commit b6014c6ffcdf830dfd0da4708664e396bb6008c1 Author: Michael Date: Thu Aug 6 18:26:45 2026 +1200 Initial commit diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..6c2dcf5 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,27 @@ +# Ships as one image: the Go binary embeds the built Svelte SPA, so this is +# the only container the app itself needs (Postgres and the OIDC provider +# already run elsewhere). + +# --- Stage 1: build the frontend --- +FROM node:20-alpine AS frontend-build +WORKDIR /frontend +COPY frontend/package.json frontend/package-lock.json* ./ +RUN npm install +COPY frontend/ ./ +RUN npm run build + +# --- Stage 2: build the Go binary, embedding the frontend build --- +FROM golang:1.25-alpine AS backend-build +WORKDIR /backend +COPY backend/go.mod backend/go.sum ./ +RUN go mod download +COPY backend/ ./ +COPY --from=frontend-build /frontend/dist/. ./cmd/server/web/ +RUN CGO_ENABLED=0 go build -o /vlog ./cmd/server + +# --- Stage 3: minimal runtime image --- +FROM alpine:3.20 +RUN apk add --no-cache ca-certificates +COPY --from=backend-build /vlog /vlog +EXPOSE 8080 +ENTRYPOINT ["/vlog"] diff --git a/backend/cmd/previewserver/embed.go b/backend/cmd/previewserver/embed.go new file mode 100644 index 0000000..5b382f1 --- /dev/null +++ b/backend/cmd/previewserver/embed.go @@ -0,0 +1,6 @@ +package main + +import "embed" + +//go:embed all:web +var frontendFS embed.FS diff --git a/backend/cmd/previewserver/main.go b/backend/cmd/previewserver/main.go new file mode 100644 index 0000000..d6f410e --- /dev/null +++ b/backend/cmd/previewserver/main.go @@ -0,0 +1,99 @@ +// Throwaway local preview server — NOT part of the real app, never +// committed. Bypasses OIDC entirely (no live provider needed for a visual +// check) by minting a session JWT directly and seeding just a user (no car +// — this drives the FULL real UI flow end-to-end, same as a real user +// would, to catch anything a direct-API test wouldn't). +package main + +import ( + "fmt" + "io/fs" + "log" + "net/http" + "os" + + "github.com/google/uuid" + + "vlog/internal/auth" + "vlog/internal/db" + "vlog/internal/handlers" + "vlog/internal/storage" +) + +func main() { + dbPath := "/tmp/vlog-preview/preview.db" + os.MkdirAll("/tmp/vlog-preview/uploads", 0o755) + os.Remove(dbPath) + + database, err := db.Connect("sqlite", dbPath) + if err != nil { + log.Fatalf("db: %v", err) + } + defer database.Close() + + store, err := storage.NewLocal("/tmp/vlog-preview/uploads") + if err != nil { + log.Fatalf("storage: %v", err) + } + + h := handlers.New(database, store, nil, "preview-secret", false) + + userID := uuid.New().String() + database.Exec(`INSERT INTO users (id, oidc_sub, email, name) VALUES (?, ?, ?, ?)`, + userID, "preview-sub", "demo@example.com", "Demo User") + + token, err := auth.MintSessionJWT("preview-secret", userID, "demo@example.com") + if err != nil { + log.Fatalf("mint jwt: %v", err) + } + fmt.Println("SESSION_TOKEN=" + token) + + mux := http.NewServeMux() + protected := http.NewServeMux() + protected.HandleFunc("GET /api/me", h.Me) + + protected.HandleFunc("GET /api/cars", h.ListCars) + protected.HandleFunc("POST /api/cars", h.CreateCar) + protected.HandleFunc("GET /api/cars/{carId}", h.GetCar) + protected.HandleFunc("PUT /api/cars/{carId}", h.UpdateCar) + protected.HandleFunc("DELETE /api/cars/{carId}", h.DeleteCar) + protected.HandleFunc("POST /api/cars/{carId}/photo", h.UploadCarPhoto) + protected.HandleFunc("GET /api/cars/{carId}/photo", h.GetCarPhoto) + protected.HandleFunc("PATCH /api/cars/{carId}/odometer", h.UpdateOdometer) + protected.HandleFunc("POST /api/cars/{carId}/share", h.GenerateShareLink) + protected.HandleFunc("DELETE /api/cars/{carId}/share", h.RevokeShareLink) + protected.HandleFunc("GET /api/cars/{carId}/mileage", h.Mileage) + + protected.HandleFunc("GET /api/cars/{carId}/service-entries", h.ListServiceEntries) + protected.HandleFunc("POST /api/cars/{carId}/service-entries", h.CreateServiceEntry) + protected.HandleFunc("GET /api/service-entries/{entryId}", h.GetServiceEntry) + protected.HandleFunc("PUT /api/service-entries/{entryId}", h.UpdateServiceEntry) + protected.HandleFunc("DELETE /api/service-entries/{entryId}", h.DeleteServiceEntry) + protected.HandleFunc("POST /api/service-entries/{entryId}/files", h.UploadServiceEntryFile) + protected.HandleFunc("GET /api/files/{fileId}", h.GetFile) + protected.HandleFunc("DELETE /api/files/{fileId}", h.DeleteFile) + + protected.HandleFunc("GET /api/cars/{carId}/reminders", h.ListReminders) + protected.HandleFunc("POST /api/cars/{carId}/reminders", h.CreateReminder) + protected.HandleFunc("PUT /api/reminders/{reminderId}", h.UpdateReminder) + protected.HandleFunc("DELETE /api/reminders/{reminderId}", h.DeleteReminder) + + protected.HandleFunc("GET /api/cars/{carId}/knowledge", h.ListKnowledge) + protected.HandleFunc("POST /api/cars/{carId}/knowledge", h.CreateKnowledge) + protected.HandleFunc("PUT /api/knowledge/{knowledgeId}", h.UpdateKnowledge) + protected.HandleFunc("DELETE /api/knowledge/{knowledgeId}", h.DeleteKnowledge) + + protected.HandleFunc("GET /api/cars/{carId}/fuel-entries", h.ListFuelEntries) + protected.HandleFunc("POST /api/cars/{carId}/fuel-entries", h.CreateFuelEntry) + protected.HandleFunc("PUT /api/fuel-entries/{entryId}", h.UpdateFuelEntry) + protected.HandleFunc("DELETE /api/fuel-entries/{entryId}", h.DeleteFuelEntry) + + protected.HandleFunc("GET /api/dashboard", h.Dashboard) + mux.Handle("/api/", auth.RequireAuth(h.JWTSecret)(protected)) + + staticFS, _ := fs.Sub(frontendFS, "web") + mux.Handle("/", http.FileServer(http.FS(staticFS))) + + log.Println("preview server on :8099") + log.Fatal(http.ListenAndServe(":8099", mux)) +} diff --git a/backend/cmd/previewserver/web/.gitkeep b/backend/cmd/previewserver/web/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/backend/cmd/previewserver/web/assets/index-CyEkKMVz.js b/backend/cmd/previewserver/web/assets/index-CyEkKMVz.js new file mode 100644 index 0000000..1deeee6 --- /dev/null +++ b/backend/cmd/previewserver/web/assets/index-CyEkKMVz.js @@ -0,0 +1,11 @@ +var ks=Object.defineProperty;var da=e=>{throw TypeError(e)};var Ss=(e,t,r)=>t in e?ks(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ne=(e,t,r)=>Ss(e,typeof t!="symbol"?t+"":t,r),$n=(e,t,r)=>t.has(e)||da("Cannot "+r);var E=(e,t,r)=>($n(e,t,"read from private field"),r?r.call(e):t.get(e)),re=(e,t,r)=>t.has(e)?da("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ae=(e,t,r,n)=>($n(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),ge=(e,t,r)=>($n(e,t,"access private method"),r);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function r(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(i){if(i.ep)return;i.ep=!0;const a=r(i);fetch(i.href,a)}})();const go=!1;var Wi=Array.isArray,Cs=Array.prototype.indexOf,Un=Array.prototype.includes,Qn=Array.from,po=Object.defineProperty,Xt=Object.getOwnPropertyDescriptor,mo=Object.getOwnPropertyDescriptors,As=Object.prototype,Ts=Array.prototype,Qi=Object.getPrototypeOf,va=Object.isExtensible;function rn(e){return typeof e=="function"}const $t=()=>{};function Is(e){return e()}function Mi(e){for(var t=0;t{e=n,t=i});return{promise:r,resolve:e,reject:t}}const qe=2,Ur=4,Cn=8,bo=1<<24,mt=16,ft=32,jt=64,Pi=128,ct=512,Fe=1024,Le=2048,bt=4096,Ye=8192,nt=16384,Wr=32768,ha=1<<25,tr=65536,Hn=1<<17,Ms=1<<18,Qr=1<<19,yo=1<<20,kt=1<<25,pr=65536,zn=1<<21,Nr=1<<22,er=1<<23,Ft=Symbol("$state"),wo=Symbol("legacy props"),Ps=Symbol(""),Dn=Symbol("attributes"),Ri=Symbol("class"),Rs=Symbol("style"),on=Symbol("text"),Bn=Symbol("form reset"),An=new class extends Error{constructor(){super(...arguments);Ne(this,"name","StaleReactionError");Ne(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};var fo;const Ns=!!((fo=globalThis.document)!=null&&fo.contentType)&&globalThis.document.contentType.includes("xml");function Ls(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function Ds(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function Bs(e,t,r){throw new Error("https://svelte.dev/e/each_key_duplicate")}function Fs(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function Os(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function qs(e){throw new Error("https://svelte.dev/e/effect_orphan")}function js(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function Us(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function Hs(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function zs(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function Vs(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function Ks(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}const Ys=1,Gs=2,xo=4,Js=8,Ws=16,Qs=1,Zs=2,Xs=4,$s=8,el=16,tl=1,rl=2,De=Symbol("uninitialized"),nl="http://www.w3.org/1999/xhtml";function il(){console.warn("https://svelte.dev/e/derived_inert")}function al(){console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function ol(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}function Eo(e){return e===this.v}function ko(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function So(e){return!ko(e,this.v)}let Zr=!1,sl=!1;function ll(){Zr=!0}let Te=null;function Hr(e){Te=e}function Se(e,t=!1,r){Te={p:Te,i:!1,c:null,e:null,s:e,x:null,r:ve,l:Zr&&!t?{s:null,u:null,$:[]}:null}}function Ce(e){var t=Te,r=t.e;if(r!==null){t.e=null;for(var n of r)Go(n)}return t.i=!0,Te=t.p,{}}function Tn(){return!Zr||Te!==null&&Te.l===null}let ar=[];function Co(){var e=ar;ar=[],Mi(e)}function St(e){if(ar.length===0&&!dn){var t=ar;queueMicrotask(()=>{t===ar&&Co()})}ar.push(e)}function ul(){for(;ar.length>0;)Co()}function Ao(e){var t=ve;if(t===null)return de.f|=er,e;if((t.f&Wr)===0&&(t.f&Ur)===0)throw e;Qt(e,t)}function Qt(e,t){if(!(t!==null&&(t.f&nt)!==0)){for(;t!==null;){if((t.f&Pi)!==0){if((t.f&Wr)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}const cl=-7169;function Me(e,t){e.f=e.f&cl|t}function Zi(e){(e.f&ct)!==0||e.deps===null?Me(e,Fe):Me(e,bt)}function To(e){if(e!==null)for(const t of e)(t.f&qe)===0||(t.f&pr)===0||(t.f^=pr,To(t.deps))}function Io(e,t,r){(e.f&Le)!==0?t.add(e):(e.f&bt)!==0&&r.add(e),To(e.deps),Me(e,Fe)}function Mo(e,t,r){if(e==null)return t(void 0),$t;const n=ir(()=>e.subscribe(t,r));return n.unsubscribe?()=>n.unsubscribe():n}const Tr=[];function fl(e,t=$t){let r=null;const n=new Set;function i(s){if(ko(e,s)&&(e=s,r)){const u=!Tr.length;for(const c of n)c[1](),Tr.push(c,e);if(u){for(let c=0;c{n.delete(c),n.size===0&&r&&(r(),r=null)}}return{set:i,update:a,subscribe:o}}function dl(e){let t;return Mo(e,r=>t=r)(),t}let Ni=!1,Rn=!1,Li=Symbol("unmounted");function vl(e,t,r){const n=r[t]??(r[t]={store:null,source:jo(void 0),unsubscribe:$t});if(n.store!==e&&!(Li in r))if(n.unsubscribe(),n.store=e??null,e==null)n.source.v=void 0,n.unsubscribe=$t;else{var i=!0;n.unsubscribe=Mo(e,a=>{i?n.source.v=a:v(n.source,a)}),i=!1}return e&&Li in r?dl(e):l(n.source)}function ga(e,t){return gl(e,t),t}function hl(){const e={};function t(){Zn(()=>{for(var r in e)e[r].unsubscribe();po(e,Li,{enumerable:!1,value:!0})})}return[e,t]}function gl(e,t){Ni=!0;try{e.set(t)}finally{Ni=!1}}function pl(e){var t=Rn;try{return Rn=!1,[e(),Rn]}finally{Rn=t}}function ml(e,t){{const r=document.body;e.autofocus=!0,St(()=>{document.activeElement===r&&e.focus()})}}let pa=!1;function _l(){pa||(pa=!0,document.addEventListener("reset",e=>{Promise.resolve().then(()=>{var t;if(!e.defaultPrevented)for(const r of e.target.elements)(t=r[Bn])==null||t.call(r)})},{capture:!0}))}function Xr(e){var t=de,r=ve;dt(null),Tt(null);try{return e()}finally{dt(t),Tt(r)}}function Xi(e,t,r,n=r){e.addEventListener(t,()=>Xr(r));const i=e[Bn];i?e[Bn]=()=>{i(),n(!0)}:e[Bn]=()=>n(!0),_l()}function bl(e){let t=0,r=_r(0),n;return()=>{na()&&(l(r),ia(()=>(t===0&&(n=ir(()=>e(()=>vn(r)))),t+=1,()=>{St(()=>{t-=1,t===0&&(n==null||n(),n=void 0,vn(r))})})))}}var yl=tr|Qr;function wl(e,t,r,n){new xl(e,t,r,n)}var ot,Ji,st,lr,We,lt,Ke,tt,Nt,ur,Jt,Lr,mn,_n,Lt,Gn,ke,El,kl,Di,Sl,Bi,Fn,On,Fi,Oi;class xl{constructor(t,r,n,i){re(this,ke);Ne(this,"parent");Ne(this,"is_pending",!1);Ne(this,"transform_error");re(this,ot);re(this,Ji,null);re(this,st);re(this,lr);re(this,We);re(this,lt,null);re(this,Ke,null);re(this,tt,null);re(this,Nt,null);re(this,ur,0);re(this,Jt,0);re(this,Lr,!1);re(this,mn,new Set);re(this,_n,new Set);re(this,Lt,null);re(this,Gn,bl(()=>(ae(this,Lt,_r(E(this,ur))),()=>{ae(this,Lt,null)})));var a;ae(this,ot,t),ae(this,st,r),ae(this,lr,o=>{var s=ve;s.b=this,s.f|=Pi,n(o)}),this.parent=ve.b,this.transform_error=i??((a=this.parent)==null?void 0:a.transform_error)??(o=>o),ae(this,We,Mn(()=>{ge(this,ke,Bi).call(this)},yl))}defer_effect(t){Io(t,E(this,mn),E(this,_n))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!E(this,st).pending}update_pending_count(t,r){ge(this,ke,Fi).call(this,t,r),ae(this,ur,E(this,ur)+t),!(!E(this,Lt)||E(this,Lr))&&(ae(this,Lr,!0),St(()=>{ae(this,Lr,!1),E(this,Lt)&&Vr(E(this,Lt),E(this,ur))}))}get_effect_pending(){return E(this,Gn).call(this),l(E(this,Lt))}error(t){if(!E(this,st).onerror&&!E(this,st).failed)throw t;W!=null&&W.is_fork?(E(this,lt)&&W.skip_effect(E(this,lt)),E(this,Ke)&&W.skip_effect(E(this,Ke)),E(this,tt)&&W.skip_effect(E(this,tt)),W.oncommit(()=>{ge(this,ke,Oi).call(this,t)})):ge(this,ke,Oi).call(this,t)}}ot=new WeakMap,Ji=new WeakMap,st=new WeakMap,lr=new WeakMap,We=new WeakMap,lt=new WeakMap,Ke=new WeakMap,tt=new WeakMap,Nt=new WeakMap,ur=new WeakMap,Jt=new WeakMap,Lr=new WeakMap,mn=new WeakMap,_n=new WeakMap,Lt=new WeakMap,Gn=new WeakMap,ke=new WeakSet,El=function(){try{ae(this,lt,ut(()=>E(this,lr).call(this,E(this,ot))))}catch(t){this.error(t)}},kl=function(t){const r=E(this,st).failed,{reset:n,invoke_onerror:i}=ge(this,ke,Di).call(this,t);St(i),r&&ae(this,tt,ut(()=>{r(E(this,ot),()=>t,()=>n)}))},Di=function(t){var r=!1,n=!1;const i=()=>{if(r){ol();return}r=!0,n&&Ks(),E(this,tt)!==null&&hr(E(this,tt),()=>{ae(this,tt,null)}),ge(this,ke,On).call(this,()=>{ge(this,ke,Bi).call(this)})};return{reset:i,invoke_onerror:()=>{var o,s;try{n=!0,(s=(o=E(this,st)).onerror)==null||s.call(o,t,i),n=!1}catch(u){Qt(u,E(this,We)&&E(this,We).parent)}}}},Sl=function(){const t=E(this,st).pending;t&&(this.is_pending=!0,ae(this,Ke,ut(()=>t(E(this,ot)))),St(()=>{var r=ae(this,Nt,document.createDocumentFragment()),n=Ot();r.append(n),ae(this,lt,ge(this,ke,On).call(this,()=>ut(()=>E(this,lr).call(this,n)))),E(this,Jt)===0&&(E(this,ot).before(r),ae(this,Nt,null),hr(E(this,Ke),()=>{ae(this,Ke,null)}),ge(this,ke,Fn).call(this,W))}))},Bi=function(){try{if(this.is_pending=this.has_pending_snippet(),ae(this,Jt,0),ae(this,ur,0),ae(this,lt,ut(()=>{E(this,lr).call(this,E(this,ot))})),E(this,Jt)>0){var t=ae(this,Nt,document.createDocumentFragment());oa(E(this,lt),t);const r=E(this,st).pending;ae(this,Ke,ut(()=>r(E(this,ot))))}else ge(this,ke,Fn).call(this,W)}catch(r){this.error(r)}},Fn=function(t){this.is_pending=!1,t.transfer_effects(E(this,mn),E(this,_n))},On=function(t){var r=ve,n=de,i=Te;Tt(E(this,We)),dt(E(this,We)),Hr(E(this,We).ctx);try{return mr.ensure(),t()}catch(a){return Ao(a),null}finally{Tt(r),dt(n),Hr(i)}},Fi=function(t,r){var n;if(!this.has_pending_snippet()){this.parent&&ge(n=this.parent,ke,Fi).call(n,t,r);return}ae(this,Jt,E(this,Jt)+t),E(this,Jt)===0&&(ge(this,ke,Fn).call(this,r),E(this,Ke)&&hr(E(this,Ke),()=>{ae(this,Ke,null)}),E(this,Nt)&&(E(this,ot).before(E(this,Nt)),ae(this,Nt,null)))},Oi=function(t){E(this,lt)&&(Xe(E(this,lt)),ae(this,lt,null)),E(this,Ke)&&(Xe(E(this,Ke)),ae(this,Ke,null)),E(this,tt)&&(Xe(E(this,tt)),ae(this,tt,null));let r=E(this,st).failed;const n=i=>{const{reset:a,invoke_onerror:o}=ge(this,ke,Di).call(this,i);o(),r&&ae(this,tt,ge(this,ke,On).call(this,()=>{try{return ut(()=>{var s=ve;s.b=this,s.f|=Pi,r(E(this,ot),()=>i,()=>a)})}catch(s){return Qt(s,E(this,We).parent),null}}))};St(()=>{var i;try{i=this.transform_error(t)}catch(a){Qt(a,E(this,We)&&E(this,We).parent);return}i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(n,a=>Qt(a,E(this,We)&&E(this,We).parent)):n(i)})};function Cl(e,t,r,n){const i=Tn()?zr:$i;var a=e.filter(g=>!g.settled),o=t.map(i);if(r.length===0&&a.length===0){n(o);return}var s=ve,u=Al(),c=a.length===1?a[0].promise:a.length>1?Promise.all(a.map(g=>g.promise)):null;function f(g){if((s.f&nt)===0){u();try{n([...o,...g])}catch(b){Qt(b,s)}Vn()}}var m=Po();if(r.length===0){c.then(()=>f([])).finally(m);return}function d(){Promise.all(r.map(g=>Tl(g))).then(f).catch(g=>Qt(g,s)).finally(m)}c?c.then(()=>{u(),d(),Vn()}):d()}function Al(){var e=ve,t=de,r=Te,n=W;return function(a=!0){Tt(e),dt(t),Hr(r),a&&(e.f&nt)===0&&(n==null||n.activate(),n==null||n.apply())}}function Vn(e=!0){Tt(null),dt(null),Hr(null),e&&(W==null||W.deactivate())}function Po(){var e=ve,t=e.b,r=W,n=!!(t!=null&&t.is_rendered());return t==null||t.update_pending_count(1,r),r.increment(n,e),()=>{t==null||t.update_pending_count(-1,r),r.decrement(n,e)}}function zr(e){var t=qe|Le;return ve!==null&&(ve.f|=Qr),{ctx:Te,deps:null,effects:null,equals:Eo,f:t,fn:e,reactions:null,rv:0,v:De,wv:0,parent:ve,ac:null}}const sn=Symbol("obsolete");function Tl(e,t,r){let n=ve;n===null&&Ds();var i=void 0,a=_r(De),o=!de,s=new Set;return Vl(()=>{var g,b;var u=ve,c=_o();i=c.promise;try{Promise.resolve(e()).then(c.resolve,C=>{C!==An&&c.reject(C)}).finally(Vn)}catch(C){c.reject(C),Vn()}var f=W;if(o){if((u.f&Wr)!==0)var m=Po();if((g=n.b)!=null&&g.is_rendered())(b=f.async_deriveds.get(u))==null||b.reject(sn);else for(const C of s.values())C.reject(sn);s.add(c),f.async_deriveds.set(u,c)}const d=(C,k=void 0)=>{m==null||m(),s.delete(c),k!==sn&&(f.activate(),k?(a.f|=er,Vr(a,k)):((a.f&er)!==0&&(a.f^=er),Vr(a,C)),f.deactivate())};c.promise.then(d,C=>d(null,C||"unknown"))}),Zn(()=>{for(const u of s)u.reject(sn)}),new Promise(u=>{function c(f){function m(){f===i?u(a):c(i)}f.then(m,m)}c(i)})}function Ct(e){const t=zr(e);return Xo(t),t}function $i(e){const t=zr(e);return t.equals=So,t}function Il(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r{r.ac.abort(An),r.ac=null}),r.fn!==null&&(r.teardown=$t),gn(r,0),aa(r))}function No(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&t.fn!==null&&Yr(t)}let ei=null,Ir=null,W=null,fn=null,je=null,qi=null,dn=!1,ti=!1,Rr=null,qn=null;var ma=0;let Pl=1;var Dr,Wt,cr,Br,Fr,Or,Dt,qr,Qe,bn,Bt,gt,xt,jr,fr,we,ji,ln,Ui,Lo,Do,Pr,Rl,un;const Jn=class Jn{constructor(){re(this,we);Ne(this,"id",Pl++);re(this,Dr,!1);Ne(this,"linked",!0);re(this,Wt,null);re(this,cr,null);Ne(this,"async_deriveds",new Map);Ne(this,"current",new Map);Ne(this,"previous",new Map);re(this,Br,new Set);re(this,Fr,new Set);re(this,Or,0);re(this,Dt,new Map);re(this,qr,null);re(this,Qe,[]);re(this,bn,[]);re(this,Bt,new Set);re(this,gt,new Set);re(this,xt,new Map);re(this,jr,new Set);Ne(this,"is_fork",!1);re(this,fr,!1);Ir===null?ei=Ir=this:(ae(Ir,cr,this),ae(this,Wt,Ir)),Ir=this}skip_effect(t){E(this,xt).has(t)||E(this,xt).set(t,{d:[],m:[]}),E(this,jr).delete(t)}unskip_effect(t,r=n=>this.schedule(n)){var n=E(this,xt).get(t);if(n){E(this,xt).delete(t);for(var i of n.d)Me(i,Le),r(i);for(i of n.m)Me(i,bt),r(i)}E(this,jr).add(t)}capture(t,r,n=!1){t.v!==De&&!this.previous.has(t)&&this.previous.set(t,t.v),(t.f&er)===0&&(this.current.set(t,[r,n]),je==null||je.set(t,r)),this.is_fork||(t.v=r)}activate(){W=this}deactivate(){W=null,je=null}flush(){try{ti=!0,W=this,ge(this,we,ln).call(this)}finally{ma=0,qi=null,Rr=null,qn=null,ti=!1,W=null,je=null,vr.clear()}}discard(){var t;for(const r of E(this,Fr))r(this);E(this,Fr).clear();for(const r of this.async_deriveds.values())r.reject(sn);ge(this,we,un).call(this),(t=E(this,qr))==null||t.resolve()}register_created_effect(t){E(this,bn).push(t)}increment(t,r){if(ae(this,Or,E(this,Or)+1),t){let n=E(this,Dt).get(r)??0;E(this,Dt).set(r,n+1)}}decrement(t,r){if(ae(this,Or,E(this,Or)-1),t){let n=E(this,Dt).get(r)??0;n===1?E(this,Dt).delete(r):E(this,Dt).set(r,n-1)}E(this,fr)||(ae(this,fr,!0),St(()=>{ae(this,fr,!1),this.linked&&this.flush()}))}transfer_effects(t,r){for(const n of t)E(this,Bt).add(n);for(const n of r)E(this,gt).add(n);t.clear(),r.clear()}oncommit(t){E(this,Br).add(t)}ondiscard(t){E(this,Fr).add(t)}settled(){return(E(this,qr)??ae(this,qr,_o())).promise}static ensure(){if(W===null){const t=W=new Jn;!ti&&!dn&&St(()=>{E(t,Dr)||t.flush()})}return W}apply(){{je=null;return}}schedule(t){var i;if(qi=t,(i=t.b)!=null&&i.is_pending&&(t.f&(Ur|Cn|bo))!==0&&(t.f&Wr)===0){t.b.defer_effect(t);return}for(var r=t;r.parent!==null;){r=r.parent;var n=r.f;if(Rr!==null&&r===ve&&(de===null||(de.f&qe)===0)&&!Ni)return;if((n&(jt|ft))!==0){if((n&Fe)===0)return;r.f^=Fe}}E(this,Qe).push(r)}};Dr=new WeakMap,Wt=new WeakMap,cr=new WeakMap,Br=new WeakMap,Fr=new WeakMap,Or=new WeakMap,Dt=new WeakMap,qr=new WeakMap,Qe=new WeakMap,bn=new WeakMap,Bt=new WeakMap,gt=new WeakMap,xt=new WeakMap,jr=new WeakMap,fr=new WeakMap,we=new WeakSet,ji=function(){if(this.is_fork)return!0;for(const n of E(this,Dt).keys()){for(var t=n,r=!1;t.parent!==null;){if(E(this,xt).has(t)){r=!0;break}t=t.parent}if(!r)return!0}return!1},ln=function(){var u,c,f,m;ae(this,Dr,!0),ma++>1e3&&(ge(this,we,un).call(this),Ll());for(const d of E(this,Bt))E(this,gt).delete(d),Me(d,Le),this.schedule(d);for(const d of E(this,gt))Me(d,bt),this.schedule(d);const t=E(this,Qe);ae(this,Qe,[]),this.apply();var r=Rr=[],n=[],i=qn=[];for(const d of t)try{ge(this,we,Ui).call(this,d,r,n)}catch(g){throw Oo(d),ge(this,we,ji).call(this)||this.discard(),g}if(W=null,i.length>0){var a=Jn.ensure();for(const d of i)a.schedule(d)}if(Rr=null,qn=null,ge(this,we,ji).call(this)){ge(this,we,Pr).call(this,n),ge(this,we,Pr).call(this,r);for(const[d,g]of E(this,xt))Fo(d,g);i.length>0&&ge(u=W,we,ln).call(u);return}const o=ge(this,we,Lo).call(this);if(o){ge(this,we,Pr).call(this,n),ge(this,we,Pr).call(this,r),ge(c=o,we,Do).call(c,this);return}E(this,Bt).clear(),E(this,gt).clear();for(const d of E(this,Br))d(this);E(this,Br).clear(),fn=this,_a(n),_a(r),fn=null,(f=E(this,qr))==null||f.resolve();var s=W;if(E(this,Or)===0&&(E(this,Qe).length===0||s!==null)&&ge(this,we,un).call(this),E(this,Qe).length>0)if(s!==null){const d=s;E(d,Qe).push(...E(this,Qe).filter(g=>!E(d,Qe).includes(g)))}else s=this;s!==null&&ge(m=s,we,ln).call(m)},Ui=function(t,r,n){t.f^=Fe;for(var i=t.first;i!==null;){var a=i.f,o=(a&(ft|jt))!==0,s=o&&(a&Fe)!==0,u=s||(a&Ye)!==0||E(this,xt).has(i);if(!u&&i.fn!==null){o?i.f^=Fe:(a&Ur)!==0?r.push(i):Pn(i)&&((a&mt)!==0&&E(this,gt).add(i),Yr(i));var c=i.first;if(c!==null){i=c;continue}}for(;i!==null;){var f=i.next;if(f!==null){i=f;break}i=i.parent}}},Lo=function(){for(var t=E(this,Wt);t!==null;){if(!t.is_fork){for(const[r,[,n]]of this.current)if(t.current.has(r)&&!n)return t}t=E(t,Wt)}return null},Do=function(t){var n;for(const[i,a]of t.current)!this.previous.has(i)&&t.previous.has(i)&&this.previous.set(i,t.previous.get(i)),this.current.set(i,a);for(const[i,a]of t.async_deriveds){const o=this.async_deriveds.get(i);o&&a.promise.then(o.resolve).catch(o.reject)}t.async_deriveds.clear(),this.transfer_effects(E(t,Bt),E(t,gt));const r=i=>{var a=i.reactions;if(a!==null&&!((i.f&qe)!==0&&(i.f&(Le|bt))===0))for(const u of a){var o=u.f;if((o&qe)!==0)r(u);else{var s=u;o&(Nr|mt)&&!this.async_deriveds.has(s)&&(E(this,gt).delete(s),Me(s,Le),this.schedule(s))}}};for(const i of this.current.keys())r(i);this.oncommit(()=>t.discard()),ge(n=t,we,un).call(n),W=this,ge(this,we,ln).call(this)},Pr=function(t){for(var r=0;r!d.current.get(g)[1]);if(!(!E(d,Dr)||i.length===0)){var a=i.filter(g=>!this.current.has(g));if(a.length===0)t&&d.discard();else if(r.length>0){if(t)for(const g of E(this,jr))d.unskip_effect(g,b=>{var C;(b.f&(mt|Nr))!==0?d.schedule(b):ge(C=d,we,Pr).call(C,[b])});d.activate();var o=new Set,s=new Map;for(var u of r)Bo(u,a,o,s);s=new Map;var c=[...d.current].filter(([g,b])=>{const C=this.current.get(g);return C?C[0]!==b[0]||C[1]!==b[1]:!0}).map(([g])=>g);if(c.length>0)for(const g of E(this,bn))(g.f&(nt|Ye|Hn))===0&&ta(g,c,s)&&((g.f&(Nr|mt))!==0?(Me(g,Le),d.schedule(g)):E(d,Bt).add(g));if(E(d,Qe).length>0&&!E(d,fr)){d.apply();for(var f of E(d,Qe))ge(m=d,we,Ui).call(m,f,[],[]);ae(d,Qe,[])}d.deactivate()}}}},un=function(){if(this.linked){var t=E(this,Wt),r=E(this,cr);t===null?ei=r:ae(t,cr,r),r===null?Ir=t:ae(r,Wt,t),this.linked=!1}};let mr=Jn;function Nl(e){var t=dn;dn=!0;try{for(var r;;){if(ul(),W===null)return r;W.flush()}}finally{dn=t}}function Ll(){try{js()}catch(e){Qt(e,qi)}}let ht=null;function _a(e){var t=e.length;if(t!==0){for(var r=0;r0)){vr.clear();for(const i of ht){if((i.f&(nt|Ye))!==0)continue;const a=[i];let o=i.parent;for(;o!==null;)ht.has(o)&&(ht.delete(o),a.push(o)),o=o.parent;for(let s=a.length-1;s>=0;s--){const u=a[s];(u.f&(nt|Ye))===0&&Yr(u)}}ht.clear()}}ht=null}}function Bo(e,t,r,n){if(!r.has(e)&&(r.add(e),e.reactions!==null))for(const i of e.reactions){const a=i.f;(a&qe)!==0?Bo(i,t,r,n):(a&(Nr|mt))!==0&&(a&Le)===0&&ta(i,t,n)&&(Me(i,Le),ra(i))}}function ta(e,t,r){const n=r.get(e);if(n!==void 0)return n;if(e.deps!==null)for(const i of e.deps){if(Un.call(t,i))return!0;if((i.f&qe)!==0&&ta(i,t,r))return r.set(i,!0),!0}return r.set(e,!1),!1}function ra(e){W.schedule(e)}function Fo(e,t){if(!((e.f&ft)!==0&&(e.f&Fe)!==0)){(e.f&Le)!==0?t.d.push(e):(e.f&bt)!==0&&t.m.push(e),Me(e,Fe);for(var r=e.first;r!==null;)Fo(r,t),r=r.next}}function Oo(e){Me(e,Fe);for(var t=e.first;t!==null;)Oo(t),t=t.next}let Kn=new Set;const vr=new Map;let qo=!1;function _r(e,t){var r={f:0,v:e,reactions:null,equals:Eo,rv:0,wv:0};return r}function B(e,t){const r=_r(e);return Xo(r),r}function jo(e,t=!1,r=!0){var i;const n=_r(e);return t||(n.equals=So),Zr&&r&&Te!==null&&Te.l!==null&&((i=Te.l).s??(i.s=[])).push(n),n}function v(e,t,r=!1){de!==null&&(!_t||(de.f&Hn)!==0)&&Tn()&&(de.f&(qe|mt|Nr|Hn))!==0&&(At===null||!At.has(e))&&Vs();let n=r?ne(t):t;return Vr(e,n,qn)}function Vr(e,t,r=null){if(!e.equals(t)){vr.set(e,Ut?t:e.v);var n=mr.ensure();if(n.capture(e,t),(e.f&qe)!==0){const i=e;(e.f&Le)!==0&&ea(i),je===null&&Zi(i)}e.wv=es(),Uo(e,Le,r),Tn()&&ve!==null&&(ve.f&Fe)!==0&&(ve.f&(ft|jt))===0&&(at===null?Gl([e]):at.push(e)),!n.is_fork&&Kn.size>0&&!qo&&Dl()}return t}function Dl(){qo=!1;for(const e of Kn){(e.f&Fe)!==0&&Me(e,bt);let t;try{t=Pn(e)}catch{t=!0}t&&Yr(e)}Kn.clear()}function vn(e){v(e,e.v+1)}function Uo(e,t,r){var n=e.reactions;if(n!==null)for(var i=Tn(),a=n.length,o=0;o{if(gr===a)return s();var u=de,c=gr;dt(null),wa(a);var f=s();return dt(u),wa(c),f};return n&&r.set("length",B(e.length)),new Proxy(e,{defineProperty(s,u,c){(!("value"in c)||c.configurable===!1||c.enumerable===!1||c.writable===!1)&&Hs();var f=r.get(u);return f===void 0?o(()=>{var m=B(c.value);return r.set(u,m),m}):v(f,c.value,!0),!0},deleteProperty(s,u){var c=r.get(u);if(c===void 0){if(u in s){const f=o(()=>B(De));r.set(u,f),vn(i)}}else v(c,De),vn(i);return!0},get(s,u,c){var g;if(u===Ft)return e;var f=r.get(u),m=u in s;if(f===void 0&&(!m||(g=Xt(s,u))!=null&&g.writable)&&(f=o(()=>{var b=ne(m?s[u]:De),C=B(b);return C}),r.set(u,f)),f!==void 0){var d=l(f);return d===De?void 0:d}return Reflect.get(s,u,c)},getOwnPropertyDescriptor(s,u){var c=Reflect.getOwnPropertyDescriptor(s,u);if(c&&"value"in c){var f=r.get(u);f&&(c.value=l(f))}else if(c===void 0){var m=r.get(u),d=m==null?void 0:m.v;if(m!==void 0&&d!==De)return{enumerable:!0,configurable:!0,value:d,writable:!0}}return c},has(s,u){var d;if(u===Ft)return!0;var c=r.get(u),f=c!==void 0&&c.v!==De||Reflect.has(s,u);if(c!==void 0||ve!==null&&(!f||(d=Xt(s,u))!=null&&d.writable)){c===void 0&&(c=o(()=>{var g=f?ne(s[u]):De,b=B(g);return b}),r.set(u,c));var m=l(c);if(m===De)return!1}return f},set(s,u,c,f){var M;var m=r.get(u),d=u in s;if(n&&u==="length")for(var g=c;gB(De)),r.set(g+"",b))}if(m===void 0)(!d||(M=Xt(s,u))!=null&&M.writable)&&(m=o(()=>B(void 0)),v(m,ne(c)),r.set(u,m));else{d=m.v!==De;var C=o(()=>ne(c));v(m,C)}var k=Reflect.getOwnPropertyDescriptor(s,u);if(k!=null&&k.set&&k.set.call(f,c),!d){if(n&&typeof u=="string"){var S=r.get("length"),I=Number(u);Number.isInteger(I)&&I>=S.v&&v(S,I+1)}vn(i)}return!0},ownKeys(s){l(i);var u=Reflect.ownKeys(s).filter(m=>{var d=r.get(m);return d===void 0||d.v!==De});for(var[c,f]of r)f.v!==De&&!(c in s)&&u.push(c);return u},setPrototypeOf(){zs()}})}function ba(e){try{if(e!==null&&typeof e=="object"&&Ft in e)return e[Ft]}catch{}return e}function Bl(e,t){return Object.is(ba(e),ba(t))}var Hi,Ho,zo,Vo;function Fl(){if(Hi===void 0){Hi=window,Ho=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;zo=Xt(t,"firstChild").get,Vo=Xt(t,"nextSibling").get,va(e)&&(e[Ri]=void 0,e[Dn]=null,e[Rs]=void 0,e.__e=void 0),va(r)&&(r[on]=void 0)}}function Ot(e=""){return document.createTextNode(e)}function Kr(e){return zo.call(e)}function In(e){return Vo.call(e)}function h(e,t){return Kr(e)}function Pe(e,t=!1){{var r=Kr(e);return r instanceof Comment&&r.data===""?In(r):r}}function _(e,t=1,r=!1){let n=e;for(;t--;)n=In(n);return n}function Ol(e){e.textContent=""}function Ko(){return!1}function ql(e,t,r){return r?document.createElement(e,{is:r}):document.createElement(e)}function Yo(e){ve===null&&(de===null&&qs(),Os()),Ut&&Fs()}function jl(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function Mt(e,t){var r=ve;r!==null&&(r.f&Ye)!==0&&(e|=Ye);var n={ctx:Te,deps:null,nodes:null,f:e|Le|ct,first:null,fn:t,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};W==null||W.register_created_effect(n);var i=n;if((e&Ur)!==0)Rr!==null?Rr.push(n):mr.ensure().schedule(n);else if(t!==null){try{Yr(n)}catch(o){throw Xe(n),o}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&(i.f&Qr)===0&&(i=i.first,(e&mt)!==0&&(e&tr)!==0&&i!==null&&(i.f|=tr))}if(i!==null&&(i.parent=r,r!==null&&jl(i,r),de!==null&&(de.f&qe)!==0&&(e&jt)===0)){var a=de;(a.effects??(a.effects=[])).push(i)}return n}function na(){return de!==null&&!_t}function Zn(e){const t=Mt(Cn,null);return Me(t,Fe),t.teardown=e,t}function it(e){Yo();var t=ve.f,r=!de&&(t&ft)!==0&&Te!==null&&!Te.i;if(r){var n=Te;(n.e??(n.e=[])).push(e)}else return Go(e)}function Go(e){return Mt(Ur|yo,e)}function Ul(e){return Yo(),Mt(Cn|yo,e)}function Hl(e){mr.ensure();const t=Mt(jt|Qr,e);return(r={})=>new Promise(n=>{r.outro?hr(t,()=>{Xe(t),n(void 0)}):(Xe(t),n(void 0))})}function zl(e){return Mt(Ur,e)}function Vl(e){return Mt(Nr|Qr,e)}function ia(e,t=0){return Mt(Cn|t,e)}function U(e,t=[],r=[],n=[]){Cl(n,t,r,i=>{Mt(Cn,()=>{e(...i.map(l))})})}function Mn(e,t=0){var r=Mt(mt|t,e);return r}function ut(e){return Mt(ft|Qr,e)}function Jo(e){var t=e.teardown;if(t!==null){const r=Ut,n=de;ya(!0),dt(null);try{t.call(null)}finally{ya(r),dt(n)}}}function aa(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){const i=r.ac;i!==null&&Xr(()=>{i.abort(An)});var n=r.next;(r.f&jt)!==0?r.parent=null:Xe(r,t),r=n}}function Kl(e){for(var t=e.first;t!==null;){var r=t.next;(t.f&ft)===0&&Xe(t),t=r}}function Xe(e,t=!0){var r=!1;(t||(e.f&Ms)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(Yl(e.nodes.start,e.nodes.end),r=!0),e.f|=ha,aa(e,t&&!r),gn(e,0);var n=e.nodes&&e.nodes.t;if(n!==null)for(const a of n)a.stop();Jo(e),e.f^=ha,e.f|=nt;var i=e.parent;i!==null&&i.first!==null&&Wo(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function Yl(e,t){for(;e!==null;){var r=e===t?null:In(e);e.remove(),e=r}}function Wo(e){var t=e.parent,r=e.prev,n=e.next;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function hr(e,t,r=!0){var n=[];Qo(e,n,!0);var i=()=>{r&&Xe(e),t&&t()},a=n.length;if(a>0){var o=()=>--a||i();for(var s of n)s.out(o)}else i()}function Qo(e,t,r){if((e.f&Ye)===0){e.f^=Ye;var n=e.nodes&&e.nodes.t;if(n!==null)for(const s of n)(s.is_global||r)&&t.push(s);for(var i=e.first;i!==null;){var a=i.next;if((i.f&jt)===0){var o=(i.f&tr)!==0||(i.f&ft)!==0&&(e.f&mt)!==0;Qo(i,t,o?r:!1)}i=a}}}function Yn(e){Zo(e,!0)}function Zo(e,t){if((e.f&Ye)!==0){e.f^=Ye,(e.f&Fe)===0&&(Me(e,Le),mr.ensure().schedule(e));for(var r=e.first;r!==null;){var n=r.next,i=(r.f&tr)!==0||(r.f&ft)!==0;Zo(r,i?t:!1),r=n}var a=e.nodes&&e.nodes.t;if(a!==null)for(const o of a)(o.is_global||t)&&o.in()}}function oa(e,t){if(e.nodes)for(var r=e.nodes.start,n=e.nodes.end;r!==null;){var i=r===n?null:In(r);t.append(r),r=i}}let jn=!1,Ut=!1;function ya(e){Ut=e}let de=null,_t=!1;function dt(e){de=e}let ve=null;function Tt(e){ve=e}let At=null;function Xo(e){de!==null&&(At??(At=new Set)).add(e)}let Ze=null,et=0,at=null;function Gl(e){at=e}let $o=1,or=0,gr=or;function wa(e){gr=e}function es(){return++$o}function Pn(e){var t=e.f;if((t&Le)!==0)return!0;if(t&qe&&(e.f&=~pr),(t&bt)!==0){for(var r=e.deps,n=r.length,i=0;ie.wv)return!0}(t&ct)!==0&&je===null&&Me(e,Fe)}return!1}function ts(e,t,r=!0){var n=e.reactions;if(n!==null&&!(At!==null&&At.has(e)))for(var i=0;i{e.ac.abort(An)}),e.ac=null);try{e.f|=zn;var f=e.fn,m=f();e.f|=Wr;var d=e.deps,g=W==null?void 0:W.is_fork;if(Ze!==null){var b;if(g||gn(e,et),d!==null&&et>0)for(d.length=et+Ze.length,b=0;b{a.ac.abort(An),a.ac=null,Me(a,Le)}),Ml(a),gn(a,0)}}function gn(e,t){var r=e.deps;if(r!==null)for(var n=t;nr==null?void 0:r.call(this,a))}return e.startsWith("pointer")||e.startsWith("touch")||e==="wheel"?St(()=>{t.addEventListener(e,i,n)}):t.addEventListener(e,i,n),i}function br(e,t,r,n,i){var a={capture:n,passive:i},o=Xl(e,t,r,a);(t===document.body||t===window||t===document||t instanceof HTMLMediaElement)&&Zn(()=>{t.removeEventListener(e,o,a)})}function se(e,t,r){(t[sr]??(t[sr]={}))[e]=r}function ze(e){for(var t=0;t{throw S});throw d}}finally{e[sr]=t,delete e.currentTarget,dt(f),Tt(m)}}}var vo;const ri=((vo=globalThis==null?void 0:globalThis.window)==null?void 0:vo.trustedTypes)&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function $l(e){return(ri==null?void 0:ri.createHTML(e))??e}function os(e){var t=ql("template");return t.innerHTML=$l(e.replaceAll("","")),t.content}function pn(e,t){var r=ve;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function q(e,t){var r=(t&tl)!==0,n=(t&rl)!==0,i,a=!e.startsWith("");return()=>{i===void 0&&(i=os(a?e:""+e),r||(i=Kr(i)));var o=n||Ho?document.importNode(i,!0):i.cloneNode(!0);if(r){var s=Kr(o),u=o.lastChild;pn(s,u)}else pn(o,o);return o}}function eu(e,t,r="svg"){var n=!e.startsWith(""),i=`<${r}>${n?e:""+e}`,a;return()=>{if(!a){var o=os(i),s=Kr(o);a=Kr(s)}var u=a.cloneNode(!0);return pn(u,u),u}}function ss(e,t){return eu(e,t,"svg")}function Gr(e=""){{var t=Ot(e+"");return pn(t,t),t}}function Zt(){var e=document.createDocumentFragment(),t=document.createComment(""),r=Ot();return e.append(t,r),pn(t,r),e}function L(e,t){e!==null&&e.before(t)}function z(e,t){var r=t==null?"":typeof t=="object"?`${t}`:t;r!==(e[on]??(e[on]=e.nodeValue))&&(e[on]=r,e.nodeValue=`${r}`)}function tu(e,t){return ru(e,t)}const Nn=new Map;function ru(e,{target:t,anchor:r,props:n={},events:i,context:a,intro:o=!0,transformError:s}){Fl();var u=void 0,c=Hl(()=>{var f=r??t.appendChild(Ot());wl(f,{pending:()=>{}},g=>{Se({});var b=Te;a&&(b.c=a),i&&(n.$$events=i),u=e(g,n)||{},Ce()},s);var m=new Set,d=g=>{for(var b=0;b{var k;for(var g of m)for(const S of[t,document]){var b=Nn.get(S),C=b.get(g);--C==0?(S.removeEventListener(g,Ki),b.delete(g),b.size===0&&Nn.delete(S)):b.set(g,C)}Vi.delete(d),f!==r&&((k=f.parentNode)==null||k.removeChild(f))}});return nu.set(u,c),u}let nu=new WeakMap;var pt,Et,rt,dr,yn,wn,Wn;class la{constructor(t,r=!0){Ne(this,"anchor");re(this,pt,new Map);re(this,Et,new Map);re(this,rt,new Map);re(this,dr,new Set);re(this,yn,!0);re(this,wn,t=>{if(E(this,pt).has(t)){var r=E(this,pt).get(t),n=E(this,Et).get(r);if(n)Yn(n),E(this,dr).delete(r);else{var i=E(this,rt).get(r);i&&(Yn(i.effect),E(this,Et).set(r,i.effect),E(this,rt).delete(r),i.fragment.lastChild.remove(),this.anchor.before(i.fragment),n=i.effect)}for(const[a,o]of E(this,pt)){if(E(this,pt).delete(a),a===t)break;const s=E(this,rt).get(o);s&&(Xe(s.effect),E(this,rt).delete(o))}for(const[a,o]of E(this,Et)){if(a===r||E(this,dr).has(a))continue;const s=()=>{if(Array.from(E(this,pt).values()).includes(a)){var c=document.createDocumentFragment();oa(o,c),c.append(Ot()),E(this,rt).set(a,{effect:o,fragment:c})}else Xe(o);E(this,dr).delete(a),E(this,Et).delete(a)};E(this,yn)||!n?(E(this,dr).add(a),hr(o,s,!1)):s()}}});re(this,Wn,t=>{E(this,pt).delete(t);const r=Array.from(E(this,pt).values());for(const[n,i]of E(this,rt))r.includes(n)||(Xe(i.effect),E(this,rt).delete(n))});this.anchor=t,ae(this,yn,r)}ensure(t,r){var n=W,i=Ko();if(r&&!E(this,Et).has(t)&&!E(this,rt).has(t))if(i){var a=document.createDocumentFragment(),o=Ot();a.append(o),E(this,rt).set(t,{effect:ut(()=>r(o)),fragment:a})}else E(this,Et).set(t,ut(()=>r(this.anchor)));if(E(this,pt).set(n,t),i){for(const[s,u]of E(this,Et))s===t?n.unskip_effect(u):n.skip_effect(u);for(const[s,u]of E(this,rt))s===t?n.unskip_effect(u.effect):n.skip_effect(u.effect);n.oncommit(E(this,wn)),n.ondiscard(E(this,Wn))}else E(this,wn).call(this,n)}}pt=new WeakMap,Et=new WeakMap,rt=new WeakMap,dr=new WeakMap,yn=new WeakMap,wn=new WeakMap,Wn=new WeakMap;function V(e,t,r=!1){var n=new la(e),i=r?tr:0;function a(o,s){n.ensure(o,s)}Mn(()=>{var o=!1;t((s,u=0)=>{o=!0,a(u,s)}),o||a(-1,null)},i)}function iu(e,t,r){for(var n=[],i=t.length,a,o=t.length,s=0;s{if(a){if(a.pending.delete(m),a.done.add(m),a.pending.size===0){var d=e.outrogroups;Yi(e,Qn(a.done)),d.delete(a),d.size===0&&(e.outrogroups=null)}}else o-=1},!1)}if(o===0){var u=n.length===0&&r!==null;if(u){var c=r,f=c.parentNode;Ol(f),f.append(c),e.items.clear()}Yi(e,t,!u)}else a={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(a)}function Yi(e,t,r=!0){var n;if(e.pending.size>0){n=new Set;for(const o of e.pending.values())for(const s of o)n.add(e.items.get(s).e)}for(var i=0;i{var M=r();return Wi(M)?M:M==null?[]:Qn(M)}),d,g=new Map,b=!0;function C(M){(I.effect.f&nt)===0&&(I.pending.delete(M),I.fallback=f,au(I,d,o,t,n),f!==null&&(d.length===0?(f.f&kt)===0?Yn(f):(f.f^=kt,cn(f,null,o)):hr(f,()=>{f=null})))}function k(M){I.pending.delete(M)}var S=Mn(()=>{d=l(m);for(var M=d.length,R=new Set,A=W,p=Ko(),x=0;xa(o)):(f=ut(()=>a(Ea??(Ea=Ot()))),f.f|=kt)),M>R.size&&Bs(),!b)if(g.set(A,R),p){for(const[T,N]of s)R.has(T)||A.skip_effect(N.e);A.oncommit(C),A.ondiscard(k)}else C(A);l(m)}),I={effect:S,items:s,pending:g,outrogroups:null,fallback:f};b=!1}function nn(e){for(;e!==null&&(e.f&ft)===0;)e=e.next;return e}function au(e,t,r,n,i){var w,T,N,F,P,H,G,Q,oe;var a=(n&Js)!==0,o=t.length,s=e.items,u=nn(e.effect.first),c,f=null,m,d=[],g=[],b,C,k,S;if(a)for(S=0;S0){var y=(n&xo)!==0&&o===0?r:null;if(a){for(S=0;S{var X,J;if(m!==void 0)for(k of m)(J=(X=k.nodes)==null?void 0:X.a)==null||J.apply()})}function ou(e,t,r,n,i,a,o,s){var u=(o&Ys)!==0?(o&Ws)===0?jo(r,!1,!1):_r(r):null,c=(o&Gs)!==0?_r(i):null;return{v:u,i:c,e:ut(()=>(a(t,u??r,c??i,s),()=>{e.delete(n)}))}}function cn(e,t,r){if(e.nodes)for(var n=e.nodes.start,i=e.nodes.end,a=t&&(t.f&kt)===0?t.nodes.start:r;n!==null;){var o=In(n);if(a.before(n),n===i)return;n=o}}function Yt(e,t,r){t===null?e.effect.first=r:t.next=r,r===null?e.effect.last=t:r.prev=t}function su(e,t,...r){var n=new la(e);Mn(()=>{const i=t()??null;n.ensure(i,i&&(a=>i(a,...r)))},tr)}function ka(e,t,r){var n=new la(e);Mn(()=>{var i=t()??null;n.ensure(i,i&&(a=>r(a,i)))},tr)}function ls(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{"__value"in e&&us(e,e.__value)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),Zn(()=>{t.disconnect()})}function fu(e,t,r=t){var n=new WeakSet,i=!0;Xi(e,"change",a=>{var o=a?"[selected]":":checked",s;if(e.multiple)s=[].map.call(e.querySelectorAll(o),hn);else{var u=e.querySelector(o)??e.querySelector("option:not([disabled])");s=u&&hn(u)}r(s),e.__value=s,W!==null&&n.add(W)}),zl(()=>{var a=t();if(e===document.activeElement){var o=W;if(n.has(o))return}if(us(e,a,i),i&&a===void 0){var s=e.querySelector(":checked");s!==null&&(a=hn(s),r(a))}e.__value=a,i=!1}),cu(e)}function hn(e){return"__value"in e?e.__value:e.value}const du=Symbol("is custom element"),vu=Symbol("is html"),hu=Ns?"progress":"PROGRESS";function gu(e,t){var r=cs(e);r.value===(r.value=t??void 0)||e.value===t&&(t!==0||e.nodeName!==hu)||(e.value=t??"")}function Ge(e,t,r,n){var i=cs(e);i[t]!==(i[t]=r)&&(t==="loading"&&(e[Ps]=r),r==null?e.removeAttribute(t):typeof r!="string"&&pu(e).includes(t)?e[t]=r:e.setAttribute(t,r))}function cs(e){return e[Dn]??(e[Dn]={[du]:e.nodeName.includes("-"),[vu]:e.namespaceURI===nl})}var Sa=new Map;function pu(e){var t=e.getAttribute("is")||e.nodeName,r=Sa.get(t);if(r)return r;Sa.set(t,r=[]);for(var n,i=e,a=Element.prototype;a!==i;){n=mo(i);for(var o in n)n[o].set&&o!=="innerHTML"&&o!=="textContent"&&o!=="innerText"&&r.push(o);i=Qi(i)}return r}function Ee(e,t,r=t){var n=new WeakSet;Xi(e,"input",async i=>{var a=i?e.defaultValue:e.value;if(a=ni(e)?ii(a):a,r(a),W!==null&&n.add(W),await sa(),a!==(a=t())){var o=e.selectionStart,s=e.selectionEnd,u=e.value.length;if(e.value=a??"",s!==null){var c=e.value.length;o===s&&s===u&&c>u?(e.selectionStart=c,e.selectionEnd=c):(e.selectionStart=o,e.selectionEnd=Math.min(s,c))}}}),ir(t)==null&&e.value&&(r(ni(e)?ii(e.value):e.value),W!==null&&n.add(W)),ia(()=>{var i=t();if(e===document.activeElement){var a=W;if(n.has(a))return}ni(e)&&i===ii(e.value)||e.type==="date"&&!i&&!e.value||i!==e.value&&(e.value=i??"")})}function mu(e,t,r=t){Xi(e,"change",n=>{var i=n?e.defaultChecked:e.checked;r(i)}),ir(t)==null&&r(e.checked),ia(()=>{var n=t();e.checked=!!n})}function ni(e){var t=e.type;return t==="number"||t==="range"}function ii(e){return e===""?null:+e}function _u(e=!1){const t=Te,r=t.l.u;if(!r)return;let n=()=>Wl(t.s);if(e){let i=0,a={};const o=zr(()=>{let s=!1;const u=t.s;for(const c in u)u[c]!==a[c]&&(a[c]=u[c],s=!0);return s&&i++,i});n=()=>l(o)}r.b.length&&Ul(()=>{Ca(t,n),Mi(r.b)}),it(()=>{const i=ir(()=>r.m.map(Is));return()=>{for(const a of i)typeof a=="function"&&a()}}),r.a.length&&it(()=>{Ca(t,n),Mi(r.a)})}function Ca(e,t){if(e.l.s)for(const r of e.l.s)l(r);t()}const bu={get(e,t){let r=e.props.length;for(;r--;){let n=e.props[r];if(rn(n)&&(n=n()),typeof n=="object"&&n!==null&&t in n)return n[t]}},set(e,t,r){let n=e.props.length;for(;n--;){let i=e.props[n];rn(i)&&(i=i());const a=Xt(i,t);if(a&&a.set)return a.set(r),!0}return!1},getOwnPropertyDescriptor(e,t){let r=e.props.length;for(;r--;){let n=e.props[r];if(rn(n)&&(n=n()),typeof n=="object"&&n!==null&&t in n){const i=Xt(n,t);return i&&!i.configurable&&(i.configurable=!0),i}}},has(e,t){if(t===Ft||t===wo)return!1;for(let r of e.props)if(rn(r)&&(r=r()),r!=null&&t in r)return!0;return!1},ownKeys(e){const t=[];for(let r of e.props)if(rn(r)&&(r=r()),!!r){for(const n in r)t.includes(n)||t.push(n);for(const n of Object.getOwnPropertySymbols(r))t.includes(n)||t.push(n)}return t}};function Aa(...e){return new Proxy({props:e},bu)}function Be(e,t,r,n){var R;var i=!Zr||(r&Zs)!==0,a=(r&$s)!==0,o=(r&el)!==0,s=n,u=!0,c=void 0,f=()=>o&&i?(c??(c=zr(n)),l(c)):(u&&(u=!1,s=o?ir(n):n),s);let m;if(a){var d=Ft in e||wo in e;m=((R=Xt(e,t))==null?void 0:R.set)??(d&&t in e?A=>e[t]=A:void 0)}var g,b=!1;a?[g,b]=pl(()=>e[t]):g=e[t],g===void 0&&n!==void 0&&(g=f(),m&&(i&&Us(),m(g)));var C;if(i?C=()=>{var A=e[t];return A===void 0?f():(u=!0,A)}:C=()=>{var A=e[t];return A!==void 0&&(s=void 0),A===void 0?s:A},i&&(r&Xs)===0)return C;if(m){var k=e.$$legacy;return(function(A,p){return arguments.length>0?((!i||!p||k||b)&&m(p?C():A),A):C()})}var S=!1,I=((r&Qs)!==0?zr:$i)(()=>(S=!1,C()));a&&l(I);var M=ve;return(function(A,p){if(arguments.length>0){const x=p?l(I):i&&a?ne(A):A;return v(I,x),S=!0,s!==void 0&&(s=x),A}return Ut&&S||(M.f&nt)!==0?I.v:l(I)})}function fs(e){Te===null&&Ls(),Zr&&Te.l!==null?yu(Te).m.push(e):it(()=>{const t=ir(e);if(typeof t=="function")return t})}function yu(e){var t=e.l;return t.u??(t.u={a:[],b:[],m:[]})}const wu="5";var ho;typeof window<"u"&&((ho=window.__svelte??(window.__svelte={})).v??(ho.v=new Set)).add(wu);function Ta(e,t){if(e instanceof RegExp)return{keys:!1,pattern:e};var r,n,i,a,o=[],s="",u=e.split("/");for(u[0]||u.shift();i=u.shift();)r=i[0],r==="*"?(o.push("wild"),s+="/(.*)"):r===":"?(n=i.indexOf("?",1),a=i.indexOf(".",1),o.push(i.substring(1,~n?n:~a?a:i.length)),s+=~n&&!~a?"(?:/([^/]+?))?":"/([^/]+?)",~a&&(s+=(~n?"?":"")+"\\"+i.substring(a))):s+="/"+i;return{keys:o,pattern:new RegExp("^"+s+"/?$","i")}}var xn,En,kn,Sn;class xu{constructor(){re(this,xn,B(Ia()));re(this,En,Ct(()=>this._loc.location));re(this,kn,Ct(()=>this._loc.querystring));re(this,Sn,B(void 0));typeof window<"u"?window.addEventListener("hashchange",()=>{this._loc=Ia()}):console.warn("[svelte-spa-router] window 'window' is not defined, skipping initiation")}get _loc(){return l(E(this,xn))}set _loc(t){v(E(this,xn),t)}get _location(){return l(E(this,En))}set _location(t){v(E(this,En),t)}get _querystring(){return l(E(this,kn))}set _querystring(t){v(E(this,kn),t)}get _params(){return l(E(this,Sn))}set _params(t){v(E(this,Sn),t)}get loc(){return this._loc}get location(){return this._location}get querystring(){return this._querystring}get params(){return this._params}}xn=new WeakMap,En=new WeakMap,kn=new WeakMap,Sn=new WeakMap;const ai=new xu;function Ia(){const e=typeof window<"u"?window.location.href:"",t=e.indexOf("#/");let r=t>-1?e.substr(t+1):"/";const n=r.indexOf("?");let i="";return n>-1&&(i=r.substr(n+1),r=r.substr(0,n)),{location:r,querystring:i}}async function ua(e){if(!e||e.length<1||e.charAt(0)!="/"&&e.indexOf("#/")!==0)throw Error("Invalid parameter location");await sa(),history.replaceState({...history.state,__svelte_spa_router_scrollX:window.scrollX,__svelte_spa_router_scrollY:window.scrollY},""),window.location.hash=(e.charAt(0)=="#"?"":"#")+e}function Ma(e){e?window.scrollTo(e.__svelte_spa_router_scrollX||0,e.__svelte_spa_router_scrollY||0):window.scrollTo(0,0)}function Pa(e,t){Se(t,!0);const r=Be(t,"routes",19,()=>({})),n=Be(t,"prefix",3,""),i=Be(t,"restoreScrollState",3,!1),a=Be(t,"onConditionsFailed",3,()=>{}),o=Be(t,"onRouteLoaded",3,()=>{}),s=Be(t,"onRouteLoading",3,()=>{}),u=Be(t,"onRouteEvent",3,()=>{});class c{constructor(p,x){Ne(this,"path");Ne(this,"component");Ne(this,"conditions");Ne(this,"userData");Ne(this,"props");Ne(this,"_pattern");Ne(this,"_keys");const D=w=>typeof w=="object"&&w!==null&&w._sveltesparouter===!0;if(!x||typeof x!="function"&&!D(x))throw Error("Invalid component object");if(!p||typeof p=="string"&&(p.length<1||p.charAt(0)!="/"&&p.charAt(0)!="*")||typeof p=="object"&&!(p instanceof RegExp))throw Error('Invalid value for "path" argument - strings must start with / or *');const y=Ta(p);if(this.path=p,D(x)){const w=x;this.component=w.component,this.conditions=w.conditions||[],this.userData=w.userData,this.props=w.props||{}}else{const w=x;this.component=()=>Promise.resolve(w),this.conditions=[],this.props={}}this._pattern=y.pattern,this._keys=y.keys}match(p){if(n()){if(typeof n()=="string")if(p.startsWith(n()))p=p.substr(n().length)||"/";else return null;else if(n()instanceof RegExp){const w=p.match(n());if(w&&w[0])p=p.substr(w[0].length)||"/";else return null}}const x=this._pattern.exec(p);if(x===null)return null;if(this._keys===!1)return x;const D={};let y=0;for(;y{f.push(new c(p,A))}):Object.keys(r()).forEach(A=>{const p=r();f.push(new c(A,p[A]))});let m=B(null),d=B(null),g=B({}),b=null,C=null;it(()=>{history.scrollRestoration=i()?"manual":"auto"}),it(()=>{if(!i())return;const A=p=>{p.state&&(p.state.__svelte_spa_router_scrollY||p.state.__svelte_spa_router_scrollX)?b=p.state:b=null};return window.addEventListener("popstate",A),()=>window.removeEventListener("popstate",A)});async function k(A,p){await sa(),A(p)}it(()=>{const A=ai.loc;let p=!1;return ir(async()=>{let x=0;for(;x{p=!0}});function S(A){return A&&typeof A=="object"&&Object.keys(A).length?A:null}var I=Zt(),M=Pe(I);{var R=A=>{const p=Ct(()=>l(m));var x=Zt(),D=Pe(x);{var y=T=>{var N=Zt(),F=Pe(N);ka(F,()=>l(p),(P,H)=>{H(P,Aa({get params(){return l(d)},get onRouteEvent(){return u()}},()=>l(g)))}),L(T,N)},w=T=>{var N=Zt(),F=Pe(N);ka(F,()=>l(p),(P,H)=>{H(P,Aa({get onRouteEvent(){return u()}},()=>l(g)))}),L(T,N)};V(D,T=>{l(d)?T(y):T(w,-1)})}L(A,x)};V(M,A=>{l(m)&&A(R)})}L(e,I),Ce()}const yr="/api";async function $r(e){if(e.status===204)return null;const r=(e.headers.get("content-type")||"").includes("application/json")?await e.json():await e.text();if(!e.ok){const n=r&&r.error||e.statusText;throw new Error(n)}return r}function He(e){return fetch(yr+e).then($r)}function wr(e,t){return fetch(yr+e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).then($r)}function en(e,t){return fetch(yr+e,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).then($r)}function Eu(e,t){return fetch(yr+e,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).then($r)}function xr(e){return fetch(yr+e,{method:"DELETE"}).then($r)}function ds(e,t){const r=new FormData;return r.append("file",t),fetch(yr+e,{method:"POST",body:r}).then($r)}function Jr(e){return yr+e}const oi=fl(null);ll();var ku=q('
🔧

My Garage

Service history, rego & WoF reminders, and a knowledgebase for every car you own.

Log in
');function Su(e){var t=ku();L(e,t)}var Cu=q(" ");function ca(e,t){let r=Be(t,"size",3,"md");const n={sm:"px-2 py-0.5 text-xs tracking-wider",md:"px-3 py-1 text-base tracking-widest",lg:"px-4 py-2 text-2xl tracking-widest"};var i=Cu(),a=h(i);U(()=>{O(i,1,`inline-block rounded border-2 border-stone-900 bg-gradient-to-b from-white to-stone-100 font-mono font-bold text-stone-900 shadow-sm ${n[r()]??""}`),z(a,t.rego)}),L(e,i)}function It(e){return e?new Date(e).toLocaleDateString("en-NZ",{day:"numeric",month:"short",year:"numeric"}):"—"}function Gi(e){if(!e)return null;const t=new Date;t.setHours(0,0,0,0);const r=new Date(e);return r.setHours(0,0,0,0),Math.round((r-t)/864e5)}const Au={service:"Service",wheel_rotation:"Wheel rotation",alignment:"Alignment",rego:"Rego",wof:"WoF",custom:"Custom"};function Tu(e){const t=e.kind??e.reminderType;return t==="custom"&&e.label?e.label:Au[t]||t}const Ht="inline-flex items-center justify-center gap-1.5 rounded-lg bg-teal-700 px-4 py-2 text-sm font-medium text-white shadow-sm shadow-teal-900/20 hover:bg-teal-600 active:bg-teal-800 disabled:opacity-50 disabled:pointer-events-none transition-colors",rr="inline-flex items-center justify-center gap-1.5 rounded-lg border border-stone-300 bg-white px-4 py-2 text-sm font-medium text-stone-700 hover:bg-stone-50 disabled:opacity-50 disabled:pointer-events-none transition-colors",vs="inline-flex items-center justify-center gap-1.5 rounded-lg border border-red-200 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50 transition-colors",nr="inline-flex items-center gap-1 rounded-md px-2 py-1 text-sm font-medium text-teal-600 hover:bg-teal-50 transition-colors",qt="inline-flex items-center justify-center rounded-md p-1.5 text-stone-400 hover:bg-stone-100 hover:text-stone-700 transition-colors",Xn="rounded-lg border border-stone-200 bg-white shadow-sm",hs="rounded-lg border border-stone-200 border-t-4 border-t-teal-700 bg-white shadow-sm p-5",be="w-full rounded-lg border border-stone-300 bg-white px-3 py-2 text-sm text-stone-900 placeholder-stone-400 focus:outline-none focus:ring-2 focus:ring-teal-500/40 focus:border-teal-500 transition-shadow",ye="mb-1 block text-sm font-medium text-stone-700",Iu="text-sm font-semibold uppercase tracking-wide text-stone-500";var Mu=ss(''),Pu=ss('');function _e(e,t){let r=Be(t,"class",3,"w-4 h-4");const n={plus:"M12 5v14M5 12h14",pencil:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z",trash:"M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m-8 0v12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V7",x:"M6 6l12 12M18 6L6 18",check:"M5 13l4 4L19 7",chevronDown:"M6 9l6 6 6-6",chevronRight:"M9 6l6 6-6 6",paperclip:"M8 12.5l6.5-6.5a3 3 0 1 1 4.24 4.24l-8.5 8.5a5 5 0 1 1-7.07-7.07L11 3.84",bookOpen:"M12 6c-1.5-1.2-4-2-7-2v13c3 0 5.5.8 7 2m0-13c1.5-1.2 4-2 7-2v13c-3 0-5.5.8-7 2m0-13v13",undo:"M9 14l-4-4 4-4M5 10h9a5 5 0 0 1 0 10h-1",share:"M12 15V3m0 0 4 4m-4-4-4 4M5 13v6a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-6",fuel:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-9 4-4"},i="M4 8a2 2 0 0 1 2-2h1.5l1-1.5h5l1 1.5H17a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8z";var a=Zt(),o=Pe(a);{var s=c=>{var f=Mu(),m=h(f);Ge(m,"d",i),U(()=>O(f,0,j(r()))),L(c,f)},u=c=>{var f=Pu(),m=h(f);U(()=>{O(f,0,j(r())),Ge(m,"d",n[t.name]??"")}),L(c,f)};V(o,c=>{t.name==="camera"?c(s):c(u,-1)})}L(e,a)}var Ru=q('
'),Nu=q('

'),Lu=q(' '),Du=q('
'),Bu=q('

',1);function Fu(e,t){Se(t,!0);let r=Be(t,"fileHref",3,A=>Jr(`/files/${A.id}`));var n=Bu(),i=Pe(n),a=h(i),o=h(a),s=h(o),u=_(o,2),c=h(u),f=_(u,2),m=h(f);{var d=A=>{var p=Gr();U(()=>z(p,t.entry.performedAt)),L(A,p)};V(m,A=>{t.entry.performedAt&&A(d)})}var g=_(m,2);{var b=A=>{var p=Gr();U(x=>z(p,`${t.entry.performedAt?" · ":""}${x??""} km`),[()=>t.entry.odometer.toLocaleString()]),L(A,p)};V(g,A=>{t.entry.odometer&&A(b)})}var C=_(a,2);{var k=A=>{var p=Ru(),x=h(p),D=h(x);_e(D,{name:"pencil",class:"h-4 w-4"});var y=_(x,2),w=h(y);_e(w,{name:"trash",class:"h-4 w-4"}),U(()=>{O(x,1,j(qt)),O(y,1,`${qt} hover:text-red-600`)}),se("click",x,()=>{var T;return(T=t.onEdit)==null?void 0:T.call(t,t.entry)}),se("click",y,()=>{var T;return(T=t.onDelete)==null?void 0:T.call(t,t.entry)}),L(A,p)};V(C,A=>{(t.onEdit||t.onDelete)&&A(k)})}var S=_(i,2);{var I=A=>{var p=Nu(),x=h(p);U(()=>z(x,t.entry.description)),L(A,p)};V(S,A=>{t.entry.description&&A(I)})}var M=_(S,2);{var R=A=>{var p=Du();zt(p,21,()=>t.entry.files,x=>x.id,(x,D)=>{var y=Lu(),w=h(y);_e(w,{name:"paperclip",class:"h-3.5 w-3.5"});var T=_(w);U(N=>{Ge(y,"href",N),z(T,` ${l(D).fileName??""}`)},[()=>r()(l(D))]),L(x,y)}),L(A,p)};V(M,A=>{var p;(p=t.entry.files)!=null&&p.length&&A(R)})}U(A=>{z(s,A),z(c,t.entry.entryType)},[()=>It(t.entry.entryDate)]),L(e,n),Ce()}ze(["click"]);var Ou=q('

No service history yet.

'),qu=q(''),ju=q('
  • '),Uu=q("
      ");function gs(e,t){Se(t,!0);var r=Zt(),n=Pe(r);{var i=o=>{var s=Ou();L(o,s)},a=o=>{var s=Uu();zt(s,23,()=>t.entries,u=>u.id,(u,c,f)=>{var m=ju(),d=h(m),g=_(h(d),2);{var b=S=>{var I=qu();L(S,I)};V(g,S=>{l(f){t.entries.length===0?o(i):o(a,-1)})}L(e,r),Ce()}var Hu=q('

      Loading…

      '),zu=q('

      '),Vu=q(''),Ku=q(""),Yu=q('

      Service history

      ',1),Gu=q('
      🔧 My Garage · shared service history
      ');function Ju(e,t){Se(t,!0);const r=t.params.token;let n=B(null),i=B(ne([])),a=B(!1),o=B(!0),s=B("");async function u(){try{v(n,await He(`/public/cars/${r}`),!0);const S=await He(`/public/cars/${r}/service-entries?limit=20&offset=0`);v(i,S.items,!0),v(a,S.hasMore,!0)}catch{v(s,"This share link is invalid, or sharing has been turned off.")}finally{v(o,!1)}}u();async function c(){const S=await He(`/public/cars/${r}/service-entries?limit=20&offset=${l(i).length}`);v(i,[...l(i),...S.items],!0),v(a,S.hasMore,!0)}const f=S=>Jr(`/public/cars/${r}/files/${S.id}`);var m=Gu(),d=_(h(m),4),g=h(d);{var b=S=>{var I=Hu();L(S,I)},C=S=>{var I=zu(),M=h(I);U(()=>z(M,l(s))),L(S,I)},k=S=>{var I=Yu(),M=Pe(I),R=h(M);{var A=P=>{var H=Vu();U(G=>{Ge(H,"src",G),Ge(H,"alt",l(n).rego)},[()=>Jr(`/public/cars/${r}/photo`)]),L(P,H)};V(R,P=>{l(n).hasPhoto&&P(A)})}var p=_(R,2),x=h(p);ca(x,{get rego(){return l(n).rego},size:"md"});var D=_(x,2),y=h(D),w=_(M,4),T=h(w);gs(T,{get entries(){return l(i)},fileHref:f});var N=_(T,2);{var F=P=>{var H=Ku();U(()=>O(H,1,`${nr} mt-3`)),se("click",H,c),L(P,H)};V(N,P=>{l(a)&&P(F)})}U(P=>z(y,`${P??""}${l(n).color?` · ${l(n).color}`:""}`),[()=>[l(n).year,l(n).make,l(n).model].filter(Boolean).join(" ")]),L(S,I)};V(g,S=>{l(o)?S(b):l(s)?S(C,1):l(n)&&S(k,2)})}L(e,m),Ce()}ze(["click"]);var Wu=q(''),Qu=q('
      🚗
      '),Zu=q(" "),Xu=q(' '),$u=q('

      '),ec=q('
      ');function tc(e,t){Se(t,!0);let r=Ct(()=>{const p=[Gi(t.car.regoExpiry),Gi(t.car.wofExpiry)].filter(x=>x!==null);return p.some(x=>x<0)?"overdue":p.some(x=>x<=30)?"upcoming":null});var n=ec(),i=h(n),a=h(i);{var o=p=>{var x=Wu();U(D=>{Ge(x,"src",D),Ge(x,"alt",t.car.rego)},[()=>Jr(`/cars/${t.car.id}/photo`)]),L(p,x)},s=p=>{var x=Qu();L(p,x)};V(a,p=>{t.car.hasPhoto?p(o):p(s,-1)})}var u=_(a,2);{var c=p=>{var x=Zu(),D=h(x);U(()=>{O(x,1,`absolute right-2 top-2 rounded px-2 py-0.5 text-xs font-semibold uppercase tracking-wide shadow-sm + ${l(r)==="overdue"?"bg-red-600 text-white":"bg-amber-500 text-white"}`),z(D,l(r)==="overdue"?"Overdue":"Due soon")}),L(p,x)};V(u,p=>{l(r)&&p(c)})}var f=_(i,2),m=h(f),d=h(m);ca(d,{get rego(){return t.car.rego},size:"sm"});var g=_(d,2);{var b=p=>{var x=Xu(),D=h(x);U(()=>z(D,`${t.car.year??""??""} ${t.car.make??""??""}`)),L(p,x)};V(g,p=>{(t.car.year||t.car.make)&&p(b)})}var C=_(m,2);{var k=p=>{var x=$u(),D=h(x);U(()=>z(D,t.car.model)),L(p,x)};V(C,p=>{t.car.model&&p(k)})}var S=_(C,2),I=h(S),M=h(I),R=_(I,2),A=h(R);U((p,x)=>{Ge(n,"href",`#/cars/${t.car.id??""}`),O(n,1,`${Xn} group block overflow-hidden transition-all hover:-translate-y-0.5 hover:shadow-lg`),z(M,`Rego: ${p??""}`),z(A,`WoF: ${x??""}`)},[()=>It(t.car.regoExpiry),()=>It(t.car.wofExpiry)]),L(e,n),Ce()}var rc=q('

      ');function yt(e,t){Se(t,!0);let r=Be(t,"wide",3,!1);function n(b){var C;b.key==="Escape"&&((C=t.onClose)==null||C.call(t))}var i=rc();br("keydown",Hi,n);var a=h(i),o=_(a,2),s=h(o),u=h(s),c=h(u),f=_(u,2),m=h(f);_e(m,{name:"x",class:"h-5 w-5"});var d=_(s,2),g=h(d);su(g,()=>t.children??$t),U(()=>{O(o,1,`relative my-8 w-full ${r()?"max-w-2xl":"max-w-lg"} rounded-lg border border-stone-200 bg-white shadow-xl sm:my-0`),z(c,t.title)}),se("click",a,()=>{var b;return(b=t.onClose)==null?void 0:b.call(t)}),se("click",f,()=>{var b;return(b=t.onClose)==null?void 0:b.call(t)}),L(e,i),Ce()}ze(["click"]);var nc=q(""),ic=q('
      '),ac=q('

      '),oc=q('
      ');function Ra(e,t){var oe,X,J,$,ue,Z;Se(t,!0);let r=Be(t,"reminder",3,null);const n=[{value:"service",label:"Service"},{value:"wheel_rotation",label:"Wheel rotation"},{value:"alignment",label:"Alignment"},{value:"custom",label:"Custom…"}];let i=B(ne(((oe=r())==null?void 0:oe.reminderType)??"service")),a=B(ne(((X=r())==null?void 0:X.label)??"")),o=B(ne((($=(J=r())==null?void 0:J.dueDate)==null?void 0:$.slice(0,10))??"")),s=B(ne(((ue=r())==null?void 0:ue.dueOdometer)??"")),u=B(ne(((Z=r())==null?void 0:Z.notes)??"")),c=B(!1),f=B("");async function m(Y){var le;if(Y.preventDefault(),l(i)==="custom"&&!l(a).trim()){v(f,"Label is required for a custom reminder");return}if(!l(o)&&!l(s)){v(f,"Set a due date or a due odometer reading");return}v(c,!0),v(f,"");const ie={reminderType:l(i),label:l(i)==="custom"?l(a).trim():null,dueDate:l(o)||null,dueOdometer:l(s)?Number(l(s)):null,notes:l(u)||null};try{r()?await en(`/reminders/${r().id}`,ie):await wr(`/cars/${t.carId}/reminders`,ie),(le=t.onSaved)==null||le.call(t)}catch(fe){v(f,fe.message,!0)}finally{v(c,!1)}}var d=oc(),g=h(d),b=h(g),C=_(b,2);zt(C,21,()=>n,Y=>Y.value,(Y,ie)=>{var le=nc(),fe=h(le),he={};U(()=>{z(fe,l(ie).label),he!==(he=l(ie).value)&&(le.value=(le.__value=l(ie).value)??"")}),L(Y,le)});var k=_(g,2);{var S=Y=>{var ie=ic(),le=h(ie),fe=_(le,2);U(()=>{O(le,1,j(ye)),O(fe,1,j(be))}),Ee(fe,()=>l(a),he=>v(a,he)),L(Y,ie)};V(k,Y=>{l(i)==="custom"&&Y(S)})}var I=_(k,2),M=h(I),R=h(M),A=_(R,2),p=_(M,2),x=h(p),D=_(x,2),y=_(I,2),w=h(y),T=_(w,2),N=_(y,2);{var F=Y=>{var ie=ac(),le=h(ie);U(()=>z(le,l(f))),L(Y,ie)};V(N,Y=>{l(f)&&Y(F)})}var P=_(N,2),H=h(P),G=_(H,2),Q=h(G);U(()=>{O(b,1,j(ye)),O(C,1,j(be)),O(R,1,j(ye)),O(A,1,j(be)),O(x,1,j(ye)),O(D,1,j(be)),O(w,1,j(ye)),O(T,1,j(be)),O(H,1,j(rr)),G.disabled=l(c),O(G,1,j(Ht)),z(Q,l(c)?"Saving…":r()?"Save changes":"Add reminder")}),br("submit",d,m),fu(C,()=>l(i),Y=>v(i,Y)),Ee(A,()=>l(o),Y=>v(o,Y)),Ee(D,()=>l(s),Y=>v(s,Y)),Ee(T,()=>l(u),Y=>v(u,Y)),se("click",H,()=>{var Y;return(Y=t.onCancel)==null?void 0:Y.call(t)}),L(e,d),Ce()}ze(["click"]);var sc=q('

      Loading…

      '),lc=q('

      '),uc=q('

      '),cc=q('Overdue'),fc=q('Due soon'),dc=q(' '),vc=q('
      '),hc=q('View car'),gc=q('
    1. '),pc=q('
        '),mc=q('
        '),_c=q(" ",1);function ps(e,t){Se(t,!0);let r=Be(t,"carId",3,null),n=B(ne([])),i=B(!0),a=B(""),o=B(!1),s=B(!1),u=B(null);async function c(){v(i,!0),v(a,"");try{r()?v(n,await He(`/cars/${r()}/reminders${l(o)?"?completed=1":""}`),!0):v(n,await He("/dashboard"),!0)}catch(y){v(a,y.message,!0)}finally{v(i,!1)}}it(()=>{r(),l(o),c()});async function f(y){await en(`/reminders/${y.id}`,{completed:!y.completedAt}),await c()}async function m(y){confirm("Delete this reminder?")&&(await xr(`/reminders/${y.id}`),await c())}function d(){v(s,!1),v(u,null),c()}var g=_c(),b=Pe(g);{var C=y=>{var w=sc();L(y,w)},k=y=>{var w=lc(),T=h(w);U(()=>z(T,l(a))),L(y,w)},S=y=>{var w=uc(),T=h(w);U(()=>z(T,l(o)?"No completed reminders.":`Nothing due${r()?"":" across your garage"}.`)),L(y,w)},I=y=>{var w=pc();zt(w,21,()=>l(n),T=>T.id??`${T.reminderType}-${T.carId}`,(T,N)=>{var F=gc(),P=h(F),H=h(P),G=h(H),Q=_(G);{var oe=K=>{var ce=cc();L(K,ce)},X=K=>{var ce=fc();L(K,ce)};V(Q,K=>{l(N).status==="overdue"?K(oe):l(N).status==="upcoming"&&K(X,1)})}var J=_(Q,2);{var $=K=>{var ce=dc(),pe=h(ce);U(()=>z(pe,`· ${l(N).carRego??""}`)),L(K,ce)};V(J,K=>{r()||K($)})}var ue=_(H,2),Z=h(ue);{var Y=K=>{var ce=Gr();U(pe=>z(ce,`Due ${pe??""}`),[()=>It(l(N).dueDate)]),L(K,ce)};V(Z,K=>{l(N).dueDate&&K(Y)})}var ie=_(Z,2);{var le=K=>{var ce=Gr();U(pe=>z(ce,`${l(N).dueDate?" · ":"Due "}${pe??""} km`),[()=>l(N).dueOdometer.toLocaleString()]),L(K,ce)};V(ie,K=>{l(N).dueOdometer&&K(le)})}var fe=_(P,2);{var he=K=>{var ce=vc(),pe=h(ce),$e=h(pe);{let Ae=Ct(()=>l(N).completedAt?"undo":"check");_e($e,{get name(){return l(Ae)},class:"h-4 w-4"})}var Ue=_(pe,2),vt=h(Ue);_e(vt,{name:"pencil",class:"h-4 w-4"});var ee=_(Ue,2),me=h(ee);_e(me,{name:"trash",class:"h-4 w-4"}),U(()=>{Ge(pe,"aria-label",l(N).completedAt?"Reopen":"Mark done"),O(pe,1,j(qt)),O(Ue,1,j(qt)),O(ee,1,`${qt} hover:text-red-600`)}),se("click",pe,()=>f(l(N))),se("click",Ue,()=>v(u,l(N),!0)),se("click",ee,()=>m(l(N))),L(K,ce)},Ie=K=>{var ce=hc();U(()=>Ge(ce,"href",`#/cars/${l(N).carId??""}`)),L(K,ce)};V(fe,K=>{r()&&l(N).id?K(he):!r()&&l(N).carId&&K(Ie,1)})}U(K=>z(G,`${K??""} `),[()=>Tu(l(N))]),L(T,F)}),L(y,w)};V(b,y=>{l(i)?y(C):l(a)?y(k,1):l(n).length===0?y(S,2):y(I,-1)})}var M=_(b,2);{var R=y=>{var w=mc(),T=h(w),N=h(T);_e(N,{name:"plus",class:"h-4 w-4"});var F=_(T,2),P=h(F);U(()=>{O(T,1,j(nr)),z(P,l(o)?"Hide completed":"Show completed")}),se("click",T,()=>v(s,!0)),se("click",F,()=>v(o,!l(o))),L(y,w)};V(M,y=>{r()&&y(R)})}var A=_(M,2);{var p=y=>{yt(y,{title:"Add reminder",onClose:()=>v(s,!1),children:(w,T)=>{Ra(w,{get carId(){return r()},onSaved:d,onCancel:()=>v(s,!1)})},$$slots:{default:!0}})};V(A,y=>{l(s)&&y(p)})}var x=_(A,2);{var D=y=>{yt(y,{title:"Edit reminder",onClose:()=>v(u,null),children:(w,T)=>{Ra(w,{get carId(){return r()},get reminder(){return l(u)},onSaved:d,onCancel:()=>v(u,null)})},$$slots:{default:!0}})};V(x,y=>{l(u)&&y(D)})}L(e,g),Ce()}ze(["click"]);var bc=q('

        Loading…

        '),yc=q('

        '),wc=q('
        🚗

        No cars yet — add your first one to get started.

        Add car
        '),xc=q('
        '),Ec=q('

        Coming up

        Your garage

        Add car
        ');function kc(e,t){Se(t,!0);let r=B(ne([])),n=B(!0),i=B("");fs(async()=>{try{v(r,await He("/cars"),!0)}catch(I){v(i,I.message,!0)}finally{v(n,!1)}});var a=Ec(),o=h(a),s=h(o),u=_(s,2);ps(u,{});var c=_(o,2),f=h(c),m=_(h(f),2),d=h(m);_e(d,{name:"plus",class:"h-4 w-4"});var g=_(f,2);{var b=I=>{var M=bc();L(I,M)},C=I=>{var M=yc(),R=h(M);U(()=>z(R,l(i))),L(I,M)},k=I=>{var M=wc(),R=_(h(M),4),A=h(R);_e(A,{name:"plus",class:"h-4 w-4"}),U(()=>{O(M,1,`${Xn} flex flex-col items-center gap-3 px-6 py-12 text-center`),O(R,1,j(Ht))}),L(I,M)},S=I=>{var M=xc();zt(M,21,()=>l(r),R=>R.id,(R,A)=>{tc(R,{get car(){return l(A)}})}),L(I,M)};V(g,I=>{l(n)?I(b):l(i)?I(C,1):l(r).length===0?I(k,2):I(S,-1)})}U(()=>{O(o,1,j(hs)),O(s,1,`${Iu} mb-3`),O(m,1,j(Ht))}),L(e,a),Ce()}var Sc=q(''),Cc=q(''),Ac=q('

        '),Tc=q('
        ');function Ic(e,t){Se(t,!0);let r=Be(t,"hasPhoto",3,!1),n=Be(t,"alt",3,"Car photo"),i=B(!1),a=B(""),o=B(0);async function s(b){var k;const C=b.target.files[0];if(C){v(i,!0),v(a,"");try{await ds(`/cars/${t.carId}/photo`,C),v(o,l(o)+1),(k=t.onUploaded)==null||k.call(t)}catch(S){v(a,S.message,!0)}finally{v(i,!1),b.target.value=""}}}var u=Tc(),c=h(u);{var f=b=>{var C=Sc(),k=h(C),S=_(k,2),I=h(S),M=h(I);_e(M,{name:"camera",class:"h-4 w-4"});var R=_(M),A=_(S,2);U(p=>{Ge(k,"src",p),Ge(k,"alt",n()),z(R,` ${l(i)?"Uploading…":"Replace photo"}`),A.disabled=l(i)},[()=>Jr(`/cars/${t.carId}/photo?v=${l(o)}`)]),se("change",A,s),L(b,C)},m=b=>{var C=Cc(),k=h(C);_e(k,{name:"camera",class:"h-8 w-8"});var S=_(k,2),I=h(S),M=_(S,2);U(()=>{z(I,l(i)?"Uploading…":"Add a photo"),M.disabled=l(i)}),se("change",M,s),L(b,C)};V(c,b=>{r()?b(f):b(m,-1)})}var d=_(c,2);{var g=b=>{var C=Ac(),k=h(C);U(()=>z(k,l(a))),L(b,C)};V(d,b=>{l(a)&&b(g)})}L(e,u),Ce()}ze(["change"]);function Mc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Mr={},si,Na;function Pc(){return Na||(Na=1,si=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),si}var li={},Gt={},La;function Er(){if(La)return Gt;La=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Gt.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},Gt.getSymbolTotalCodewords=function(n){return t[n]},Gt.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Gt.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Gt.isKanjiModeEnabled=function(){return typeof e<"u"},Gt.toSJIS=function(n){return e(n)},Gt}var ui={},Da;function fa(){return Da||(Da=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,i){if(e.isValid(n))return n;try{return t(n)}catch{return i}}})(ui)),ui}var ci,Ba;function Rc(){if(Ba)return ci;Ba=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},ci=e,ci}var fi,Fa;function Nc(){if(Fa)return fi;Fa=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,i){const a=t*this.size+r;this.data[a]=n,i&&(this.reservedBit[a]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},fi=e,fi}var di={},Oa;function Lc(){return Oa||(Oa=1,(function(e){const t=Er().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const i=Math.floor(n/7)+2,a=t(n),o=a===145?26:Math.ceil((a-13)/(2*i-2))*2,s=[a-7];for(let u=1;u=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const a=i.size;let o=0,s=0,u=0,c=null,f=null;for(let m=0;m=5&&(o+=t.N1+(s-5)),c=g,s=1),g=i.get(d,m),g===f?u++:(u>=5&&(o+=t.N1+(u-5)),f=g,u=1)}s>=5&&(o+=t.N1+(s-5)),u>=5&&(o+=t.N1+(u-5))}return o},e.getPenaltyN2=function(i){const a=i.size;let o=0;for(let s=0;s=10&&(s===1488||s===93)&&o++,u=u<<1&2047|i.get(f,c),f>=10&&(u===1488||u===93)&&o++}return o*t.N3},e.getPenaltyN4=function(i){let a=0;const o=i.data.length;for(let u=0;u=0;){const o=a[0];for(let u=0;u0){const s=new Uint8Array(this.degree);return s.set(a,o),s}return a},pi=t,pi}var mi={},_i={},bi={},Ka;function _s(){return Ka||(Ka=1,bi.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),bi}var wt={},Ya;function bs(){if(Ya)return wt;Ya=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r +]))+`;wt.KANJI=new RegExp(r,"g"),wt.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),wt.BYTE=new RegExp(n,"g"),wt.NUMERIC=new RegExp(e,"g"),wt.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),a=new RegExp("^"+e+"$"),o=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return wt.testKanji=function(u){return i.test(u)},wt.testNumeric=function(u){return a.test(u)},wt.testAlphanumeric=function(u){return o.test(u)},wt}var Ga;function kr(){return Ga||(Ga=1,(function(e){const t=_s(),r=bs();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(a,o){if(!a.ccBits)throw new Error("Invalid mode: "+a);if(!t.isValid(o))throw new Error("Invalid version: "+o);return o>=1&&o<10?a.ccBits[0]:o<27?a.ccBits[1]:a.ccBits[2]},e.getBestModeForData=function(a){return r.testNumeric(a)?e.NUMERIC:r.testAlphanumeric(a)?e.ALPHANUMERIC:r.testKanji(a)?e.KANJI:e.BYTE},e.toString=function(a){if(a&&a.id)return a.id;throw new Error("Invalid mode")},e.isValid=function(a){return a&&a.bit&&a.ccBits};function n(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+i)}}e.from=function(a,o){if(e.isValid(a))return a;try{return n(a)}catch{return o}}})(_i)),_i}var Ja;function jc(){return Ja||(Ja=1,(function(e){const t=Er(),r=ms(),n=fa(),i=kr(),a=_s(),o=7973,s=t.getBCHDigit(o);function u(d,g,b){for(let C=1;C<=40;C++)if(g<=e.getCapacity(C,b,d))return C}function c(d,g){return i.getCharCountIndicator(d,g)+4}function f(d,g){let b=0;return d.forEach(function(C){const k=c(C.mode,g);b+=k+C.getBitsLength()}),b}function m(d,g){for(let b=1;b<=40;b++)if(f(d,b)<=e.getCapacity(b,g,i.MIXED))return b}e.from=function(g,b){return a.isValid(g)?parseInt(g,10):b},e.getCapacity=function(g,b,C){if(!a.isValid(g))throw new Error("Invalid QR Code version");typeof C>"u"&&(C=i.BYTE);const k=t.getSymbolTotalCodewords(g),S=r.getTotalCodewordsCount(g,b),I=(k-S)*8;if(C===i.MIXED)return I;const M=I-c(C,g);switch(C){case i.NUMERIC:return Math.floor(M/10*3);case i.ALPHANUMERIC:return Math.floor(M/11*2);case i.KANJI:return Math.floor(M/13);case i.BYTE:default:return Math.floor(M/8)}},e.getBestVersionForData=function(g,b){let C;const k=n.from(b,n.M);if(Array.isArray(g)){if(g.length>1)return m(g,k);if(g.length===0)return 1;C=g[0]}else C=g;return u(C.mode,C.getLength(),k)},e.getEncodedBits=function(g){if(!a.isValid(g)||g<7)throw new Error("Invalid QR Code version");let b=g<<12;for(;t.getBCHDigit(b)-s>=0;)b^=o<=0;)u^=t<0&&(a=this.data.substr(i),o=parseInt(a,10),n.put(o,s*3+1))},xi=t,xi}var Ei,Za;function zc(){if(Za)return Ei;Za=1;const e=kr(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(i){let a;for(a=0;a+2<=this.data.length;a+=2){let o=t.indexOf(this.data[a])*45;o+=t.indexOf(this.data[a+1]),i.put(o,11)}this.data.length%2&&i.put(t.indexOf(this.data[a]),6)},Ei=r,Ei}var ki,Xa;function Vc(){if(Xa)return ki;Xa=1;const e=kr();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,i=this.data.length;n=33088&&a<=40956)a-=33088;else if(a>=57408&&a<=60351)a-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+` +Make sure your charset is UTF-8`);a=(a>>>8&255)*192+(a&255),n.put(a,13)}},Si=r,Si}var Ci={exports:{}},eo;function Yc(){return eo||(eo=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var a={},o={};o[n]=0;var s=t.PriorityQueue.make();s.push(n,0);for(var u,c,f,m,d,g,b,C,k;!s.empty();){u=s.pop(),c=u.value,m=u.cost,d=r[c]||{};for(f in d)d.hasOwnProperty(f)&&(g=d[f],b=m+g,C=o[f],k=typeof o[f]>"u",(k||C>b)&&(o[f]=b,s.push(f,b),a[f]=c))}if(typeof i<"u"&&typeof o[i]>"u"){var S=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(S)}return a},extract_shortest_path_from_predecessor_list:function(r,n){for(var i=[],a=n;a;)i.push(a),r[a],a=r[a];return i.reverse(),i},find_path:function(r,n,i){var a=t.single_source_shortest_paths(r,n,i);return t.extract_shortest_path_from_predecessor_list(a,i)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,i={},a;r=r||{};for(a in n)n.hasOwnProperty(a)&&(i[a]=n[a]);return i.queue=[],i.sorter=r.sorter||n.default_sorter,i},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var i={value:r,cost:n};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Ci)),Ci.exports}var to;function Gc(){return to||(to=1,(function(e){const t=kr(),r=Hc(),n=zc(),i=Vc(),a=Kc(),o=bs(),s=Er(),u=Yc();function c(S){return unescape(encodeURIComponent(S)).length}function f(S,I,M){const R=[];let A;for(;(A=S.exec(M))!==null;)R.push({data:A[0],index:A.index,mode:I,length:A[0].length});return R}function m(S){const I=f(o.NUMERIC,t.NUMERIC,S),M=f(o.ALPHANUMERIC,t.ALPHANUMERIC,S);let R,A;return s.isKanjiModeEnabled()?(R=f(o.BYTE,t.BYTE,S),A=f(o.KANJI,t.KANJI,S)):(R=f(o.BYTE_KANJI,t.BYTE,S),A=[]),I.concat(M,R,A).sort(function(x,D){return x.index-D.index}).map(function(x){return{data:x.data,mode:x.mode,length:x.length}})}function d(S,I){switch(I){case t.NUMERIC:return r.getBitsLength(S);case t.ALPHANUMERIC:return n.getBitsLength(S);case t.KANJI:return a.getBitsLength(S);case t.BYTE:return i.getBitsLength(S)}}function g(S){return S.reduce(function(I,M){const R=I.length-1>=0?I[I.length-1]:null;return R&&R.mode===M.mode?(I[I.length-1].data+=M.data,I):(I.push(M),I)},[])}function b(S){const I=[];for(let M=0;M=0&&F<=6&&(P===0||P===6)||P>=0&&P<=6&&(F===0||F===6)||F>=2&&F<=4&&P>=2&&P<=4?p.set(T+F,N+P,!0,!0):p.set(T+F,N+P,!1,!0))}}function b(p){const x=p.size;for(let D=8;D>F&1)===1,p.set(w,T,N,!0),p.set(T,w,N,!0)}function S(p,x,D){const y=p.size,w=f.getEncodedBits(x,D);let T,N;for(T=0;T<15;T++)N=(w>>T&1)===1,T<6?p.set(T,8,N,!0):T<8?p.set(T+1,8,N,!0):p.set(y-15+T,8,N,!0),T<8?p.set(8,y-T-1,N,!0):T<9?p.set(8,15-T-1+1,N,!0):p.set(8,15-T-1,N,!0);p.set(y-8,8,1,!0)}function I(p,x){const D=p.size;let y=-1,w=D-1,T=7,N=0;for(let F=D-1;F>0;F-=2)for(F===6&&F--;;){for(let P=0;P<2;P++)if(!p.isReserved(w,F-P)){let H=!1;N>>T&1)===1),p.set(w,F-P,H),T--,T===-1&&(N++,T=7)}if(w+=y,w<0||D<=w){w-=y,y=-y;break}}}function M(p,x,D){const y=new r;D.forEach(function(P){y.put(P.mode.bit,4),y.put(P.getLength(),m.getCharCountIndicator(P.mode,p)),P.write(y)});const w=e.getSymbolTotalCodewords(p),T=s.getTotalCodewordsCount(p,x),N=(w-T)*8;for(y.getLengthInBits()+4<=N&&y.put(0,4);y.getLengthInBits()%8!==0;)y.putBit(0);const F=(N-y.getLengthInBits())/8;for(let P=0;P=7&&k(P,x),I(P,N),isNaN(y)&&(y=o.getBestMask(P,S.bind(null,P,D))),o.applyMask(y,P),S(P,D,y),{modules:P,version:x,errorCorrectionLevel:D,maskPattern:y,segments:w}}return li.create=function(x,D){if(typeof x>"u"||x==="")throw new Error("No input text");let y=t.M,w,T;return typeof D<"u"&&(y=t.from(D.errorCorrectionLevel,t.M),w=c.from(D.version),T=o.from(D.maskPattern),D.toSJISFunc&&e.setToSJISFunction(D.toSJISFunc)),A(x,w,y,T)},li}var Ai={},Ti={},no;function ys(){return no||(no=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(a){return[a,a]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,a=n.width&&n.width>=21?n.width:void 0,o=n.scale||4;return{width:a,scale:a?4:o,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const a=e.getScale(n,i);return Math.floor((n+i.margin*2)*a)},e.qrToImageData=function(n,i,a){const o=i.modules.size,s=i.modules.data,u=e.getScale(o,a),c=Math.floor((o+a.margin*2)*u),f=a.margin*u,m=[a.color.light,a.color.dark];for(let d=0;d=f&&g>=f&&d"u"&&(!o||!o.getContext)&&(u=o,o=void 0),o||(c=n()),u=t.getOptions(u);const f=t.getImageWidth(a.modules.size,u),m=c.getContext("2d"),d=m.createImageData(f,f);return t.qrToImageData(d.data,a,u),r(m,c,f),m.putImageData(d,0,0),c},e.renderToDataURL=function(a,o,s){let u=s;typeof u>"u"&&(!o||!o.getContext)&&(u=o,o=void 0),u||(u={});const c=e.render(a,o,u),f=u.type||"image/png",m=u.rendererOpts||{};return c.toDataURL(f,m.quality)}})(Ai)),Ai}var Ii={},ao;function Qc(){if(ao)return Ii;ao=1;const e=ys();function t(i,a){const o=i.a/255,s=a+'="'+i.hex+'"';return o<1?s+" "+a+'-opacity="'+o.toFixed(2).slice(1)+'"':s}function r(i,a,o){let s=i+a;return typeof o<"u"&&(s+=" "+o),s}function n(i,a,o){let s="",u=0,c=!1,f=0;for(let m=0;m0&&d>0&&i[m-1]||(s+=c?r("M",d+o,.5+g+o):r("m",u,0),u=0,c=!1),d+1':"",g="',b='viewBox="0 0 '+m+" "+m+'"',k=''+d+g+` +`;return typeof s=="function"&&s(null,k),k},Ii}var oo;function Zc(){if(oo)return Mr;oo=1;const e=Pc(),t=Jc(),r=Wc(),n=Qc();function i(a,o,s,u,c){const f=[].slice.call(arguments,1),m=f.length,d=typeof f[m-1]=="function";if(!d&&!e())throw new Error("Callback required as last argument");if(d){if(m<2)throw new Error("Too few arguments provided");m===2?(c=s,s=o,o=u=void 0):m===3&&(o.getContext&&typeof c>"u"?(c=u,u=void 0):(c=u,u=s,s=o,o=void 0))}else{if(m<1)throw new Error("Too few arguments provided");return m===1?(s=o,o=u=void 0):m===2&&!o.getContext&&(u=s,s=o,o=void 0),new Promise(function(g,b){try{const C=t.create(s,u);g(a(C,o,u))}catch(C){b(C)}})}try{const g=t.create(s,u);c(null,a(g,o,u))}catch(g){c(g)}}return Mr.create=t.create,Mr.toCanvas=i.bind(null,r.render),Mr.toDataURL=i.bind(null,r.renderToDataURL),Mr.toString=i.bind(null,function(a,o,s){return n.render(a,s)}),Mr}var Xc=Zc();const $c=Mc(Xc);var ef=q(""),tf=q('QR code for share link'),rf=q('
        ',1),nf=q('

        '),af=q('

        ');function of(e,t){Se(t,!0);let r=B(ne(t.car.shareToken)),n=B(""),i=B(!1),a=B(!1),o=B(""),s=Ct(()=>l(r)?`${window.location.origin}/#/share/${l(r)}`:"");it(()=>{if(!l(s)){v(n,"");return}$c.toDataURL(l(s),{width:220,margin:1}).then(R=>v(n,R,!0))});async function u(){var R;v(i,!0),v(o,"");try{const A=await wr(`/cars/${t.car.id}/share`,{});v(r,A.shareToken,!0),(R=t.onUpdated)==null||R.call(t,A)}catch(A){v(o,A.message,!0)}finally{v(i,!1)}}async function c(){confirm("Regenerate the link? The current QR code/link will stop working.")&&await u()}async function f(){var R;if(confirm("Turn off sharing? The current link/QR code will stop working.")){v(i,!0),v(o,"");try{await xr(`/cars/${t.car.id}/share`),v(r,null),(R=t.onUpdated)==null||R.call(t,{...t.car,shareToken:null})}catch(A){v(o,A.message,!0)}finally{v(i,!1)}}}async function m(){await navigator.clipboard.writeText(l(s)),v(a,!0),setTimeout(()=>v(a,!1),1500)}var d=af(),g=h(d),b=h(g),C=_(g,2);{var k=R=>{var A=ef(),p=h(A);U(()=>{A.disabled=l(i),O(A,1,j(Ht)),z(p,l(i)?"Generating…":"Turn on sharing")}),se("click",A,u),L(R,A)},S=R=>{var A=rf(),p=Pe(A),x=h(p);{var D=G=>{var Q=tf();U(()=>Ge(Q,"src",l(n))),L(G,Q)};V(x,G=>{l(n)&&G(D)})}var y=_(x,2),w=h(y),T=_(w,2),N=h(T),F=_(p,2),P=h(F),H=_(P,2);U(()=>{gu(w,l(s)),O(T,1,j(rr)),z(N,l(a)?"Copied!":"Copy"),P.disabled=l(i),O(P,1,j(rr)),H.disabled=l(i),O(H,1,j(vs))}),se("click",T,m),se("click",P,c),se("click",H,f),L(R,A)};V(C,R=>{l(r)?R(S,-1):R(k)})}var I=_(C,2);{var M=R=>{var A=nf(),p=h(A);U(()=>z(p,l(o))),L(R,A)};V(I,R=>{l(o)&&R(M)})}U(()=>z(b,`Share a read-only view of ${t.car.rego??""}'s service history (including attached docs) — no login required. Handy for + a QR code in the glovebox, or a link when selling the car.`)),L(e,d),Ce()}ze(["click"]);var sf=q('

        '),lf=q('
        ');function so(e,t){var A,p;Se(t,!0);let r=Be(t,"entry",3,null),n=B(ne(((A=r())==null?void 0:A.title)??"")),i=B(ne(((p=r())==null?void 0:p.body)??"")),a=B(!1),o=B("");async function s(x){var y;if(x.preventDefault(),!l(n).trim()){v(o,"Title is required");return}v(a,!0),v(o,"");const D={title:l(n).trim(),body:l(i)};try{r()?await en(`/knowledge/${r().id}`,D):await wr(`/cars/${t.carId}/knowledge`,D),(y=t.onSaved)==null||y.call(t)}catch(w){v(o,w.message,!0)}finally{v(a,!1)}}var u=lf(),c=h(u),f=h(c),m=_(f,2),d=_(c,2),g=h(d),b=_(g,2),C=_(d,2);{var k=x=>{var D=sf(),y=h(D);U(()=>z(y,l(o))),L(x,D)};V(C,x=>{l(o)&&x(k)})}var S=_(C,2),I=h(S),M=_(I,2),R=h(M);U(()=>{O(f,1,j(ye)),O(m,1,j(be)),O(g,1,j(ye)),O(b,1,j(be)),O(I,1,j(rr)),M.disabled=l(a),O(M,1,j(Ht)),z(R,l(a)?"Saving…":r()?"Save changes":"Add entry")}),br("submit",u,s),Ee(m,()=>l(n),x=>v(n,x)),Ee(b,()=>l(i),x=>v(i,x)),se("click",I,()=>{var x;return(x=t.onCancel)==null?void 0:x.call(t)}),L(e,u),Ce()}ze(["click"]);var uf=q('

        Loading…

        '),cf=q('

        '),ff=q('

        No knowledgebase entries yet — document procedures, common problems, or reference info like coolant type.

        '),df=q(''),vf=q(""),hf=q('
        ',1),gf=q('

        ',1),pf=q(" ",1);function mf(e,t){Se(t,!0);const r=20;let n=B(ne([])),i=B(!1),a=B(!0),o=B(!1),s=B(""),u=B(null),c=B(!1),f=B(null);async function m(){v(a,!0),v(s,"");try{const P=await He(`/cars/${t.carId}/knowledge?limit=${r}&offset=0`);v(n,P.items,!0),v(i,P.hasMore,!0)}catch(P){v(s,P.message,!0)}finally{v(a,!1)}}async function d(){v(o,!0);try{const P=await He(`/cars/${t.carId}/knowledge?limit=${r}&offset=${l(n).length}`);v(n,[...l(n),...P.items],!0),v(i,P.hasMore,!0)}catch(P){v(s,P.message,!0)}finally{v(o,!1)}}it(()=>{t.carId,m()});async function g(P){confirm(`Delete "${P.title}"?`)&&(await xr(`/knowledge/${P.id}`),v(u,null),m())}function b(){v(c,!1),v(f,null),m()}function C(P){v(u,null),v(f,P,!0)}var k=pf(),S=Pe(k);{var I=P=>{var H=uf();L(P,H)},M=P=>{var H=cf(),G=h(H);U(()=>z(G,l(s))),L(P,H)},R=P=>{var H=ff();L(P,H)},A=P=>{var H=hf(),G=Pe(H);zt(G,21,()=>l(n),X=>X.id,(X,J)=>{var $=df(),ue=h($),Z=h(ue),Y=h(Z),ie=_(Z,2),le=h(ie),fe=_(ue,2);_e(fe,{name:"chevronRight",class:"h-4 w-4 shrink-0 text-stone-400"}),U(he=>{z(Y,l(J).title),z(le,`Updated ${he??""}`)},[()=>It(l(J).updatedAt)]),se("click",$,()=>v(u,l(J),!0)),L(X,$)});var Q=_(G,2);{var oe=X=>{var J=vf(),$=h(J);_e($,{name:"chevronDown",class:"h-4 w-4"});var ue=_($);U(()=>{J.disabled=l(o),O(J,1,`${nr} mt-3 disabled:opacity-50`),z(ue,` ${l(o)?"Loading…":"Load more"}`)}),se("click",J,d),L(X,J)};V(Q,X=>{l(i)&&X(oe)})}L(P,H)};V(S,P=>{l(a)?P(I):l(s)?P(M,1):l(n).length===0?P(R,2):P(A,-1)})}var p=_(S,2),x=h(p);_e(x,{name:"plus",class:"h-4 w-4"});var D=_(p,2);{var y=P=>{yt(P,{get title(){return l(u).title},onClose:()=>v(u,null),wide:!0,children:(H,G)=>{var Q=gf(),oe=Pe(Q),X=h(oe),J=_(oe,2),$=h(J),ue=h($),Z=_($,2),Y=h(Z),ie=h(Y);_e(ie,{name:"pencil",class:"h-4 w-4"});var le=_(Y,2),fe=h(le);_e(fe,{name:"trash",class:"h-4 w-4"}),U(he=>{z(X,l(u).body),z(ue,`Updated ${he??""}`),O(Y,1,j(qt)),O(le,1,`${qt} hover:text-red-600`)},[()=>It(l(u).updatedAt)]),se("click",Y,()=>C(l(u))),se("click",le,()=>g(l(u))),L(H,Q)},$$slots:{default:!0}})};V(D,P=>{l(u)&&P(y)})}var w=_(D,2);{var T=P=>{yt(P,{title:"Add knowledge entry",onClose:()=>v(c,!1),children:(H,G)=>{so(H,{get carId(){return t.carId},onSaved:b,onCancel:()=>v(c,!1)})},$$slots:{default:!0}})};V(w,P=>{l(c)&&P(T)})}var N=_(w,2);{var F=P=>{yt(P,{title:"Edit knowledge entry",onClose:()=>v(f,null),children:(H,G)=>{so(H,{get carId(){return t.carId},get entry(){return l(f)},onSaved:b,onCancel:()=>v(f,null)})},$$slots:{default:!0}})};V(N,P=>{l(f)&&P(F)})}U(()=>O(p,1,`${nr} mt-3`)),se("click",p,()=>v(c,!0)),L(e,k),Ce()}ze(["click"]);var _f=q(' '),bf=q('
        Attached files
        '),yf=q('

        '),wf=q('

        '),xf=q(`
        `);function lo(e,t){var Ue,vt,ee,me,Ae,Oe,Pt,Ve;Se(t,!0);let r=Be(t,"entry",3,null),n=B(ne(((vt=(Ue=r())==null?void 0:Ue.entryDate)==null?void 0:vt.slice(0,10))??new Date().toISOString().slice(0,10))),i=B(ne(((ee=r())==null?void 0:ee.entryType)??"")),a=B(ne(((me=r())==null?void 0:me.performedAt)??"")),o=B(ne(((Ae=r())==null?void 0:Ae.odometer)??"")),s=B(ne(((Oe=r())==null?void 0:Oe.description)??"")),u=B(ne(((Pt=r())==null?void 0:Pt.isService)??!1)),c=B(ne([])),f=B(ne(((Ve=r())==null?void 0:Ve.files)??[])),m=B(!1),d=B("");function g(te){v(c,Array.from(te.target.files),!0)}async function b(te){confirm(`Remove "${te.fileName}"?`)&&(await xr(`/files/${te.id}`),v(f,l(f).filter(Re=>Re.id!==te.id),!0))}async function C(te){var Je;if(te.preventDefault(),!l(i).trim()){v(d,"Type is required");return}v(m,!0),v(d,"");const Re={entryDate:l(n),entryType:l(i).trim(),performedAt:l(a)||null,odometer:l(o)?Number(l(o)):null,description:l(s)||null,isService:l(u)};try{const Vt=r()?await en(`/service-entries/${r().id}`,Re):await wr(`/cars/${t.carId}/service-entries`,Re);for(const Kt of l(c))await ds(`/service-entries/${Vt.id}/files`,Kt);(Je=t.onSaved)==null||Je.call(t)}catch(Vt){v(d,Vt.message,!0)}finally{v(m,!1)}}var k=xf(),S=h(k),I=h(S),M=h(I),R=_(M,2),A=_(I,2),p=h(A),x=_(p,2),D=_(S,2),y=h(D),w=h(y),T=_(w,2),N=_(y,2),F=h(N),P=_(F,2),H=_(D,2),G=h(H),Q=_(G,2),oe=_(H,2),X=h(oe),J=_(oe,2);{var $=te=>{var Re=bf(),Je=h(Re),Vt=_(Je,2);zt(Vt,21,()=>l(f),Kt=>Kt.id,(Kt,Sr)=>{var tn=_f(),xe=h(tn);_e(xe,{name:"paperclip",class:"h-3.5 w-3.5 shrink-0"});var Rt=_(xe,2),Cr=h(Rt),Ar=_(Rt,2),xs=h(Ar);_e(xs,{name:"x",class:"h-3 w-3"}),U(Es=>{Ge(Rt,"href",Es),z(Cr,l(Sr).fileName)},[()=>Jr(`/files/${l(Sr).id}`)]),se("click",Ar,()=>b(l(Sr))),L(Kt,tn)}),U(()=>O(Je,1,j(ye))),L(te,Re)};V(J,te=>{l(f).length>0&&te($)})}var ue=_(J,2),Z=h(ue),Y=h(Z),ie=_(Z,2),le=_(ie,2);{var fe=te=>{var Re=yf(),Je=h(Re);U(()=>z(Je,`${l(c).length??""} file${l(c).length===1?"":"s"} selected`)),L(te,Re)};V(le,te=>{l(c).length>0&&te(fe)})}var he=_(ue,2);{var Ie=te=>{var Re=wf(),Je=h(Re);U(()=>z(Je,l(d))),L(te,Re)};V(he,te=>{l(d)&&te(Ie)})}var K=_(he,2),ce=h(K),pe=_(ce,2),$e=h(pe);U(()=>{O(M,1,j(ye)),O(R,1,j(be)),O(p,1,j(ye)),O(x,1,j(be)),O(w,1,j(ye)),O(T,1,j(be)),O(F,1,j(ye)),O(P,1,j(be)),O(G,1,j(ye)),O(Q,1,j(be)),O(Z,1,j(ye)),z(Y,l(f).length>0?"Attach more files (PNG/PDF)":"Attach files (PNG/PDF)"),O(ce,1,j(rr)),pe.disabled=l(m),O(pe,1,j(Ht)),z($e,l(m)?"Saving…":r()?"Save changes":"Add entry")}),br("submit",k,C),Ee(R,()=>l(n),te=>v(n,te)),Ee(x,()=>l(i),te=>v(i,te)),Ee(T,()=>l(a),te=>v(a,te)),Ee(P,()=>l(o),te=>v(o,te)),Ee(Q,()=>l(s),te=>v(s,te)),mu(X,()=>l(u),te=>v(u,te)),se("change",ie,g),se("click",ce,()=>{var te;return(te=t.onCancel)==null?void 0:te.call(t)}),L(e,k),Ce()}ze(["click","change"]);var Ef=q('

        Loading…

        '),kf=q('

        '),Sf=q(""),Cf=q(" ",1),Af=q(" ",1);function Tf(e,t){Se(t,!0);const r=20;let n=B(ne([])),i=B(!1),a=B(!0),o=B(!1),s=B(""),u=B(!1),c=B(null);async function f(){v(a,!0),v(s,"");try{const y=await He(`/cars/${t.carId}/service-entries?limit=${r}&offset=0`);v(n,y.items,!0),v(i,y.hasMore,!0)}catch(y){v(s,y.message,!0)}finally{v(a,!1)}}async function m(){v(o,!0);try{const y=await He(`/cars/${t.carId}/service-entries?limit=${r}&offset=${l(n).length}`);v(n,[...l(n),...y.items],!0),v(i,y.hasMore,!0)}catch(y){v(s,y.message,!0)}finally{v(o,!1)}}it(()=>{t.carId,f()});async function d(y){confirm(`Delete "${y.entryType}"?`)&&(await xr(`/service-entries/${y.id}`),f())}function g(){v(u,!1),v(c,null),f()}var b=Af(),C=Pe(b);{var k=y=>{var w=Ef();L(y,w)},S=y=>{var w=kf(),T=h(w);U(()=>z(T,l(s))),L(y,w)},I=y=>{var w=Cf(),T=Pe(w);gs(T,{get entries(){return l(n)},onEdit:P=>v(c,P,!0),onDelete:d});var N=_(T,2);{var F=P=>{var H=Sf(),G=h(H);_e(G,{name:"chevronDown",class:"h-4 w-4"});var Q=_(G);U(()=>{H.disabled=l(o),O(H,1,`${nr} mt-3 disabled:opacity-50`),z(Q,` ${l(o)?"Loading…":"Load more"}`)}),se("click",H,m),L(P,H)};V(N,P=>{l(i)&&P(F)})}L(y,w)};V(C,y=>{l(a)?y(k):l(s)?y(S,1):y(I,-1)})}var M=_(C,2),R=h(M);_e(R,{name:"plus",class:"h-4 w-4"});var A=_(M,2);{var p=y=>{yt(y,{title:"Add service entry",onClose:()=>v(u,!1),children:(w,T)=>{lo(w,{get carId(){return t.carId},onSaved:g,onCancel:()=>v(u,!1)})},$$slots:{default:!0}})};V(A,y=>{l(u)&&y(p)})}var x=_(A,2);{var D=y=>{yt(y,{title:"Edit service entry",onClose:()=>v(c,null),children:(w,T)=>{lo(w,{get carId(){return t.carId},get entry(){return l(c)},onSaved:g,onCancel:()=>v(c,null)})},$$slots:{default:!0}})};V(x,y=>{l(c)&&y(D)})}U(()=>O(M,1,`${nr} mt-3`)),se("click",M,()=>v(u,!0)),L(e,b),Ce()}ze(["click"]);var If=q('

        '),Mf=q('
        ');function uo(e,t){var Z,Y,ie,le,fe,he,Ie;Se(t,!0);let r=Be(t,"entry",3,null),n=B(ne(((Y=(Z=r())==null?void 0:Z.entryDate)==null?void 0:Y.slice(0,10))??new Date().toISOString().slice(0,10))),i=B(ne(((ie=r())==null?void 0:ie.litres)??"")),a=B(ne(((le=r())==null?void 0:le.cost)??"")),o=B(ne(((fe=r())==null?void 0:fe.odometer)??"")),s=B(ne(((he=r())==null?void 0:he.location)??"")),u=B(ne(((Ie=r())==null?void 0:Ie.notes)??"")),c=B(!1),f=B("");async function m(K){var pe;if(K.preventDefault(),!l(i)||Number(l(i))<=0){v(f,"Litres is required");return}if(!l(a)||Number(l(a))<=0){v(f,"Cost is required");return}v(c,!0),v(f,"");const ce={entryDate:l(n),litres:Number(l(i)),cost:Number(l(a)),odometer:l(o)?Number(l(o)):null,location:l(s)||null,notes:l(u)||null};try{r()?await en(`/fuel-entries/${r().id}`,ce):await wr(`/cars/${t.carId}/fuel-entries`,ce),(pe=t.onSaved)==null||pe.call(t)}catch($e){v(f,$e.message,!0)}finally{v(c,!1)}}var d=Mf(),g=h(d),b=h(g),C=h(b),k=_(C,2),S=_(b,2),I=h(S),M=_(I,2),R=_(g,2),A=h(R),p=h(A),x=_(p,2),D=_(A,2),y=h(D),w=_(y,2),T=_(D,2),N=h(T),F=_(N,2),P=_(R,2),H=h(P),G=_(H,2),Q=_(P,2);{var oe=K=>{var ce=If(),pe=h(ce);U(()=>z(pe,l(f))),L(K,ce)};V(Q,K=>{l(f)&&K(oe)})}var X=_(Q,2),J=h(X),$=_(J,2),ue=h($);U(()=>{O(C,1,j(ye)),O(k,1,j(be)),O(I,1,j(ye)),O(M,1,j(be)),O(p,1,j(ye)),O(x,1,j(be)),O(y,1,j(ye)),O(w,1,j(be)),O(N,1,j(ye)),O(F,1,j(be)),O(H,1,j(ye)),O(G,1,j(be)),O(J,1,j(rr)),$.disabled=l(c),O($,1,j(Ht)),z(ue,l(c)?"Saving…":r()?"Save changes":"Add fuel-up")}),br("submit",d,m),Ee(k,()=>l(n),K=>v(n,K)),Ee(M,()=>l(s),K=>v(s,K)),Ee(x,()=>l(i),K=>v(i,K)),Ee(w,()=>l(a),K=>v(a,K)),Ee(F,()=>l(o),K=>v(o,K)),Ee(G,()=>l(u),K=>v(u,K)),se("click",J,()=>{var K;return(K=t.onCancel)==null?void 0:K.call(t)}),L(e,d),Ce()}ze(["click"]);var Pf=q('

        Loading…

        '),Rf=q('

        '),Nf=q('

        This month

        Last 14 days

        Avg price/L

        Avg L/100km

        '),Lf=q('

        No fuel-ups logged yet.

        '),Df=q('
      • '),Bf=q(""),Ff=q('
          ',1),Of=q(" ",1),qf=q(" ",1);function jf(e,t){Se(t,!0);const r=20;let n=B(ne([])),i=B(!1),a=B(!0),o=B(!1),s=B(""),u=B(!1),c=B(null);async function f(){v(a,!0),v(s,"");try{const w=await He(`/cars/${t.carId}/fuel-entries?limit=${r}&offset=0`);v(n,w.items,!0),v(i,w.hasMore,!0)}catch(w){v(s,w.message,!0)}finally{v(a,!1)}}async function m(){v(o,!0);try{const w=await He(`/cars/${t.carId}/fuel-entries?limit=${r}&offset=${l(n).length}`);v(n,[...l(n),...w.items],!0),v(i,w.hasMore,!0)}catch(w){v(s,w.message,!0)}finally{v(o,!1)}}it(()=>{t.carId,f()});async function d(w){confirm(`Delete this fuel entry from ${It(w.entryDate)}?`)&&(await xr(`/fuel-entries/${w.id}`),f())}function g(){v(u,!1),v(c,null),f()}let b=Ct(()=>{const w=new Date,T=new Date(w.getFullYear(),w.getMonth(),1),N=new Date(w);N.setDate(w.getDate()-14);let F=0,P=0,H=0,G=0;for(const J of l(n)){const $=new Date(J.entryDate);H+=J.cost,G+=J.litres,$>=T&&(F+=J.cost),$>=N&&(P+=J.cost)}const Q=G>0?H/G:null,oe=l(n).filter(J=>J.odometer!=null).slice().sort((J,$)=>J.odometer-$.odometer);let X=null;if(oe.length>=2){const J=oe[0],$=oe[oe.length-1],ue=$.odometer-J.odometer,Z=l(n).filter(Y=>Y.odometer>J.odometer&&Y.odometer<=$.odometer).reduce((Y,ie)=>Y+ie.litres,0);ue>0&&Z>0&&(X=Z/ue*100)}return{monthCost:F,fortnightCost:P,avgPricePerLitre:Q,avgL100km:X}});var C=qf(),k=Pe(C);{var S=w=>{var T=Pf();L(w,T)},I=w=>{var T=Rf(),N=h(T);U(()=>z(N,l(s))),L(w,T)},M=w=>{var T=Of(),N=Pe(T);{var F=Q=>{var oe=Nf(),X=h(oe),J=_(h(X),2),$=h(J),ue=_(X,2),Z=_(h(ue),2),Y=h(Z),ie=_(ue,2),le=_(h(ie),2),fe=h(le),he=_(ie,2),Ie=_(h(he),2),K=h(Ie);U((ce,pe,$e,Ue)=>{z($,`$${ce??""}`),z(Y,`$${pe??""}`),z(fe,$e),z(K,Ue)},[()=>l(b).monthCost.toFixed(2),()=>l(b).fortnightCost.toFixed(2),()=>l(b).avgPricePerLitre!=null?`$${l(b).avgPricePerLitre.toFixed(2)}`:"—",()=>l(b).avgL100km!=null?l(b).avgL100km.toFixed(1):"—"]),L(Q,oe)};V(N,Q=>{l(n).length>0&&Q(F)})}var P=_(N,2);{var H=Q=>{var oe=Lf();L(Q,oe)},G=Q=>{var oe=Ff(),X=Pe(oe);zt(X,21,()=>l(n),ue=>ue.id,(ue,Z)=>{var Y=Df(),ie=h(Y),le=h(ie),fe=h(le),he=_(fe),Ie=h(he),K=_(le,2),ce=h(K),pe=_(ce);{var $e=Ve=>{var te=Gr();U(()=>z(te,`· ${l(Z).location??""}`)),L(Ve,te)};V(pe,Ve=>{l(Z).location&&Ve($e)})}var Ue=_(pe,2);{var vt=Ve=>{var te=Gr();U(Re=>z(te,`· ${Re??""} km`),[()=>l(Z).odometer.toLocaleString()]),L(Ve,te)};V(Ue,Ve=>{l(Z).odometer&&Ve(vt)})}var ee=_(ie,2),me=h(ee),Ae=h(me);_e(Ae,{name:"pencil",class:"h-4 w-4"});var Oe=_(me,2),Pt=h(Oe);_e(Pt,{name:"trash",class:"h-4 w-4"}),U((Ve,te,Re,Je)=>{z(fe,`${Ve??""} L · $${te??""} `),z(Ie,`($${Re??""}/L)`),z(ce,`${Je??""} `),O(me,1,j(qt)),O(Oe,1,`${qt} hover:text-red-600`)},[()=>l(Z).litres.toFixed(1),()=>l(Z).cost.toFixed(2),()=>(l(Z).cost/l(Z).litres).toFixed(2),()=>It(l(Z).entryDate)]),se("click",me,()=>v(c,l(Z),!0)),se("click",Oe,()=>d(l(Z))),L(ue,Y)});var J=_(X,2);{var $=ue=>{var Z=Bf(),Y=h(Z);_e(Y,{name:"chevronDown",class:"h-4 w-4"});var ie=_(Y);U(()=>{Z.disabled=l(o),O(Z,1,`${nr} mt-3 disabled:opacity-50`),z(ie,` ${l(o)?"Loading…":"Load more"}`)}),se("click",Z,m),L(ue,Z)};V(J,ue=>{l(i)&&ue($)})}L(Q,oe)};V(P,Q=>{l(n).length===0?Q(H):Q(G,-1)})}L(w,T)};V(k,w=>{l(a)?w(S):l(s)?w(I,1):w(M,-1)})}var R=_(k,2),A=h(R);_e(A,{name:"plus",class:"h-4 w-4"});var p=_(R,2);{var x=w=>{yt(w,{title:"Add fuel-up",onClose:()=>v(u,!1),children:(T,N)=>{uo(T,{get carId(){return t.carId},onSaved:g,onCancel:()=>v(u,!1)})},$$slots:{default:!0}})};V(p,w=>{l(u)&&w(x)})}var D=_(p,2);{var y=w=>{yt(w,{title:"Edit fuel-up",onClose:()=>v(c,null),children:(T,N)=>{uo(T,{get carId(){return t.carId},get entry(){return l(c)},onSaved:g,onCancel:()=>v(c,null)})},$$slots:{default:!0}})};V(D,w=>{l(c)&&w(y)})}U(()=>O(R,1,`${nr} mt-3`)),se("click",R,()=>v(u,!0)),L(e,C),Ce()}ze(["click"]);var Uf=q('

          Loading…

          '),Hf=q('

          '),zf=q('
          '),Vf=q(''),Kf=q('

          Estimated usage

          '),Yf=q(' '),Gf=q('

          Next 100,000 km

          At your current rate, from today — not tied to a round odometer number.

          '),Jf=q('

          Log a service or fuel-up with an odometer reading (from a different date) to start estimating your usage rate.

          '),Wf=q('

          Odometer

          ',1),Qf=q('
          ');function Zf(e,t){Se(t,!0);let r=B(null),n=B(!0),i=B(""),a=B(!1),o=B(""),s=B(!1);async function u(){v(n,!0),v(i,"");try{v(r,await He(`/cars/${t.carId}/mileage`),!0)}catch(k){v(i,k.message,!0)}finally{v(n,!1)}}it(()=>{t.carId,u()});function c(){v(o,t.odometer??"",!0),v(a,!0)}async function f(k){var S;if(k.preventDefault(),!(l(o)===""||Number(l(o))<0)){v(s,!0);try{await Eu(`/cars/${t.carId}/odometer`,{odometer:Number(l(o))}),v(a,!1),await u(),(S=t.onUpdated)==null||S.call(t)}catch(I){v(i,I.message,!0)}finally{v(s,!1)}}}var m=Qf(),d=h(m);{var g=k=>{var S=Uf();L(k,S)},b=k=>{var S=Hf(),I=h(S);U(()=>z(I,l(i))),L(k,S)},C=k=>{var S=Wf(),I=Pe(S),M=_(h(I),2);{var R=T=>{var N=zf(),F=h(N);ml(F);var P=_(F,2),H=h(P),G=_(P,2);U(()=>{O(F,1,`${be} w-32 py-1`),P.disabled=l(s),O(P,1,`${Ht} px-3 py-1 text-sm`),z(H,l(s)?"Saving…":"Save")}),br("submit",N,f),Ee(F,()=>l(o),Q=>v(o,Q)),se("click",G,()=>v(a,!1)),L(T,N)},A=T=>{var N=Vf(),F=h(N),P=_(F);_e(P,{name:"pencil",class:"h-3.5 w-3.5 text-stone-400"}),U(H=>z(F,`${H??""} `),[()=>l(r).currentOdometer!=null?`${l(r).currentOdometer.toLocaleString()} km`:"Not set"]),se("click",N,c),L(T,N)};V(M,T=>{l(a)?T(R):T(A,-1)})}var p=_(I,2);{var x=T=>{var N=Kf(),F=_(h(N),2),P=h(F);U(H=>z(P,`~${H??""} km/year`),[()=>Math.round(l(r).kmPerYear).toLocaleString()]),L(T,N)};V(p,T=>{l(r).kmPerYear&&T(x)})}var D=_(p,2);{var y=T=>{var N=Gf(),F=_(h(N),2),P=h(F),H=_(P);{var G=Q=>{var oe=Yf(),X=h(oe);U(J=>z(X,`· by ~${J??""}`),[()=>It(l(r).next100kEta)]),L(Q,oe)};V(H,Q=>{l(r).next100kEta&&Q(G)})}U(Q=>z(P,`~${Q??""} years `),[()=>l(r).yearsPer100k.toFixed(1)]),L(T,N)},w=T=>{var N=Jf();L(T,N)};V(D,T=>{l(r).yearsPer100k?T(y):T(w,-1)})}L(k,S)};V(d,k=>{l(n)?k(g):l(i)?k(b,1):l(r)&&k(C,2)})}L(e,m),Ce()}ze(["click"]);var Xf=q('

          Loading…

          '),$f=q('

          '),co=q(" "),ed=q(""),td=q('

          Edit
          ',1);function rd(e,t){Se(t,!0);let r=Ct(()=>t.params.id),n=B(null),i=B(!0),a=B(""),o=B(!1),s=B(!1);const u=[{key:"reminders",label:"Reminders",icon:"check"},{key:"knowledge",label:"Knowledgebase",icon:"bookOpen"},{key:"service",label:"Service history",icon:"paperclip"},{key:"fuel",label:"Fuel",icon:"fuel"}];let c=B("reminders");async function f(){v(n,await He(`/cars/${l(r)}`),!0)}it(()=>{l(r),v(i,!0),v(a,""),f().catch(I=>v(a,I.message,!0)).finally(()=>v(i,!1))});async function m(){confirm(`Delete ${l(n).rego} and all its history? This can't be undone.`)&&(await xr(`/cars/${l(r)}`),ua("/"))}function d(I,M){const R=Gi(I);let A="border-stone-200 text-stone-600";return R!==null&&(R<0?A="border-red-200 bg-red-50 text-red-700":R<=30&&(A="border-amber-200 bg-amber-50 text-amber-700")),{text:`${M} ${It(I)}`,tone:A}}var g=Zt(),b=Pe(g);{var C=I=>{var M=Xf();L(I,M)},k=I=>{var M=$f(),R=h(M);U(()=>z(R,l(a))),L(I,M)},S=I=>{var M=td(),R=Pe(M),A=h(R);Ic(A,{get carId(){return l(r)},get hasPhoto(){return l(n).hasPhoto},get alt(){return l(n).rego},onUploaded:f});var p=_(A,2),x=h(p),D=h(x);ca(D,{get rego(){return l(n).rego},size:"lg"});var y=_(D,2),w=h(y),T=_(y,2),N=h(T);{var F=ee=>{const me=Ct(()=>d(l(n).regoExpiry,"Rego"));var Ae=co(),Oe=h(Ae);U(()=>{O(Ae,1,`rounded-full border px-2.5 py-0.5 text-xs font-medium ${l(me).tone??""}`),z(Oe,l(me).text)}),L(ee,Ae)};V(N,ee=>{l(n).regoExpiry&&ee(F)})}var P=_(N,2);{var H=ee=>{const me=Ct(()=>d(l(n).wofExpiry,"WoF"));var Ae=co(),Oe=h(Ae);U(()=>{O(Ae,1,`rounded-full border px-2.5 py-0.5 text-xs font-medium ${l(me).tone??""}`),z(Oe,l(me).text)}),L(ee,Ae)};V(P,ee=>{l(n).wofExpiry&&ee(H)})}var G=_(P,2),Q=h(G),oe=_(x,2),X=h(oe),J=h(X);_e(J,{name:"share",class:"h-4 w-4"});var $=_(X,2),ue=h($);_e(ue,{name:"pencil",class:"h-4 w-4"});var Z=_($,2),Y=h(Z);_e(Y,{name:"trash",class:"h-4 w-4"});var ie=_(p,2);zt(ie,21,()=>u,ee=>ee.key,(ee,me)=>{var Ae=ed(),Oe=h(Ae);_e(Oe,{get name(){return l(me).icon},class:"h-4 w-4"});var Pt=_(Oe);U(()=>{O(Ae,1,`flex shrink-0 items-center gap-1.5 border-b-2 px-3 py-2.5 text-sm font-medium transition-colors + ${l(c)===l(me).key?"border-teal-700 text-teal-700":"border-transparent text-stone-500 hover:border-stone-300 hover:text-stone-900"}`),z(Pt,` ${l(me).label??""}`)}),se("click",Ae,()=>v(c,l(me).key,!0)),L(ee,Ae)});var le=_(ie,2),fe=h(le);{var he=ee=>{ps(ee,{get carId(){return l(r)}})},Ie=ee=>{mf(ee,{get carId(){return l(r)}})},K=ee=>{Tf(ee,{get carId(){return l(r)}})},ce=ee=>{jf(ee,{get carId(){return l(r)}})};V(fe,ee=>{l(c)==="reminders"?ee(he):l(c)==="knowledge"?ee(Ie,1):l(c)==="service"?ee(K,2):l(c)==="fuel"&&ee(ce,3)})}var pe=_(R,2);{var $e=ee=>{yt(ee,{get title(){return`Share ${l(n).rego??""}`},onClose:()=>v(o,!1),children:(me,Ae)=>{of(me,{get car(){return l(n)},onUpdated:Oe=>v(n,Oe,!0)})},$$slots:{default:!0}})};V(pe,ee=>{l(o)&&ee($e)})}var Ue=_(pe,2);{var vt=ee=>{yt(ee,{title:"Mileage",onClose:()=>v(s,!1),children:(me,Ae)=>{Zf(me,{get carId(){return l(r)},get odometer(){return l(n).odometer},onUpdated:f})},$$slots:{default:!0}})};V(Ue,ee=>{l(s)&&ee(vt)})}U((ee,me)=>{z(w,`${ee??""}${l(n).color?` · ${l(n).color}`:""}`),z(Q,me),O(X,1,j(rr)),Ge($,"href",`#/cars/${l(r)??""}/edit`),O($,1,j(rr)),O(Z,1,j(vs)),O(le,1,j(hs))},[()=>[l(n).year,l(n).make,l(n).model].filter(Boolean).join(" "),()=>l(n).odometer?`${l(n).odometer.toLocaleString()} km`:"Set odometer"]),se("click",G,()=>v(s,!0)),se("click",X,()=>v(o,!0)),se("click",Z,m),L(I,M)};V(b,I=>{l(i)?I(C):l(a)?I(k,1):l(n)&&I(S,2)})}L(e,g),Ce()}ze(["click"]);var nd=q('

          '),id=q('
          Service interval (optional)

          Whichever comes first triggers a reminder, counted from the last entry marked "full service".

          ');function ws(e,t){var Oe,Pt,Ve,te,Re,Je,Vt,Kt,Sr,tn;Se(t,!0);let r=Be(t,"car",3,null),n=B(ne(((Oe=r())==null?void 0:Oe.rego)??"")),i=B(ne(((Pt=r())==null?void 0:Pt.make)??"")),a=B(ne(((Ve=r())==null?void 0:Ve.model)??"")),o=B(ne(((te=r())==null?void 0:te.year)??"")),s=B(ne(((Re=r())==null?void 0:Re.color)??"")),u=B(ne(((Je=r())==null?void 0:Je.odometer)??"")),c=B(ne((Vt=r())!=null&&Vt.regoExpiry?r().regoExpiry.slice(0,10):"")),f=B(ne((Kt=r())!=null&&Kt.wofExpiry?r().wofExpiry.slice(0,10):"")),m=B(ne(((Sr=r())==null?void 0:Sr.serviceIntervalKm)??"")),d=B(ne(((tn=r())==null?void 0:tn.serviceIntervalMonths)??"")),g=B(!1),b=B("");async function C(xe){var Cr;if(xe.preventDefault(),!l(n).trim()){v(b,"Rego is required");return}v(g,!0),v(b,"");const Rt={rego:l(n).trim(),make:l(i)||null,model:l(a)||null,year:l(o)?Number(l(o)):null,color:l(s)||null,odometer:l(u)?Number(l(u)):null,regoExpiry:l(c)||null,wofExpiry:l(f)||null,serviceIntervalKm:l(m)?Number(l(m)):null,serviceIntervalMonths:l(d)?Number(l(d)):null};try{const Ar=r()?await en(`/cars/${r().id}`,Rt):await wr("/cars",Rt);(Cr=t.onSave)==null||Cr.call(t,Ar)}catch(Ar){v(b,Ar.message,!0)}finally{v(g,!1)}}var k=id(),S=h(k),I=h(S),M=_(I,2),R=_(S,2),A=h(R),p=h(A),x=_(p,2),D=_(A,2),y=h(D),w=_(y,2),T=_(R,2),N=h(T),F=h(N),P=_(F,2),H=_(N,2),G=h(H),Q=_(G,2),oe=_(H,2),X=h(oe),J=_(X,2),$=_(T,2),ue=h($),Z=h(ue),Y=_(Z,2),ie=_(ue,2),le=h(ie),fe=_(le,2),he=_($,2),Ie=h(he),K=_(Ie,4),ce=h(K),pe=_(h(ce),2),$e=_(ce,2),Ue=_(h($e),2),vt=_(he,2);{var ee=xe=>{var Rt=nd(),Cr=h(Rt);U(()=>z(Cr,l(b))),L(xe,Rt)};V(vt,xe=>{l(b)&&xe(ee)})}var me=_(vt,2),Ae=h(me);U(()=>{O(I,1,j(ye)),O(M,1,j(be)),O(p,1,j(ye)),O(x,1,j(be)),O(y,1,j(ye)),O(w,1,j(be)),O(F,1,j(ye)),O(P,1,j(be)),O(G,1,j(ye)),O(Q,1,j(be)),O(X,1,j(ye)),O(J,1,j(be)),O(Z,1,j(ye)),O(Y,1,j(be)),O(le,1,j(ye)),O(fe,1,j(be)),O(Ie,1,j(ye)),O(pe,1,j(be)),O(Ue,1,j(be)),me.disabled=l(g),O(me,1,j(Ht)),z(Ae,l(g)?"Saving…":r()?"Save changes":"Create car")}),br("submit",k,C),Ee(M,()=>l(n),xe=>v(n,xe)),Ee(x,()=>l(i),xe=>v(i,xe)),Ee(w,()=>l(a),xe=>v(a,xe)),Ee(P,()=>l(o),xe=>v(o,xe)),Ee(Q,()=>l(s),xe=>v(s,xe)),Ee(J,()=>l(u),xe=>v(u,xe)),Ee(Y,()=>l(c),xe=>v(c,xe)),Ee(fe,()=>l(f),xe=>v(f,xe)),Ee(pe,()=>l(m),xe=>v(m,xe)),Ee(Ue,()=>l(d),xe=>v(d,xe)),L(e,k),Ce()}var ad=q('

          Add a car

          ');function od(e,t){Se(t,!1);function r(o){ua(`/cars/${o.id}`)}_u();var n=ad(),i=_(h(n),2),a=h(i);ws(a,{onSave:r}),U(()=>O(i,1,`${Xn} p-5`)),L(e,n),Ce()}var sd=q('

          Loading…

          '),ld=q('

          '),ud=q("
          "),cd=q('

          Edit car

          ');function fd(e,t){Se(t,!0);let r=B(null),n=B(!0),i=B("");fs(async()=>{try{v(r,await He(`/cars/${t.params.id}`),!0)}catch(m){v(i,m.message,!0)}finally{v(n,!1)}});function a(){ua(`/cars/${t.params.id}`)}var o=cd(),s=_(h(o),2);{var u=m=>{var d=sd();L(m,d)},c=m=>{var d=ld(),g=h(d);U(()=>z(g,l(i))),L(m,d)},f=m=>{var d=ud(),g=h(d);ws(g,{get car(){return l(r)},onSave:a}),U(()=>O(d,1,`${Xn} p-5`)),L(m,d)};V(s,m=>{l(n)?m(u):l(i)?m(c,1):m(f,-1)})}L(e,o),Ce()}var dd=q('
          Loading…
          '),vd=q('
          ');function hd(e,t){Se(t,!0);const r=()=>vl(oi,"$user",n),[n,i]=hl(),a={"/":kc,"/cars/new":od,"/cars/:id/edit":fd,"/cars/:id":rd,"/share/:token":Ju};let o=B(ne(window.location.hash.startsWith("#/share/")));window.addEventListener("hashchange",()=>{v(o,window.location.hash.startsWith("#/share/"),!0)});let s=B(!0),u=B(!1);async function c(){try{ga(oi,await He("/me")),v(u,!0)}catch{v(u,!1)}finally{v(s,!1)}}l(o)?v(s,!1):c();async function f(){await wr("/auth/logout",{}),ga(oi,null),v(u,!1)}function m(I,M){return(I||M||"?").split(/\s+/).map(A=>A[0]).slice(0,2).join("").toUpperCase()}var d=Zt(),g=Pe(d);{var b=I=>{Pa(I,{get routes(){return a}})},C=I=>{var M=dd();L(I,M)},k=I=>{Su(I)},S=I=>{var M=vd(),R=_(h(M),2),A=h(R),p=_(h(A),2),x=h(p),D=h(x),y=_(x,2),w=_(R,2),T=h(w);Pa(T,{get routes(){return a}}),U(N=>z(D,N),[()=>{var N,F;return m((N=r())==null?void 0:N.name,(F=r())==null?void 0:F.email)}]),se("click",y,f),L(I,M)};V(g,I=>{l(o)?I(b):l(s)?I(C,1):l(u)?I(S,-1):I(k,2)})}L(e,d),Ce(),i()}ze(["click"]);tu(hd,{target:document.getElementById("app")}); diff --git a/backend/cmd/previewserver/web/assets/index-N5TiDU3Y.css b/backend/cmd/previewserver/web/assets/index-N5TiDU3Y.css new file mode 100644 index 0000000..edc50ee --- /dev/null +++ b/backend/cmd/previewserver/web/assets/index-N5TiDU3Y.css @@ -0,0 +1 @@ +/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-200:oklch(88.5% .062 18.334);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-200:oklch(92.4% .12 95.746);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-700:oklch(55.5% .163 48.998);--color-teal-50:oklch(98.4% .014 180.72);--color-teal-100:oklch(95.3% .051 180.801);--color-teal-500:oklch(70.4% .14 182.503);--color-teal-600:oklch(60% .118 184.704);--color-teal-700:oklch(51.1% .096 186.391);--color-teal-800:oklch(43.7% .078 188.216);--color-teal-900:oklch(38.6% .063 188.416);--color-stone-50:oklch(98.5% .001 106.423);--color-stone-100:oklch(97% .001 106.424);--color-stone-200:oklch(92.3% .003 48.717);--color-stone-300:oklch(86.9% .005 56.366);--color-stone-400:oklch(70.9% .01 56.259);--color-stone-500:oklch(55.3% .013 58.071);--color-stone-600:oklch(44.4% .011 73.639);--color-stone-700:oklch(37.4% .01 67.558);--color-stone-900:oklch(21.6% .006 56.043);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-2xl:42rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--text-5xl:3rem;--text-5xl--line-height:1;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wide:.025em;--tracking-wider:.05em;--tracking-widest:.1em;--radius-md:.375rem;--radius-lg:.5rem;--blur-sm:8px;--aspect-video:16 / 9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.top-2{top:calc(var(--spacing) * 2)}.right-2{right:calc(var(--spacing) * 2)}.z-50{z-index:50}.mx-4{margin-inline:calc(var(--spacing) * 4)}.mx-auto{margin-inline:auto}.my-8{margin-block:calc(var(--spacing) * 8)}.-mt-1{margin-top:calc(var(--spacing) * -1)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:var(--spacing)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mb-1{margin-bottom:var(--spacing)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.aspect-\[21\/9\]{aspect-ratio:21/9}.aspect-video{aspect-ratio:var(--aspect-video)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2\.5{height:calc(var(--spacing) * 2.5)}.h-3{height:calc(var(--spacing) * 3)}.h-3\.5{height:calc(var(--spacing) * 3.5)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-14{height:calc(var(--spacing) * 14)}.h-20{height:calc(var(--spacing) * 20)}.h-48{height:calc(var(--spacing) * 48)}.h-full{height:100%}.max-h-\[75vh\]{max-height:75vh}.min-h-screen{min-height:100vh}.w-2\.5{width:calc(var(--spacing) * 2.5)}.w-3{width:calc(var(--spacing) * 3)}.w-3\.5{width:calc(var(--spacing) * 3.5)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-7{width:calc(var(--spacing) * 7)}.w-8{width:calc(var(--spacing) * 8)}.w-14{width:calc(var(--spacing) * 14)}.w-28{width:calc(var(--spacing) * 28)}.w-32{width:calc(var(--spacing) * 32)}.w-48{width:calc(var(--spacing) * 48)}.w-full{width:100%}.w-px{width:1px}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-sm{max-width:var(--container-sm)}.min-w-0{min-width:0}.flex-1{flex:1}.shrink-0{flex-shrink:0}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-8>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 8) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 8) * calc(1 - var(--tw-space-y-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-stone-100>:not(:last-child)){border-color:var(--color-stone-100)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-t-4{border-top-style:var(--tw-border-style);border-top-width:4px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-amber-200{border-color:var(--color-amber-200)}.border-red-200{border-color:var(--color-red-200)}.border-stone-100{border-color:var(--color-stone-100)}.border-stone-200{border-color:var(--color-stone-200)}.border-stone-300{border-color:var(--color-stone-300)}.border-stone-900{border-color:var(--color-stone-900)}.border-teal-700{border-color:var(--color-teal-700)}.border-transparent{border-color:#0000}.border-t-teal-700{border-top-color:var(--color-teal-700)}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-amber-500{background-color:var(--color-amber-500)}.bg-black\/0{background-color:#0000}@supports (color:color-mix(in lab,red,red)){.bg-black\/0{background-color:color-mix(in oklab,var(--color-black) 0%,transparent)}}.bg-red-50{background-color:var(--color-red-50)}.bg-red-100{background-color:var(--color-red-100)}.bg-red-600{background-color:var(--color-red-600)}.bg-stone-50{background-color:var(--color-stone-50)}.bg-stone-100{background-color:var(--color-stone-100)}.bg-stone-200{background-color:var(--color-stone-200)}.bg-stone-900\/60{background-color:#1c191799}@supports (color:color-mix(in lab,red,red)){.bg-stone-900\/60{background-color:color-mix(in oklab,var(--color-stone-900) 60%,transparent)}}.bg-teal-100{background-color:var(--color-teal-100)}.bg-teal-700{background-color:var(--color-teal-700)}.bg-white{background-color:var(--color-white)}.bg-white\/90{background-color:#ffffffe6}@supports (color:color-mix(in lab,red,red)){.bg-white\/90{background-color:color-mix(in oklab,var(--color-white) 90%,transparent)}}.bg-gradient-to-b{--tw-gradient-position:to bottom in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-white{--tw-gradient-from:var(--color-white);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-stone-100{--tw-gradient-to:var(--color-stone-100);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.object-cover{object-fit:cover}.p-0\.5{padding:calc(var(--spacing) * .5)}.p-1{padding:var(--spacing)}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-8{padding:calc(var(--spacing) * 8)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.py-12{padding-block:calc(var(--spacing) * 12)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pr-1{padding-right:var(--spacing)}.pb-6{padding-bottom:calc(var(--spacing) * 6)}.pl-2{padding-left:calc(var(--spacing) * 2)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-5xl{font-size:var(--text-5xl);line-height:var(--tw-leading,var(--text-5xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.whitespace-pre-wrap{white-space:pre-wrap}.text-amber-700{color:var(--color-amber-700)}.text-red-600{color:var(--color-red-600)}.text-red-700{color:var(--color-red-700)}.text-stone-400{color:var(--color-stone-400)}.text-stone-500{color:var(--color-stone-500)}.text-stone-600{color:var(--color-stone-600)}.text-stone-700{color:var(--color-stone-700)}.text-stone-900{color:var(--color-stone-900)}.text-teal-600{color:var(--color-teal-600)}.text-teal-700{color:var(--color-teal-700)}.text-white{color:var(--color-white)}.uppercase{text-transform:uppercase}.placeholder-stone-400::placeholder{color:var(--color-stone-400)}.opacity-0{opacity:0}.opacity-30{opacity:.3}.shadow,.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-teal-900\/20{--tw-shadow-color:#0b4f4a33}@supports (color:color-mix(in lab,red,red)){.shadow-teal-900\/20{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-teal-900) 20%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-teal-900\/30{--tw-shadow-color:#0b4f4a4d}@supports (color:color-mix(in lab,red,red)){.shadow-teal-900\/30{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-teal-900) 30%, transparent) var(--tw-shadow-alpha), transparent)}}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-shadow{transition-property:box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}@media(hover:hover){.group-hover\:scale-105:is(:where(.group):hover *){--tw-scale-x:105%;--tw-scale-y:105%;--tw-scale-z:105%;scale:var(--tw-scale-x) var(--tw-scale-y)}.group-hover\:bg-black\/40:is(:where(.group):hover *){background-color:#0006}@supports (color:color-mix(in lab,red,red)){.group-hover\:bg-black\/40:is(:where(.group):hover *){background-color:color-mix(in oklab,var(--color-black) 40%,transparent)}}.group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}.file\:mr-3::file-selector-button{margin-right:calc(var(--spacing) * 3)}.file\:rounded-lg::file-selector-button{border-radius:var(--radius-lg)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0}.file\:bg-stone-100::file-selector-button{background-color:var(--color-stone-100)}.file\:px-3::file-selector-button{padding-inline:calc(var(--spacing) * 3)}.file\:py-1\.5::file-selector-button{padding-block:calc(var(--spacing) * 1.5)}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.file\:text-stone-700::file-selector-button{color:var(--color-stone-700)}.first\:pt-0:first-child{padding-top:0}.last\:pb-0:last-child{padding-bottom:0}@media(hover:hover){.hover\:-translate-y-0\.5:hover{--tw-translate-y:calc(var(--spacing) * -.5);translate:var(--tw-translate-x) var(--tw-translate-y)}.hover\:border-stone-300:hover{border-color:var(--color-stone-300)}.hover\:border-teal-600:hover{border-color:var(--color-teal-600)}.hover\:bg-red-50:hover{background-color:var(--color-red-50)}.hover\:bg-stone-50:hover{background-color:var(--color-stone-50)}.hover\:bg-stone-100:hover{background-color:var(--color-stone-100)}.hover\:bg-teal-50:hover{background-color:var(--color-teal-50)}.hover\:bg-teal-50\/50:hover{background-color:#f0fdfa80}@supports (color:color-mix(in lab,red,red)){.hover\:bg-teal-50\/50:hover{background-color:color-mix(in oklab,var(--color-teal-50) 50%,transparent)}}.hover\:bg-teal-600:hover{background-color:var(--color-teal-600)}.hover\:text-red-600:hover{color:var(--color-red-600)}.hover\:text-stone-600:hover{color:var(--color-stone-600)}.hover\:text-stone-700:hover{color:var(--color-stone-700)}.hover\:text-stone-900:hover{color:var(--color-stone-900)}.hover\:text-teal-700:hover{color:var(--color-teal-700)}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-lg:hover{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.hover\:file\:bg-stone-200:hover::file-selector-button{background-color:var(--color-stone-200)}}.focus\:border-teal-500:focus{border-color:var(--color-teal-500)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-teal-500\/40:focus{--tw-ring-color:#00baa766}@supports (color:color-mix(in lab,red,red)){.focus\:ring-teal-500\/40:focus{--tw-ring-color:color-mix(in oklab, var(--color-teal-500) 40%, transparent)}}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.active\:bg-teal-800:active{background-color:var(--color-teal-800)}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:opacity-50:disabled{opacity:.5}@media(min-width:40rem){.sm\:my-0{margin-block:0}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:items-center{align-items:center}.sm\:p-6{padding:calc(var(--spacing) * 6)}}@media(min-width:64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0} diff --git a/backend/cmd/previewserver/web/index.html b/backend/cmd/previewserver/web/index.html new file mode 100644 index 0000000..41f54c2 --- /dev/null +++ b/backend/cmd/previewserver/web/index.html @@ -0,0 +1,13 @@ + + + + + + My Garage + + + + +
          + + diff --git a/backend/cmd/server/embed.go b/backend/cmd/server/embed.go new file mode 100644 index 0000000..e22ab5f --- /dev/null +++ b/backend/cmd/server/embed.go @@ -0,0 +1,10 @@ +package main + +import "embed" + +// frontendFS holds the built Svelte SPA (frontend/dist contents, copied into +// ./web at build time — see backend/Dockerfile and scripts/build-frontend.sh). +// Embedding it means the whole app ships as one binary/container. +// +//go:embed all:web +var frontendFS embed.FS diff --git a/backend/cmd/server/integration_test.go b/backend/cmd/server/integration_test.go new file mode 100644 index 0000000..2f25a31 --- /dev/null +++ b/backend/cmd/server/integration_test.go @@ -0,0 +1,687 @@ +package main + +// End-to-end smoke test against SQLite + local-disk storage — the +// DB_DRIVER=sqlite / STORAGE_DRIVER=local combination that lets this app be +// tested with no external services at all. Exercises the real mux/handlers; +// only OIDC login/callback are skipped (they need a real provider), so the +// session cookie is minted directly the same way Callback would. +import ( + "bytes" + "encoding/json" + "fmt" + "mime/multipart" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "github.com/google/uuid" + + "vlog/internal/auth" + "vlog/internal/db" + "vlog/internal/handlers" + "vlog/internal/storage" +) + +// a minimal valid 1x1 PNG. +var testPNG = []byte{ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, + 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, + 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, + 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00, + 0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, + 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, +} + +func newTestApp(t *testing.T) (*http.ServeMux, string) { + t.Helper() + dir := t.TempDir() + + database, err := db.Connect("sqlite", filepath.Join(dir, "test.db")) + if err != nil { + t.Fatalf("db.Connect: %v", err) + } + t.Cleanup(func() { database.Close() }) + + store, err := storage.NewLocal(filepath.Join(dir, "uploads")) + if err != nil { + t.Fatalf("storage.NewLocal: %v", err) + } + + // Authenticator is nil — fine as long as the test never hits + // /api/auth/login or /api/auth/callback (OIDC needs a real provider). + h := handlers.New(database, store, nil, "test-jwt-secret", false) + + mux := http.NewServeMux() + registerRoutes(mux, h) + + // Simulate what Callback does on first login: JIT-provision a user row + // and mint the same session JWT. + userID := uuid.New().String() + if _, err := database.Exec(`INSERT INTO users (id, oidc_sub, email, name) VALUES (?, ?, ?, ?)`, + userID, "test-sub", "test@example.com", "Test User"); err != nil { + t.Fatalf("seed user: %v", err) + } + token, err := auth.MintSessionJWT("test-jwt-secret", userID, "test@example.com") + if err != nil { + t.Fatalf("mint session: %v", err) + } + + return mux, token +} + +func doJSON(t *testing.T, mux *http.ServeMux, token, method, path string, body interface{}) *httptest.ResponseRecorder { + t.Helper() + var buf bytes.Buffer + if body != nil { + if err := json.NewEncoder(&buf).Encode(body); err != nil { + t.Fatalf("encode body: %v", err) + } + } + req := httptest.NewRequest(method, path, &buf) + req.Header.Set("Content-Type", "application/json") + req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token}) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + return rec +} + +func doUpload(t *testing.T, mux *http.ServeMux, token, path, fieldFile string, content []byte) *httptest.ResponseRecorder { + t.Helper() + var buf bytes.Buffer + w := multipart.NewWriter(&buf) + part, err := w.CreateFormFile("file", fieldFile) + if err != nil { + t.Fatalf("create form file: %v", err) + } + if _, err := part.Write(content); err != nil { + t.Fatalf("write form file: %v", err) + } + w.Close() + + req := httptest.NewRequest(http.MethodPost, path, &buf) + req.Header.Set("Content-Type", w.FormDataContentType()) + req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token}) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + return rec +} + +func TestFullFlow_SQLiteAndLocalStorage(t *testing.T) { + mux, token := newTestApp(t) + + // Me + rec := doJSON(t, mux, token, http.MethodGet, "/api/me", nil) + if rec.Code != http.StatusOK { + t.Fatalf("GET /api/me: got %d, body %s", rec.Code, rec.Body.String()) + } + + // Create car + rec = doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{ + "rego": "ABC123", + "make": "Toyota", + "model": "Corolla", + "year": 2018, + "regoExpiry": "2026-09-01", + "wofExpiry": "2026-08-20", + }) + if rec.Code != http.StatusCreated { + t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String()) + } + var car struct { + ID string `json:"id"` + Rego string `json:"rego"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &car); err != nil { + t.Fatalf("decode car: %v", err) + } + if car.Rego != "ABC123" { + t.Fatalf("expected rego ABC123, got %q", car.Rego) + } + + // List cars + rec = doJSON(t, mux, token, http.MethodGet, "/api/cars", nil) + if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("ABC123")) { + t.Fatalf("GET /api/cars: got %d, body %s", rec.Code, rec.Body.String()) + } + + // Upload photo (local storage) + rec = doUpload(t, mux, token, fmt.Sprintf("/api/cars/%s/photo", car.ID), "photo.png", testPNG) + if rec.Code != http.StatusOK { + t.Fatalf("POST photo: got %d, body %s", rec.Code, rec.Body.String()) + } + + // Stream photo back + req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/cars/%s/photo", car.ID), nil) + req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token}) + rec2 := httptest.NewRecorder() + mux.ServeHTTP(rec2, req) + if rec2.Code != http.StatusOK { + t.Fatalf("GET photo: got %d", rec2.Code) + } + if got := rec2.Body.Bytes(); !bytes.Equal(got, testPNG) { + t.Fatalf("photo bytes round-trip mismatch: got %d bytes, want %d", len(got), len(testPNG)) + } + if ct := rec2.Header().Get("Content-Type"); ct != "image/png" { + t.Fatalf("expected image/png content-type, got %q", ct) + } + + // A renamed non-image file must be rejected (content-sniffing, not extension) + rec = doUpload(t, mux, token, fmt.Sprintf("/api/cars/%s/photo", car.ID), "fake.png", []byte("not actually a png")) + if rec.Code != http.StatusUnsupportedMediaType { + t.Fatalf("expected 415 for fake png, got %d, body %s", rec.Code, rec.Body.String()) + } + + // Add a service entry + rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{ + "entryDate": "2026-07-01", + "entryType": "Oil change", + "performedAt": "Bob's Garage", + "odometer": 45000, + }) + if rec.Code != http.StatusCreated { + t.Fatalf("POST service-entries: got %d, body %s", rec.Code, rec.Body.String()) + } + var entry struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &entry) + + // Attach a PNG to it + rec = doUpload(t, mux, token, fmt.Sprintf("/api/service-entries/%s/files", entry.ID), "invoice.png", testPNG) + if rec.Code != http.StatusCreated { + t.Fatalf("POST service-entry file: got %d, body %s", rec.Code, rec.Body.String()) + } + var file struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &file) + + // Timeline shows the entry with its file + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), nil) + if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("invoice.png")) { + t.Fatalf("GET service-entries: got %d, body %s", rec.Code, rec.Body.String()) + } + + // Stream the attachment back + req = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/files/%s", file.ID), nil) + req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token}) + rec2 = httptest.NewRecorder() + mux.ServeHTTP(rec2, req) + if rec2.Code != http.StatusOK || !bytes.Equal(rec2.Body.Bytes(), testPNG) { + t.Fatalf("GET file: got %d, %d bytes", rec2.Code, rec2.Body.Len()) + } + + // Add a custom reminder due soon, and one far in the future + rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{ + "reminderType": "custom", + "label": "Spark plugs", + "dueDate": "2026-08-20", + }) + if rec.Code != http.StatusCreated { + t.Fatalf("POST reminders: got %d, body %s", rec.Code, rec.Body.String()) + } + rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{ + "reminderType": "service", + "dueDate": "2030-01-01", + }) + if rec.Code != http.StatusCreated { + t.Fatalf("POST reminders (far future): got %d, body %s", rec.Code, rec.Body.String()) + } + + // Dashboard should surface: the near-due custom reminder, rego expiry, + // and WoF expiry (all within 30 days) — but not the 2030 reminder. + rec = doJSON(t, mux, token, http.MethodGet, "/api/dashboard", nil) + if rec.Code != http.StatusOK { + t.Fatalf("GET dashboard: got %d, body %s", rec.Code, rec.Body.String()) + } + var items []map[string]interface{} + if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil { + t.Fatalf("decode dashboard: %v", err) + } + kinds := map[string]bool{} + for _, it := range items { + kinds[it["reminderType"].(string)] = true + } + for _, want := range []string{"custom", "rego", "wof"} { + if !kinds[want] { + t.Errorf("expected dashboard to include kind %q, items: %+v", want, items) + } + } + if len(items) != 3 { + t.Errorf("expected exactly 3 dashboard items (not the 2030 reminder), got %d: %+v", len(items), items) + } + + // Delete the car — must cascade to entries/files/reminders. + rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/cars/%s", car.ID), nil) + if rec.Code != http.StatusOK { + t.Fatalf("DELETE car: got %d, body %s", rec.Code, rec.Body.String()) + } + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s", car.ID), nil) + if rec.Code != http.StatusNotFound { + t.Fatalf("GET deleted car: expected 404, got %d", rec.Code) + } + + // The attached file should also be gone from local disk (best-effort + // delete on cascade) — GET should now 404. + req = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/files/%s", file.ID), nil) + req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token}) + rec2 = httptest.NewRecorder() + mux.ServeHTTP(rec2, req) + if rec2.Code != http.StatusNotFound { + t.Fatalf("GET file after car delete: expected 404, got %d", rec2.Code) + } +} + +func TestKnowledgeBase(t *testing.T) { + mux, token := newTestApp(t) + + rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "KB001"}) + if rec.Code != http.StatusCreated { + t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String()) + } + var car struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &car) + + // Create + rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), map[string]interface{}{ + "title": "Coolant type", + "body": "Use Toyota Super Long Life Coolant, pink, diluted 50/50.", + }) + if rec.Code != http.StatusCreated { + t.Fatalf("POST knowledge: got %d, body %s", rec.Code, rec.Body.String()) + } + var entry struct { + ID string `json:"id"` + Title string `json:"title"` + } + json.Unmarshal(rec.Body.Bytes(), &entry) + if entry.Title != "Coolant type" { + t.Fatalf("expected title Coolant type, got %q", entry.Title) + } + + // List + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), nil) + if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Coolant type")) { + t.Fatalf("GET knowledge: got %d, body %s", rec.Code, rec.Body.String()) + } + + // Update + rec = doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/knowledge/%s", entry.ID), map[string]interface{}{ + "title": "Coolant type (updated)", + "body": "Use Toyota Super Long Life Coolant, pink, diluted 50/50. Bleed via the top-left nipple.", + }) + if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Bleed via")) { + t.Fatalf("PUT knowledge: got %d, body %s", rec.Code, rec.Body.String()) + } + + // Delete + rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/knowledge/%s", entry.ID), nil) + if rec.Code != http.StatusOK { + t.Fatalf("DELETE knowledge: got %d, body %s", rec.Code, rec.Body.String()) + } + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), nil) + if rec.Code != http.StatusOK || string(rec.Body.Bytes()) != `{"items":[],"hasMore":false}`+"\n" { + t.Fatalf("expected empty knowledge list after delete, got %d: %s", rec.Code, rec.Body.String()) + } +} + +// TestListPagination covers both paginated list endpoints (service entries +// and knowledge entries) — the thing that matters for a car with a very +// long history: a page at a time, never the whole thing in one response. +func TestListPagination(t *testing.T) { + mux, token := newTestApp(t) + + rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "PAGE001"}) + if rec.Code != http.StatusCreated { + t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String()) + } + var car struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &car) + + const total = 25 + for i := 0; i < total; i++ { + rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{ + "entryDate": fmt.Sprintf("2020-01-%02d", (i%28)+1), + "entryType": fmt.Sprintf("Entry %d", i), + }) + if rec.Code != http.StatusCreated { + t.Fatalf("seed service entry %d: got %d, body %s", i, rec.Code, rec.Body.String()) + } + rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), map[string]interface{}{ + "title": fmt.Sprintf("KB %d", i), + "body": "body", + }) + if rec.Code != http.StatusCreated { + t.Fatalf("seed knowledge entry %d: got %d, body %s", i, rec.Code, rec.Body.String()) + } + } + + for _, endpoint := range []string{"service-entries", "knowledge"} { + // Default page (no ?limit=) should cap at 20 and report more available. + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s", car.ID, endpoint), nil) + var firstPage struct { + Items []json.RawMessage `json:"items"` + HasMore bool `json:"hasMore"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &firstPage); err != nil { + t.Fatalf("%s first page: decode failed: %v, body %s", endpoint, err, rec.Body.String()) + } + if len(firstPage.Items) != 20 || !firstPage.HasMore { + t.Fatalf("%s first page: expected 20 items + hasMore=true, got %d items, hasMore=%v", + endpoint, len(firstPage.Items), firstPage.HasMore) + } + + // Second page (offset=20) should return the remaining 5, hasMore=false. + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s?limit=20&offset=20", car.ID, endpoint), nil) + var secondPage struct { + Items []json.RawMessage `json:"items"` + HasMore bool `json:"hasMore"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &secondPage); err != nil { + t.Fatalf("%s second page: decode failed: %v, body %s", endpoint, err, rec.Body.String()) + } + if len(secondPage.Items) != total-20 || secondPage.HasMore { + t.Fatalf("%s second page: expected %d items + hasMore=false, got %d items, hasMore=%v", + endpoint, total-20, len(secondPage.Items), secondPage.HasMore) + } + + // A tiny explicit page size still respects hasMore correctly. + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s?limit=3&offset=0", car.ID, endpoint), nil) + var smallPage struct { + Items []json.RawMessage `json:"items"` + HasMore bool `json:"hasMore"` + } + json.Unmarshal(rec.Body.Bytes(), &smallPage) + if len(smallPage.Items) != 3 || !smallPage.HasMore { + t.Fatalf("%s small page: expected 3 items + hasMore=true, got %d items, hasMore=%v", + endpoint, len(smallPage.Items), smallPage.HasMore) + } + } +} + +func TestSecondUserCannotSeeFirstUsersCar(t *testing.T) { + mux, token1 := newTestApp(t) + + rec := doJSON(t, mux, token1, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "PRIVATE1"}) + if rec.Code != http.StatusCreated { + t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String()) + } + var car struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &car) + + // Mint a second user's session against the SAME app/db (simulating a + // second OIDC-authenticated user). + // newTestApp already seeded one user in its own fresh DB, so instead we + // reuse the mux but mint a token for a brand-new, never-provisioned user. + req := httptest.NewRequest(http.MethodGet, "/api/cars", nil) + badToken, err := auth.MintSessionJWT("test-jwt-secret", "00000000-0000-0000-0000-000000000000", "other@example.com") + if err != nil { + t.Fatalf("mint: %v", err) + } + req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: badToken}) + rec2 := httptest.NewRecorder() + mux.ServeHTTP(rec2, req) + if rec2.Code != http.StatusOK || string(rec2.Body.Bytes()) != "[]\n" { + // (also guards against regressing to encoding an empty list as + // JSON null, which would crash the frontend's cars.length checks) + t.Fatalf("second user's garage should be empty, got %d: %s", rec2.Code, rec2.Body.String()) + } + + // And can't reach the first user's car by ID either. + rec3 := doJSON(t, mux, badToken, http.MethodGet, fmt.Sprintf("/api/cars/%s", car.ID), nil) + if rec3.Code != http.StatusNotFound { + t.Fatalf("expected 404 for other user's car, got %d", rec3.Code) + } +} + +func TestSharingPublicEndpoints(t *testing.T) { + mux, token := newTestApp(t) + + rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "SHARE1", "make": "Honda"}) + if rec.Code != http.StatusCreated { + t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String()) + } + var car struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &car) + + // Not shared yet — public endpoint 404s. + req := httptest.NewRequest(http.MethodGet, "/api/public/cars/nonexistent-token", nil) + rec2 := httptest.NewRecorder() + mux.ServeHTTP(rec2, req) + if rec2.Code != http.StatusNotFound { + t.Fatalf("expected 404 for unknown share token, got %d", rec2.Code) + } + + // Turn sharing on. + rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/share", car.ID), nil) + if rec.Code != http.StatusOK { + t.Fatalf("POST share: got %d, body %s", rec.Code, rec.Body.String()) + } + var shared struct { + ShareToken string `json:"shareToken"` + } + json.Unmarshal(rec.Body.Bytes(), &shared) + if shared.ShareToken == "" { + t.Fatal("expected a non-empty shareToken") + } + + // Add a service entry with an attachment, to confirm docs are included + // in the public view (the whole point of sharing when selling a car). + rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{ + "entryDate": "2026-01-01", + "entryType": "Oil change", + }) + var entry struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &entry) + rec = doUpload(t, mux, token, fmt.Sprintf("/api/service-entries/%s/files", entry.ID), "invoice.png", testPNG) + var file struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &file) + + // Public car info — no auth cookie needed at all. + req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken, nil) + rec2 = httptest.NewRecorder() + mux.ServeHTTP(rec2, req) + if rec2.Code != http.StatusOK || !bytes.Contains(rec2.Body.Bytes(), []byte("SHARE1")) { + t.Fatalf("public car: got %d, body %s", rec2.Code, rec2.Body.String()) + } + + // Public service history — should include the attachment. + req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken+"/service-entries", nil) + rec2 = httptest.NewRecorder() + mux.ServeHTTP(rec2, req) + if rec2.Code != http.StatusOK || !bytes.Contains(rec2.Body.Bytes(), []byte("invoice.png")) { + t.Fatalf("public service-entries: got %d, body %s", rec2.Code, rec2.Body.String()) + } + + // Public file download. + req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken+"/files/"+file.ID, nil) + rec2 = httptest.NewRecorder() + mux.ServeHTTP(rec2, req) + if rec2.Code != http.StatusOK || !bytes.Equal(rec2.Body.Bytes(), testPNG) { + t.Fatalf("public file: got %d, %d bytes", rec2.Code, rec2.Body.Len()) + } + + // Revoke — public endpoint 404s again. + rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/cars/%s/share", car.ID), nil) + if rec.Code != http.StatusOK { + t.Fatalf("DELETE share: got %d, body %s", rec.Code, rec.Body.String()) + } + req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken, nil) + rec2 = httptest.NewRecorder() + mux.ServeHTTP(rec2, req) + if rec2.Code != http.StatusNotFound { + t.Fatalf("expected 404 after revoke, got %d", rec2.Code) + } +} + +func TestFuelEntries(t *testing.T) { + mux, token := newTestApp(t) + + rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "FUEL1"}) + var car struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &car) + + rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), map[string]interface{}{ + "entryDate": "2026-07-01", + "litres": 45.5, + "cost": 98.20, + "odometer": 50000, + "location": "BP", + }) + if rec.Code != http.StatusCreated { + t.Fatalf("POST fuel-entries: got %d, body %s", rec.Code, rec.Body.String()) + } + var entry struct { + ID string `json:"id"` + Litres float64 `json:"litres"` + } + json.Unmarshal(rec.Body.Bytes(), &entry) + if entry.Litres != 45.5 { + t.Fatalf("expected litres 45.5, got %v", entry.Litres) + } + + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), nil) + if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("BP")) { + t.Fatalf("GET fuel-entries: got %d, body %s", rec.Code, rec.Body.String()) + } + + rec = doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/fuel-entries/%s", entry.ID), map[string]interface{}{ + "entryDate": "2026-07-01", + "litres": 46, + "cost": 100, + "location": "Z Energy", + }) + if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Z Energy")) { + t.Fatalf("PUT fuel-entries: got %d, body %s", rec.Code, rec.Body.String()) + } + + rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/fuel-entries/%s", entry.ID), nil) + if rec.Code != http.StatusOK { + t.Fatalf("DELETE fuel-entries: got %d, body %s", rec.Code, rec.Body.String()) + } +} + +func TestMileageAndMilestone(t *testing.T) { + mux, token := newTestApp(t) + + rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "MILE1", "odometer": 68420}) + var car struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &car) + + // With no history points yet, still reports current reading, just no + // rate/throughput estimate. + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/mileage", car.ID), nil) + var m struct { + CurrentOdometer int `json:"currentOdometer"` + KmPerYear *float64 `json:"kmPerYear"` + YearsPer100k *float64 `json:"yearsPer100k"` + Next100kEta *string `json:"next100kEta"` + } + json.Unmarshal(rec.Body.Bytes(), &m) + if m.KmPerYear != nil || m.YearsPer100k != nil { + t.Fatalf("expected no rate/throughput with <2 data points, got kmPerYear=%v yearsPer100k=%v", m.KmPerYear, m.YearsPer100k) + } + + // Add a historical fuel entry a year ago at a lower reading — now there + // are two points and a rate/throughput estimate should compute. + yearAgo := "2025-08-06" + doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), map[string]interface{}{ + "entryDate": yearAgo, "litres": 40, "cost": 80, "odometer": 50000, + }) + + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/mileage", car.ID), nil) + json.Unmarshal(rec.Body.Bytes(), &m) + if m.KmPerYear == nil || *m.KmPerYear < 17000 || *m.KmPerYear > 19500 { + t.Fatalf("expected ~18,420 km/year, got %v", m.KmPerYear) + } + // 100,000km / ~18,420km per year is ~5.4 years — a throughput figure + // from today, unrelated to the odometer's current position (68,420km + // is nowhere near a "100,000km" round number, and that's the point). + if m.YearsPer100k == nil || *m.YearsPer100k < 5.0 || *m.YearsPer100k > 6.0 { + t.Fatalf("expected ~5.4 years per 100,000km, got %v", m.YearsPer100k) + } + if m.Next100kEta == nil { + t.Fatal("expected a next100kEta date once a rate is known") + } +} + +func TestSynthesizedReminders(t *testing.T) { + mux, token := newTestApp(t) + + rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{ + "rego": "REM001", "regoExpiry": "2026-08-20", "wofExpiry": "2026-08-15", + }) + var car struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &car) + + // Even with zero real reminders, rego/WoF show up automatically. + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil) + var views []map[string]interface{} + json.Unmarshal(rec.Body.Bytes(), &views) + types := map[string]bool{} + for _, v := range views { + types[v["reminderType"].(string)] = true + if v["id"] != nil && v["reminderType"] == "rego" { + t.Fatalf("synthesized rego reminder should have a nil id, got %v", v["id"]) + } + } + if !types["rego"] || !types["wof"] { + t.Fatalf("expected synthesized rego+wof reminders, got %+v", views) + } + + // Configure a service interval and log a qualifying service entry — + // a synthesized "service" reminder should now also appear. + doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/cars/%s", car.ID), map[string]interface{}{ + "rego": "REM001", "serviceIntervalKm": 10000, "serviceIntervalMonths": 6, + }) + doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{ + "entryDate": "2026-01-01", "entryType": "Full service", "odometer": 40000, "isService": true, + }) + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil) + json.Unmarshal(rec.Body.Bytes(), &views) + types = map[string]bool{} + for _, v := range views { + types[v["reminderType"].(string)] = true + } + if !types["service"] { + t.Fatalf("expected synthesized service reminder after logging a qualifying entry, got %+v", views) + } + + // A completed real reminder is hidden by default, shown with ?completed=1. + rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{ + "reminderType": "custom", "label": "Test reminder", "dueDate": "2026-09-01", + }) + var reminder struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &reminder) + doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/reminders/%s", reminder.ID), map[string]interface{}{"completed": true}) + + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil) + if bytes.Contains(rec.Body.Bytes(), []byte("Test reminder")) { + t.Fatalf("completed reminder should be hidden by default, got %s", rec.Body.String()) + } + rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders?completed=1", car.ID), nil) + if !bytes.Contains(rec.Body.Bytes(), []byte("Test reminder")) { + t.Fatalf("completed reminder should show with ?completed=1, got %s", rec.Body.String()) + } +} diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go new file mode 100644 index 0000000..e44f144 --- /dev/null +++ b/backend/cmd/server/main.go @@ -0,0 +1,85 @@ +// Command server is the whole app: it serves the JSON API and the embedded +// Svelte SPA from one binary, and applies DB migrations on startup. +package main + +import ( + "context" + "fmt" + "io/fs" + "log" + "net/http" + "strings" + "time" + + "vlog/internal/auth" + "vlog/internal/config" + "vlog/internal/db" + "vlog/internal/handlers" + "vlog/internal/storage" +) + +func main() { + cfg, err := config.Load() + if err != nil { + log.Fatalf("config: %v", err) + } + + ctx := context.Background() + + database, err := db.Connect(cfg.DBDriver, cfg.DatabaseURL) + if err != nil { + log.Fatalf("database: %v", err) + } + defer database.Close() + + store, err := newStorage(ctx, cfg) + if err != nil { + log.Fatalf("storage: %v", err) + } + + // Only require Secure cookies when we're actually serving over https — + // lets this run over plain http for local dev. + secureCookies := strings.HasPrefix(cfg.PublicBaseURL, "https://") + + authenticator, err := auth.NewAuthenticator(ctx, cfg.OIDCIssuerURL, cfg.OIDCClientID, cfg.OIDCClientSecret, cfg.OIDCRedirectURL, secureCookies) + if err != nil { + log.Fatalf("oidc: %v", err) + } + + h := handlers.New(database, store, authenticator, cfg.JWTSigningSecret, secureCookies) + + mux := http.NewServeMux() + registerRoutes(mux, h) + + staticFS, err := fs.Sub(frontendFS, "web") + if err != nil { + log.Fatalf("frontend assets: %v", err) + } + mux.Handle("/", spaHandler(staticFS)) + + srv := &http.Server{ + Addr: ":" + cfg.Port, + Handler: logMiddleware(mux), + ReadHeaderTimeout: 10 * time.Second, + } + + log.Printf("listening on :%s", cfg.Port) + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("server: %v", err) + } +} + +// newStorage picks the file storage backend based on STORAGE_DRIVER: "s3" +// (production) or "local" (writes to disk — for testing without a real S3 +// bucket). Handlers depend only on the storage.Storage interface, so +// nothing else in the app needs to know which one is active. +func newStorage(ctx context.Context, cfg *config.Config) (storage.Storage, error) { + switch cfg.StorageDriver { + case "s3": + return storage.NewS3(ctx, cfg.AWSRegion, cfg.S3Bucket) + case "local": + return storage.NewLocal(cfg.LocalStoragePath) + default: + return nil, fmt.Errorf("invalid STORAGE_DRIVER %q (must be s3 or local)", cfg.StorageDriver) + } +} diff --git a/backend/cmd/server/middleware.go b/backend/cmd/server/middleware.go new file mode 100644 index 0000000..620338a --- /dev/null +++ b/backend/cmd/server/middleware.go @@ -0,0 +1,24 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// logMiddleware and recovery in one small wrapper — no need for a whole +// middleware package for two stdlib one-liners. +func logMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if rec := recover(); rec != nil { + log.Printf("panic handling %s %s: %v", r.Method, r.URL.Path, rec) + http.Error(w, "internal server error", http.StatusInternalServerError) + } + }() + + start := time.Now() + next.ServeHTTP(w, r) + log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start)) + }) +} diff --git a/backend/cmd/server/routes.go b/backend/cmd/server/routes.go new file mode 100644 index 0000000..06ba90a --- /dev/null +++ b/backend/cmd/server/routes.go @@ -0,0 +1,70 @@ +package main + +import ( + "net/http" + + "vlog/internal/auth" + "vlog/internal/handlers" +) + +// registerRoutes wires up the whole JSON API. Auth login/callback/logout +// and the /api/public/... share endpoints are public; everything else +// requires the session cookie. +func registerRoutes(mux *http.ServeMux, h *handlers.Handlers) { + mux.HandleFunc("GET /api/auth/login", h.Login) + mux.HandleFunc("GET /api/auth/callback", h.Callback) + mux.HandleFunc("POST /api/auth/logout", h.Logout) + + // Public, unauthenticated share view (QR code / link, no login) — a + // deliberately narrow read-only surface, see internal/handlers/public.go. + mux.HandleFunc("GET /api/public/cars/{shareToken}", h.PublicCar) + mux.HandleFunc("GET /api/public/cars/{shareToken}/photo", h.PublicCarPhoto) + mux.HandleFunc("GET /api/public/cars/{shareToken}/service-entries", h.PublicServiceEntries) + mux.HandleFunc("GET /api/public/cars/{shareToken}/files/{fileId}", h.PublicFile) + + protected := http.NewServeMux() + protected.HandleFunc("GET /api/me", h.Me) + + protected.HandleFunc("GET /api/cars", h.ListCars) + protected.HandleFunc("POST /api/cars", h.CreateCar) + protected.HandleFunc("GET /api/cars/{carId}", h.GetCar) + protected.HandleFunc("PUT /api/cars/{carId}", h.UpdateCar) + protected.HandleFunc("DELETE /api/cars/{carId}", h.DeleteCar) + protected.HandleFunc("POST /api/cars/{carId}/photo", h.UploadCarPhoto) + protected.HandleFunc("GET /api/cars/{carId}/photo", h.GetCarPhoto) + protected.HandleFunc("PATCH /api/cars/{carId}/odometer", h.UpdateOdometer) + protected.HandleFunc("POST /api/cars/{carId}/share", h.GenerateShareLink) + protected.HandleFunc("DELETE /api/cars/{carId}/share", h.RevokeShareLink) + protected.HandleFunc("GET /api/cars/{carId}/mileage", h.Mileage) + + protected.HandleFunc("GET /api/cars/{carId}/service-entries", h.ListServiceEntries) + protected.HandleFunc("POST /api/cars/{carId}/service-entries", h.CreateServiceEntry) + protected.HandleFunc("GET /api/service-entries/{entryId}", h.GetServiceEntry) + protected.HandleFunc("PUT /api/service-entries/{entryId}", h.UpdateServiceEntry) + protected.HandleFunc("DELETE /api/service-entries/{entryId}", h.DeleteServiceEntry) + protected.HandleFunc("POST /api/service-entries/{entryId}/files", h.UploadServiceEntryFile) + protected.HandleFunc("GET /api/files/{fileId}", h.GetFile) + protected.HandleFunc("DELETE /api/files/{fileId}", h.DeleteFile) + + protected.HandleFunc("GET /api/cars/{carId}/reminders", h.ListReminders) + protected.HandleFunc("POST /api/cars/{carId}/reminders", h.CreateReminder) + protected.HandleFunc("PUT /api/reminders/{reminderId}", h.UpdateReminder) + protected.HandleFunc("DELETE /api/reminders/{reminderId}", h.DeleteReminder) + + protected.HandleFunc("GET /api/cars/{carId}/knowledge", h.ListKnowledge) + protected.HandleFunc("POST /api/cars/{carId}/knowledge", h.CreateKnowledge) + protected.HandleFunc("PUT /api/knowledge/{knowledgeId}", h.UpdateKnowledge) + protected.HandleFunc("DELETE /api/knowledge/{knowledgeId}", h.DeleteKnowledge) + + protected.HandleFunc("GET /api/cars/{carId}/fuel-entries", h.ListFuelEntries) + protected.HandleFunc("POST /api/cars/{carId}/fuel-entries", h.CreateFuelEntry) + protected.HandleFunc("PUT /api/fuel-entries/{entryId}", h.UpdateFuelEntry) + protected.HandleFunc("DELETE /api/fuel-entries/{entryId}", h.DeleteFuelEntry) + + protected.HandleFunc("GET /api/dashboard", h.Dashboard) + + // Mounted as a subtree on the outer mux; Go's ServeMux does not strip + // the prefix, so the protected mux's patterns include the full "/api/..." + // path and match the original request untouched. + mux.Handle("/api/", auth.RequireAuth(h.JWTSecret)(protected)) +} diff --git a/backend/cmd/server/spa.go b/backend/cmd/server/spa.go new file mode 100644 index 0000000..947f348 --- /dev/null +++ b/backend/cmd/server/spa.go @@ -0,0 +1,30 @@ +package main + +import ( + "io/fs" + "net/http" + "strings" +) + +// spaHandler serves the embedded Svelte build, falling back to index.html +// for any path that isn't a real static asset — this is what lets the +// client-side router handle "deep" URLs like /cars/123 on a hard refresh. +func spaHandler(staticFS fs.FS) http.Handler { + fileServer := http.FileServer(http.FS(staticFS)) + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path := strings.TrimPrefix(r.URL.Path, "/") + if path == "" { + path = "index.html" + } + + if _, err := fs.Stat(staticFS, path); err != nil { + indexReq := r.Clone(r.Context()) + indexReq.URL.Path = "/" + fileServer.ServeHTTP(w, indexReq) + return + } + + fileServer.ServeHTTP(w, r) + }) +} diff --git a/backend/cmd/server/web/.gitkeep b/backend/cmd/server/web/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/backend/go.mod b/backend/go.mod new file mode 100644 index 0000000..8a9214a --- /dev/null +++ b/backend/go.mod @@ -0,0 +1,45 @@ +module vlog + +go 1.25.0 + +require ( + github.com/aws/aws-sdk-go-v2 v1.43.4 + github.com/aws/aws-sdk-go-v2/config v1.32.35 + github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.40 + github.com/aws/aws-sdk-go-v2/service/s3 v1.106.5 + github.com/coreos/go-oidc/v3 v3.20.0 + github.com/golang-jwt/jwt/v5 v5.3.1 + github.com/golang-migrate/migrate/v4 v4.19.1 + github.com/google/uuid v1.6.0 + github.com/jmoiron/sqlx v1.4.0 + github.com/lib/pq v1.12.3 + golang.org/x/oauth2 v0.36.0 + modernc.org/sqlite v1.56.0 +) + +require ( + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.16 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.19.34 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.35 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.35 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.35 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.36 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.15 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.28 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.35 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.36 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.5.4 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.33.4 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.4 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.45.4 // indirect + github.com/aws/smithy-go v1.27.6 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-jose/go-jose/v4 v4.1.4 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sys v0.47.0 // indirect + modernc.org/libc v1.74.4 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.11.0 // indirect +) diff --git a/backend/go.sum b/backend/go.sum new file mode 100644 index 0000000..2f42df8 --- /dev/null +++ b/backend/go.sum @@ -0,0 +1,165 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/aws/aws-sdk-go-v2 v1.43.4 h1:b9FTvbRwy+JCsfp2Wp6wV/KbOx3Aj7nkoFb2cRX0IhE= +github.com/aws/aws-sdk-go-v2 v1.43.4/go.mod h1:70vwSy16txshwG+g55WkpgPKDIByzHI8ccBsOteo3bQ= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.16 h1:aiuaKlDweRC5qExJondpWjOgyzMHpofpwspGXUtwn4c= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.16/go.mod h1:nG/LOlmox9BDe9HvQnXWzgcK8uKbgBMZ/Hp5pVt/21I= +github.com/aws/aws-sdk-go-v2/config v1.32.35 h1:UEzXuET8E42lxBPijuACu/tEK7v5lFPlk0Q+GT5WD9E= +github.com/aws/aws-sdk-go-v2/config v1.32.35/go.mod h1:KaMtJpFa2JlL2BStjjHQVwQpzZEmw+ND/EgVrfFoo2g= +github.com/aws/aws-sdk-go-v2/credentials v1.19.34 h1:y6GkSmcv5myd1ngrYbGmiLlwQqB6TQhOuN/tbSSuWDY= +github.com/aws/aws-sdk-go-v2/credentials v1.19.34/go.mod h1:w3dTcnDVoQIewjo7JG45hduAToikiIFLC4FIO7fndvw= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.35 h1:+S7kbJoLDDQ5tE+lHrUBgMkzC8NLgsaioS2F3dVoFAE= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.35/go.mod h1:Ak7xXviIARfFdNUJ9Etb0bdVDt/KAvKjMGJVLWXDzik= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.40 h1:8h8ZlKpMiJDWHptcpP9SYjWds3ppVAKrbI02pqEi8uM= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.40/go.mod h1:K8aokMNmZVa12zR7OJ5vF2+uwBl1QEZqm3AuBS3DqIo= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.35 h1:kzVuGlatQtYinwBJEEyLAbggepCoavosiaHHX9+fD+c= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.35/go.mod h1:0yLx0yEI+SfqeJMPvOtIEFoZbiQYXMGszBueiutQyaI= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.35 h1:WK6CjihTuLisCjSKKbildJ79sGZZgbBz3iNa7VsKIhU= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.35/go.mod h1:KYleN57luLoe97R7vTnx8PMcVrr9gAcRECtOjl91DNg= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.36 h1:jbGY4CXLzZElOXgGsexlC3Hi+3YM0rSmk4opFXKqg/k= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.36/go.mod h1:uBu/9aKsS/UQGc72RAt3y54kjgYQxmhut8ZD2dXCDNE= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.15 h1:JJLBQxwY+AFwuPAi5ivGc1ChnTdUt4cXMv7e76m2c/Y= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.15/go.mod h1:lQknBIe78MVL0cQOQDlag8KGflMbMEVFx9mB6O8ENvk= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.28 h1:Q1TF1J9jVD+vFo0LzNnmNdQ9EAt52TS+MQlq9Ir+Yxo= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.28/go.mod h1:4KqXXC/p1hrotmouDFbrRoWaLy962b9PMUReCG6+uWo= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.35 h1:BBEElKh4a+rKshvjrfpajTe9CbpZvrbb4Jkg2PB7RzA= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.35/go.mod h1:zaZk983w//8beSruBVec/mr4CmDwgZitW/qzGhAAX0g= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.36 h1:EUIwBoN+q7UmhAejxgD27APiRjh1vwCFo53gSqdT0BM= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.36/go.mod h1:6u00gmlTGR6W0b2k9NBrld7MnOEmf1Spqx0VVt6AqyE= +github.com/aws/aws-sdk-go-v2/service/s3 v1.106.5 h1:HpN6GgZ3T8pSvRp81ZsgumNjlvRsa+9M0ZL2o6W4uLY= +github.com/aws/aws-sdk-go-v2/service/s3 v1.106.5/go.mod h1:5FTZoQxhmLEiCAtYVk6V+t0iS/B5yGZVLZ3Wq5FDJZI= +github.com/aws/aws-sdk-go-v2/service/signin v1.5.4 h1:cOJELVNrq5Q3Udry2GLuHUM7MhwpeaQRdYaoa6GI/yI= +github.com/aws/aws-sdk-go-v2/service/signin v1.5.4/go.mod h1:f4LxzKBtaTxD7xh3PiVg3CE1tchQemfmghaJr+NbK2c= +github.com/aws/aws-sdk-go-v2/service/sso v1.33.4 h1:AMW7a7S8iQaHjBYZdU3PCq4GKRPijTPRAc7e6XtEThY= +github.com/aws/aws-sdk-go-v2/service/sso v1.33.4/go.mod h1:QQNsFV1DVXoXcZt18FS8lI8rtUrlDyAuWZLQ5shunv4= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.4 h1:AsbZcJAQPRmHDJG8K1N0pof/1zPWjVT8TFlTWuGLSvo= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.4/go.mod h1:6imqztH0//t0mKbl6yWl7swSEl7F/w32oAmqB3vP1ag= +github.com/aws/aws-sdk-go-v2/service/sts v1.45.4 h1:w/AryDYMjSUANSQ2uoZxJovUsMTwWJNTv3IMex30Y+4= +github.com/aws/aws-sdk-go-v2/service/sts v1.45.4/go.mod h1:WeBiAa67azG7Su9Vf+ChGDBLiAozJCXzdjXiPBUwtbc= +github.com/aws/smithy-go v1.27.6 h1:0zjT8jgK3jbrTT7JJ3EE6JsMhX8JTrZ+f1sEndYDXrA= +github.com/aws/smithy-go v1.27.6/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= +github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= +github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= +github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/coreos/go-oidc/v3 v3.20.0 h1:EtE0WIBHk03N+DqGkY4+UONzzZHk7amKt6IyNd7OsZE= +github.com/coreos/go-oidc/v3 v3.20.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dhui/dktest v0.4.6 h1:+DPKyScKSEp3VLtbMDHcUq6V5Lm5zfZZVb0Sk7Ahom4= +github.com/dhui/dktest v0.4.6/go.mod h1:JHTSYDtKkvFNFHJKqCzVzqXecyv+tKt8EzceOmQOgbU= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/docker/docker v28.3.3+incompatible h1:Dypm25kh4rmk49v1eiVbsAtpAsYURjYkaKubwuBdxEI= +github.com/docker/docker v28.3.3+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c= +github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang-migrate/migrate/v4 v4.19.1 h1:OCyb44lFuQfYXYLx1SCxPZQGU7mcaZ7gH9yH4jSFbBA= +github.com/golang-migrate/migrate/v4 v4.19.1/go.mod h1:CTcgfjxhaUtsLipnLoQRWCrjYXycRz/g5+RWDuYgPrE= +github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= +github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= +github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ= +github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= +github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= +github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= +go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ= +go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I= +go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE= +go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E= +go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4= +go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= +golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI= +modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU= +modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI= +modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k= +modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.56.0 h1:/D8e2RfFqoy/Zc6PuC76U28zFwmI/sYx1Kjm4yEn9e0= +modernc.org/sqlite v1.56.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/backend/internal/auth/jwt.go b/backend/internal/auth/jwt.go new file mode 100644 index 0000000..aea597a --- /dev/null +++ b/backend/internal/auth/jwt.go @@ -0,0 +1,81 @@ +package auth + +import ( + "fmt" + "net/http" + "time" + + "github.com/golang-jwt/jwt/v5" +) + +const ( + SessionCookieName = "session" + sessionTTL = 7 * 24 * time.Hour +) + +// SessionClaims is the app's own JWT payload minted after a successful OIDC +// login. Subject is our internal user UUID, not the OIDC sub. +type SessionClaims struct { + Email string `json:"email"` + jwt.RegisteredClaims +} + +// MintSessionJWT signs a new session token for the given internal user ID. +func MintSessionJWT(secret, userID, email string) (string, error) { + now := time.Now() + claims := SessionClaims{ + Email: email, + RegisteredClaims: jwt.RegisteredClaims{ + Subject: userID, + Issuer: "vlog-backend", + IssuedAt: jwt.NewNumericDate(now), + ExpiresAt: jwt.NewNumericDate(now.Add(sessionTTL)), + }, + } + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + return token.SignedString([]byte(secret)) +} + +// ParseSessionJWT verifies and decodes a session token, returning the claims. +func ParseSessionJWT(secret, tokenString string) (*SessionClaims, error) { + claims := &SessionClaims{} + token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) { + if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"]) + } + return []byte(secret), nil + }) + if err != nil { + return nil, err + } + if !token.Valid { + return nil, fmt.Errorf("invalid token") + } + return claims, nil +} + +// SetSessionCookie writes the signed session JWT as an httpOnly cookie. +func SetSessionCookie(w http.ResponseWriter, token string, secure bool) { + http.SetCookie(w, &http.Cookie{ + Name: SessionCookieName, + Value: token, + Path: "/", + HttpOnly: true, + Secure: secure, + SameSite: http.SameSiteLaxMode, + MaxAge: int(sessionTTL.Seconds()), + }) +} + +// ClearSessionCookie logs the user out client-side. +func ClearSessionCookie(w http.ResponseWriter, secure bool) { + http.SetCookie(w, &http.Cookie{ + Name: SessionCookieName, + Value: "", + Path: "/", + HttpOnly: true, + Secure: secure, + SameSite: http.SameSiteLaxMode, + MaxAge: -1, + }) +} diff --git a/backend/internal/auth/middleware.go b/backend/internal/auth/middleware.go new file mode 100644 index 0000000..56692a9 --- /dev/null +++ b/backend/internal/auth/middleware.go @@ -0,0 +1,42 @@ +package auth + +import ( + "context" + "net/http" +) + +type contextKey string + +const userIDContextKey contextKey = "userID" + +// RequireAuth reads the session cookie, verifies the JWT, and injects the +// internal user ID into the request context. Responds 401 if missing/invalid. +// This is the only route guard the app needs — every non-auth API route is +// wrapped with it. +func RequireAuth(jwtSecret string) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie(SessionCookieName) + if err != nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + + claims, err := ParseSessionJWT(jwtSecret, cookie.Value) + if err != nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + + ctx := context.WithValue(r.Context(), userIDContextKey, claims.Subject) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +// UserIDFromContext returns the authenticated user's internal UUID. Only +// valid on requests that passed through RequireAuth. +func UserIDFromContext(ctx context.Context) (string, bool) { + id, ok := ctx.Value(userIDContextKey).(string) + return id, ok +} diff --git a/backend/internal/auth/oidc.go b/backend/internal/auth/oidc.go new file mode 100644 index 0000000..f3d4f8b --- /dev/null +++ b/backend/internal/auth/oidc.go @@ -0,0 +1,153 @@ +// Package auth implements the OIDC authorization-code login flow and the +// app's own JWT session cookie that replaces the OIDC tokens after login. +package auth + +import ( + "context" + "crypto/rand" + "encoding/base64" + "errors" + "fmt" + "net/http" + "time" + + "github.com/coreos/go-oidc/v3/oidc" + "golang.org/x/oauth2" +) + +const ( + stateCookieName = "oidc_state" + verifierCookieName = "oidc_verifier" + oidcCookieTTL = 5 * time.Minute +) + +// OIDCClaims is the subset of ID token claims we care about. +type OIDCClaims struct { + Sub string `json:"sub"` + Email string `json:"email"` + Name string `json:"name"` +} + +// Authenticator wraps the discovered OIDC provider + oauth2 config for the +// authorization-code flow. +type Authenticator struct { + provider *oidc.Provider + verifier *oidc.IDTokenVerifier + oauthConfig oauth2.Config + // secureCookies controls the Secure flag on the short-lived login + // cookies; false only makes sense for local http:// development. + secureCookies bool +} + +func NewAuthenticator(ctx context.Context, issuerURL, clientID, clientSecret, redirectURL string, secureCookies bool) (*Authenticator, error) { + provider, err := oidc.NewProvider(ctx, issuerURL) + if err != nil { + return nil, fmt.Errorf("discover oidc provider: %w", err) + } + + return &Authenticator{ + provider: provider, + verifier: provider.Verifier(&oidc.Config{ClientID: clientID}), + oauthConfig: oauth2.Config{ + ClientID: clientID, + ClientSecret: clientSecret, + RedirectURL: redirectURL, + Endpoint: provider.Endpoint(), + Scopes: []string{oidc.ScopeOpenID, "profile", "email"}, + }, + secureCookies: secureCookies, + }, nil +} + +// BeginLogin generates state + a PKCE verifier, stashes both in short-lived +// cookies, and redirects the browser to the provider's authorize endpoint. +func (a *Authenticator) BeginLogin(w http.ResponseWriter, r *http.Request) { + state := randomToken() + verifier := oauth2.GenerateVerifier() + + setShortLivedCookie(w, stateCookieName, state, a.secureCookies) + setShortLivedCookie(w, verifierCookieName, verifier, a.secureCookies) + + authURL := a.oauthConfig.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier)) + http.Redirect(w, r, authURL, http.StatusFound) +} + +// HandleCallback validates state, exchanges the code for tokens, and returns +// the verified ID token claims. It also clears the short-lived cookies. +func (a *Authenticator) HandleCallback(ctx context.Context, w http.ResponseWriter, r *http.Request) (*OIDCClaims, error) { + defer clearCookie(w, stateCookieName) + defer clearCookie(w, verifierCookieName) + + stateCookie, err := r.Cookie(stateCookieName) + if err != nil { + return nil, errors.New("missing state cookie") + } + verifierCookie, err := r.Cookie(verifierCookieName) + if err != nil { + return nil, errors.New("missing verifier cookie") + } + + if r.URL.Query().Get("state") != stateCookie.Value { + return nil, errors.New("state mismatch") + } + + code := r.URL.Query().Get("code") + if code == "" { + return nil, errors.New("missing code") + } + + token, err := a.oauthConfig.Exchange(ctx, code, oauth2.VerifierOption(verifierCookie.Value)) + if err != nil { + return nil, fmt.Errorf("exchange code: %w", err) + } + + rawIDToken, ok := token.Extra("id_token").(string) + if !ok { + return nil, errors.New("no id_token in token response") + } + + idToken, err := a.verifier.Verify(ctx, rawIDToken) + if err != nil { + return nil, fmt.Errorf("verify id_token: %w", err) + } + + var claims OIDCClaims + if err := idToken.Claims(&claims); err != nil { + return nil, fmt.Errorf("parse id_token claims: %w", err) + } + if claims.Sub == "" { + return nil, errors.New("id_token missing sub") + } + + return &claims, nil +} + +func randomToken() string { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + panic(err) // crypto/rand failing is unrecoverable + } + return base64.RawURLEncoding.EncodeToString(b) +} + +func setShortLivedCookie(w http.ResponseWriter, name, value string, secure bool) { + http.SetCookie(w, &http.Cookie{ + Name: name, + Value: value, + Path: "/", + HttpOnly: true, + Secure: secure, + SameSite: http.SameSiteLaxMode, + MaxAge: int(oidcCookieTTL.Seconds()), + }) +} + +func clearCookie(w http.ResponseWriter, name string) { + http.SetCookie(w, &http.Cookie{ + Name: name, + Value: "", + Path: "/", + HttpOnly: true, + MaxAge: -1, + }) +} diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go new file mode 100644 index 0000000..e8ea6b1 --- /dev/null +++ b/backend/internal/config/config.go @@ -0,0 +1,96 @@ +// Package config loads and validates the app's configuration from environment +// variables. Everything the app needs to run lives here — no config files, +// no flags, just env vars (Docker Compose friendly). +package config + +import ( + "fmt" + "os" +) + +type Config struct { + Port string + + // DBDriver is "postgres" (default, production) or "sqlite" (local + // dev/testing without a real Postgres instance). When sqlite, + // DatabaseURL is a filesystem path to the DB file instead of a DSN. + DBDriver string + DatabaseURL string + + OIDCIssuerURL string + OIDCClientID string + OIDCClientSecret string + OIDCRedirectURL string + + // PublicBaseURL is this app's own externally-visible URL, e.g. + // https://garage.example.com. Used to build the OIDC redirect URL and to + // decide whether to mark cookies Secure. + PublicBaseURL string + + JWTSigningSecret string + + // StorageDriver is "s3" (default, production) or "local" (writes + // uploads to disk — for testing without an S3 bucket). When local, + // LocalStoragePath is where files are written. + StorageDriver string + LocalStoragePath string + + AWSRegion string + S3Bucket string + // AWS credentials are picked up by the SDK's default credential chain + // (env vars, instance role, etc.) — we don't read them ourselves. +} + +func Load() (*Config, error) { + cfg := &Config{ + Port: getEnv("PORT", "8080"), + DBDriver: getEnv("DB_DRIVER", "postgres"), + DatabaseURL: os.Getenv("DATABASE_URL"), + OIDCIssuerURL: os.Getenv("OIDC_ISSUER_URL"), + OIDCClientID: os.Getenv("OIDC_CLIENT_ID"), + OIDCClientSecret: os.Getenv("OIDC_CLIENT_SECRET"), + OIDCRedirectURL: os.Getenv("OIDC_REDIRECT_URL"), + PublicBaseURL: os.Getenv("PUBLIC_BASE_URL"), + JWTSigningSecret: os.Getenv("JWT_SIGNING_SECRET"), + StorageDriver: getEnv("STORAGE_DRIVER", "s3"), + LocalStoragePath: getEnv("LOCAL_STORAGE_PATH", "./data/uploads"), + AWSRegion: os.Getenv("AWS_REGION"), + S3Bucket: os.Getenv("S3_BUCKET_NAME"), + } + + if cfg.DBDriver != "postgres" && cfg.DBDriver != "sqlite" { + return nil, fmt.Errorf("invalid DB_DRIVER %q (must be postgres or sqlite)", cfg.DBDriver) + } + if cfg.StorageDriver != "s3" && cfg.StorageDriver != "local" { + return nil, fmt.Errorf("invalid STORAGE_DRIVER %q (must be s3 or local)", cfg.StorageDriver) + } + + required := map[string]string{ + "DATABASE_URL": cfg.DatabaseURL, + "OIDC_ISSUER_URL": cfg.OIDCIssuerURL, + "OIDC_CLIENT_ID": cfg.OIDCClientID, + "OIDC_CLIENT_SECRET": cfg.OIDCClientSecret, + "OIDC_REDIRECT_URL": cfg.OIDCRedirectURL, + "PUBLIC_BASE_URL": cfg.PublicBaseURL, + "JWT_SIGNING_SECRET": cfg.JWTSigningSecret, + } + // S3 credentials only matter when actually using S3. + if cfg.StorageDriver == "s3" { + required["AWS_REGION"] = cfg.AWSRegion + required["S3_BUCKET_NAME"] = cfg.S3Bucket + } + for name, val := range required { + if val == "" { + return nil, fmt.Errorf("missing required env var %s", name) + } + } + + return cfg, nil +} + +func getEnv(key, fallback string) string { + if v := os.Getenv(key); v != "" { + return v + } + return fallback +} diff --git a/backend/internal/db/db.go b/backend/internal/db/db.go new file mode 100644 index 0000000..389ef68 --- /dev/null +++ b/backend/internal/db/db.go @@ -0,0 +1,99 @@ +// Package db wraps the DB connection and applies the schema on startup so +// there's no separate migrate step for the operator to remember. Supports +// Postgres (production) and SQLite (local dev/testing without a real +// Postgres instance) via DB_DRIVER. +package db + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/golang-migrate/migrate/v4" + "github.com/golang-migrate/migrate/v4/database/postgres" + "github.com/golang-migrate/migrate/v4/source/iofs" + "github.com/jmoiron/sqlx" + + _ "github.com/lib/pq" // postgres driver + _ "modernc.org/sqlite" // pure-Go sqlite driver, no CGO + + "vlog/migrations" +) + +// Connect opens the DB connection for the given driver ("postgres" or +// "sqlite") and applies the schema. +func Connect(driver, databaseURL string) (*sqlx.DB, error) { + switch driver { + case "postgres": + return connectPostgres(databaseURL) + case "sqlite": + return connectSQLite(databaseURL) + default: + return nil, fmt.Errorf("invalid DB_DRIVER %q (must be postgres or sqlite)", driver) + } +} + +func connectPostgres(databaseURL string) (*sqlx.DB, error) { + conn, err := sqlx.Connect("postgres", databaseURL) + if err != nil { + return nil, fmt.Errorf("connect to postgres: %w", err) + } + + sourceDriver, err := iofs.New(migrations.PostgresFS, "postgres") + if err != nil { + conn.Close() + return nil, fmt.Errorf("load embedded migrations: %w", err) + } + dbDriver, err := postgres.WithInstance(conn.DB, &postgres.Config{}) + if err != nil { + conn.Close() + return nil, fmt.Errorf("init postgres migrate driver: %w", err) + } + m, err := migrate.NewWithInstance("iofs", sourceDriver, "postgres", dbDriver) + if err != nil { + conn.Close() + return nil, fmt.Errorf("init migrate instance: %w", err) + } + if err := m.Up(); err != nil && err != migrate.ErrNoChange { + conn.Close() + return nil, fmt.Errorf("run migrations: %w", err) + } + + return conn, nil +} + +// connectSQLite treats databaseURL as a filesystem path to the DB file +// (e.g. "./data/vlog.db"). The schema is applied idempotently on every +// startup rather than through golang-migrate — see migrations/sqlite/schema.sql. +func connectSQLite(path string) (*sqlx.DB, error) { + if dir := filepath.Dir(path); dir != "." && dir != "" { + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, fmt.Errorf("create sqlite db directory: %w", err) + } + } + + conn, err := sqlx.Connect("sqlite", path) + if err != nil { + return nil, fmt.Errorf("connect to sqlite: %w", err) + } + + // SQLite handles one writer at a time anyway; capping the pool at a + // single connection sidesteps per-connection PRAGMA/locking headaches + // entirely. Fine for the local dev/testing use case this is for. + conn.SetMaxOpenConns(1) + + if _, err := conn.Exec(`PRAGMA foreign_keys = ON`); err != nil { + conn.Close() + return nil, fmt.Errorf("enable sqlite foreign keys: %w", err) + } + if _, err := conn.Exec(migrations.SQLiteSchemaSQL); err != nil { + conn.Close() + return nil, fmt.Errorf("apply sqlite schema: %w", err) + } + if err := ensureSQLiteColumns(conn); err != nil { + conn.Close() + return nil, fmt.Errorf("apply sqlite column additions: %w", err) + } + + return conn, nil +} diff --git a/backend/internal/db/db_test.go b/backend/internal/db/db_test.go new file mode 100644 index 0000000..10b8dd5 --- /dev/null +++ b/backend/internal/db/db_test.go @@ -0,0 +1,66 @@ +package db + +import ( + "path/filepath" + "testing" + + "github.com/jmoiron/sqlx" + + _ "modernc.org/sqlite" +) + +// TestSQLiteAddsMissingColumns simulates exactly the bug a user hit: an +// existing local .db file created before share_token/service_interval_*/ +// is_service existed. Connect must add them in place, not require deleting +// the file. The "old" schema is hand-built (not via schema.sql, which +// already has the new columns) so CREATE TABLE IF NOT EXISTS in the real +// connectSQLite is a genuine no-op against it, same as it would be against +// a real pre-existing file. +func TestSQLiteAddsMissingColumns(t *testing.T) { + path := filepath.Join(t.TempDir(), "old.db") + + oldConn, err := sqlx.Connect("sqlite", path) + if err != nil { + t.Fatalf("open old-style db: %v", err) + } + for _, stmt := range []string{ + `CREATE TABLE users (id TEXT PRIMARY KEY, oidc_sub TEXT NOT NULL UNIQUE, email TEXT NOT NULL, name TEXT, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)`, + `CREATE TABLE cars (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, rego TEXT NOT NULL, odometer INTEGER, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)`, + `CREATE TABLE service_entries (id TEXT PRIMARY KEY, car_id TEXT NOT NULL, entry_date DATE NOT NULL, entry_type TEXT NOT NULL, odometer INTEGER, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)`, + } { + if _, err := oldConn.Exec(stmt); err != nil { + t.Fatalf("build old-style schema (%s): %v", stmt, err) + } + } + oldConn.Close() + + // Reconnecting through the real path (as a fresh app start would) must + // backfill the missing columns without erroring and without the + // caller/operator doing anything special. + conn, err := connectSQLite(path) + if err != nil { + t.Fatalf("connect against old-style schema: %v", err) + } + defer conn.Close() + + if _, err := conn.Exec(`INSERT INTO cars (id, user_id, rego, service_interval_km) VALUES ('c1', 'u1', 'ABC123', 10000)`); err != nil { + t.Fatalf("insert using backfilled column: %v", err) + } + if _, err := conn.Exec(`UPDATE cars SET share_token = 'tok1' WHERE id = 'c1'`); err != nil { + t.Fatalf("update using backfilled share_token column: %v", err) + } + var count int + if err := conn.Get(&count, `SELECT COUNT(*) FROM cars WHERE share_token = 'tok1'`); err != nil || count != 1 { + t.Fatalf("expected to find the row by its backfilled share_token, err=%v count=%d", err, count) + } + + // The share_token uniqueness constraint must actually be enforced, not + // just present as an unconstrained column. + if _, err := conn.Exec(`INSERT INTO cars (id, user_id, rego, share_token) VALUES ('c2', 'u1', 'XYZ789', 'tok1')`); err == nil { + t.Fatal("expected duplicate share_token to be rejected") + } + + if _, err := conn.Exec(`INSERT INTO service_entries (id, car_id, entry_date, entry_type, is_service) VALUES ('e1', 'c1', '2026-01-01', 'Service', 1)`); err != nil { + t.Fatalf("insert using backfilled is_service column: %v", err) + } +} diff --git a/backend/internal/db/sqlite_migrate.go b/backend/internal/db/sqlite_migrate.go new file mode 100644 index 0000000..416908a --- /dev/null +++ b/backend/internal/db/sqlite_migrate.go @@ -0,0 +1,62 @@ +package db + +import ( + "fmt" + + "github.com/jmoiron/sqlx" +) + +// sqliteColumnAdditions lists every column added to a pre-existing table +// since schema.sql's original CREATE TABLE statements. CREATE TABLE IF NOT +// EXISTS is a no-op against a table that already exists, so an existing +// local .db file never picks up new columns just by editing schema.sql — +// this applies them the same way a real migration would, without requiring +// the developer to delete and recreate their local dev database every time +// the schema grows during active development. +var sqliteColumnAdditions = []struct { + table string + column string + ddl string // type + constraints, everything after the column name +}{ + {"cars", "share_token", "TEXT"}, + {"cars", "service_interval_km", "INTEGER"}, + {"cars", "service_interval_months", "INTEGER"}, + {"service_entries", "is_service", "BOOLEAN NOT NULL DEFAULT 0"}, +} + +// ensureSQLiteColumns adds any missing columns from the list above, and +// (re)creates the share_token uniqueness index — SQLite's ALTER TABLE ADD +// COLUMN can't declare UNIQUE inline, so that's a separate CREATE UNIQUE +// INDEX IF NOT EXISTS, safe to run every time regardless of whether the +// column was just added or already existed. +func ensureSQLiteColumns(conn *sqlx.DB) error { + for _, c := range sqliteColumnAdditions { + var existing []string + // pragma_table_info as a table-valued function (not the bare PRAGMA + // statement) so this is a normal SELECT we can project down to just + // the column we need — the bare PRAGMA form always returns every + // column (cid, name, type, ...), which sqlx's strict struct scan + // rejects unless every one of them has a matching destination field. + if err := conn.Select(&existing, `SELECT name FROM pragma_table_info(?)`, c.table); err != nil { + return fmt.Errorf("inspect %s columns: %w", c.table, err) + } + found := false + for _, name := range existing { + if name == c.column { + found = true + break + } + } + if !found { + if _, err := conn.Exec(fmt.Sprintf(`ALTER TABLE %s ADD COLUMN %s %s`, c.table, c.column, c.ddl)); err != nil { + return fmt.Errorf("add column %s.%s: %w", c.table, c.column, err) + } + } + } + + if _, err := conn.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_cars_share_token ON cars(share_token)`); err != nil { + return fmt.Errorf("create share_token index: %w", err) + } + + return nil +} diff --git a/backend/internal/handlers/auth.go b/backend/internal/handlers/auth.go new file mode 100644 index 0000000..c519c28 --- /dev/null +++ b/backend/internal/handlers/auth.go @@ -0,0 +1,74 @@ +package handlers + +import ( + "net/http" + + "github.com/google/uuid" + + "vlog/internal/auth" +) + +// Login kicks off the OIDC authorization-code flow. +func (h *Handlers) Login(w http.ResponseWriter, r *http.Request) { + h.Authenticator.BeginLogin(w, r) +} + +// Callback completes the OIDC flow: verifies the ID token, JIT-provisions +// the user row, mints our own session JWT, and redirects into the app. +func (h *Handlers) Callback(w http.ResponseWriter, r *http.Request) { + claims, err := h.Authenticator.HandleCallback(r.Context(), w, r) + if err != nil { + writeError(w, http.StatusUnauthorized, "login failed: "+err.Error()) + return + } + + var name *string + if claims.Name != "" { + name = &claims.Name + } + + var userID string + err = h.dbGet(r.Context(), &userID, ` + INSERT INTO users (id, oidc_sub, email, name) + VALUES (?, ?, ?, ?) + ON CONFLICT (oidc_sub) DO UPDATE SET email = excluded.email, name = excluded.name + RETURNING id + `, uuid.New().String(), claims.Sub, claims.Email, name) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to provision user") + return + } + + token, err := auth.MintSessionJWT(h.JWTSecret, userID, claims.Email) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to mint session") + return + } + + auth.SetSessionCookie(w, token, h.SecureCookies) + http.Redirect(w, r, "/", http.StatusFound) +} + +// Logout clears the session cookie. +func (h *Handlers) Logout(w http.ResponseWriter, r *http.Request) { + auth.ClearSessionCookie(w, h.SecureCookies) + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +// Me returns the current authenticated user. +func (h *Handlers) Me(w http.ResponseWriter, r *http.Request) { + userID, _ := auth.UserIDFromContext(r.Context()) + + var user struct { + ID string `db:"id" json:"id"` + Email string `db:"email" json:"email"` + Name *string `db:"name" json:"name"` + } + err := h.dbGet(r.Context(), &user, `SELECT id, email, name FROM users WHERE id = ?`, userID) + if err != nil { + writeError(w, http.StatusUnauthorized, "user not found") + return + } + + writeJSON(w, http.StatusOK, user) +} diff --git a/backend/internal/handlers/cars.go b/backend/internal/handlers/cars.go new file mode 100644 index 0000000..7d46fdc --- /dev/null +++ b/backend/internal/handlers/cars.go @@ -0,0 +1,302 @@ +package handlers + +import ( + "database/sql" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + + "github.com/google/uuid" + + "vlog/internal/auth" + "vlog/internal/models" + "vlog/internal/storage" +) + +// ListCars returns the current user's garage. +func (h *Handlers) ListCars(w http.ResponseWriter, r *http.Request) { + userID, _ := auth.UserIDFromContext(r.Context()) + + cars := []models.Car{} // not "var" — an empty result must encode as [], not null + err := h.dbSelect(r.Context(), &cars, ` + SELECT * FROM cars WHERE user_id = ? ORDER BY created_at DESC + `, userID) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to list cars") + return + } + for i := range cars { + cars[i].HasPhoto = cars[i].PhotoS3Key != nil + } + writeJSON(w, http.StatusOK, cars) +} + +// CreateCar creates a new car in the current user's garage. +func (h *Handlers) CreateCar(w http.ResponseWriter, r *http.Request) { + userID, _ := auth.UserIDFromContext(r.Context()) + + var in models.CarInput + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return + } + if in.Rego == "" { + writeError(w, http.StatusBadRequest, "rego is required") + return + } + + regoExpiry, err := parseOptionalDate(in.RegoExpiry) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid regoExpiry") + return + } + wofExpiry, err := parseOptionalDate(in.WofExpiry) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid wofExpiry") + return + } + + var car models.Car + err = h.dbGet(r.Context(), &car, ` + INSERT INTO cars (id, user_id, rego, make, model, year, color, odometer, rego_expiry, wof_expiry, service_interval_km, service_interval_months) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + RETURNING * + `, uuid.New().String(), userID, in.Rego, in.Make, in.Model, in.Year, in.Color, in.Odometer, regoExpiry, wofExpiry, in.ServiceIntervalKM, in.ServiceIntervalMonths) + if err != nil { + if isUniqueConstraintErr(err) { + writeError(w, http.StatusConflict, "could not create car (rego may already exist in your garage)") + } else { + writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to create car: %v", err)) + } + return + } + + writeJSON(w, http.StatusCreated, car) +} + +// GetCar returns a single car owned by the current user. +func (h *Handlers) GetCar(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + car.HasPhoto = car.PhotoS3Key != nil + writeJSON(w, http.StatusOK, car) +} + +// UpdateCar edits an existing car. +func (h *Handlers) UpdateCar(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + + var in models.CarInput + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return + } + if in.Rego == "" { + writeError(w, http.StatusBadRequest, "rego is required") + return + } + + regoExpiry, err := parseOptionalDate(in.RegoExpiry) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid regoExpiry") + return + } + wofExpiry, err := parseOptionalDate(in.WofExpiry) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid wofExpiry") + return + } + + var updated models.Car + err = h.dbGet(r.Context(), &updated, ` + UPDATE cars + SET rego = ?, make = ?, model = ?, year = ?, color = ?, + odometer = ?, rego_expiry = ?, wof_expiry = ?, + service_interval_km = ?, service_interval_months = ?, updated_at = CURRENT_TIMESTAMP + WHERE id = ? + RETURNING * + `, in.Rego, in.Make, in.Model, in.Year, in.Color, in.Odometer, regoExpiry, wofExpiry, + in.ServiceIntervalKM, in.ServiceIntervalMonths, car.ID) + if err != nil { + if isUniqueConstraintErr(err) { + writeError(w, http.StatusConflict, "could not update car (rego may already exist in your garage)") + } else { + writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to update car: %v", err)) + } + return + } + + writeJSON(w, http.StatusOK, updated) +} + +// DeleteCar removes a car (cascades to service entries, files, reminders in +// the DB; best-effort cleans up its photo in storage). +func (h *Handlers) DeleteCar(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + + if _, err := h.dbExec(r.Context(), `DELETE FROM cars WHERE id = ?`, car.ID); err != nil { + writeError(w, http.StatusInternalServerError, "failed to delete car") + return + } + + if car.PhotoS3Key != nil { + _ = h.Storage.Delete(r.Context(), *car.PhotoS3Key) + } + + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +// UploadCarPhoto accepts a multipart PNG/JPEG upload and replaces the car's photo. +func (h *Handlers) UploadCarPhoto(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + + file, contentType, ok := parseUploadedFile(w, r, 10<<20, storage.AllowedPhotoTypes) + if !ok { + return + } + defer file.Close() + + oldKey := car.PhotoS3Key + key := fmt.Sprintf("users/%s/cars/%s/photo.%s", car.UserID, car.ID, extensionForContentType(contentType)) + + if err := h.Storage.Upload(r.Context(), key, contentType, file); err != nil { + writeError(w, http.StatusInternalServerError, "failed to upload photo") + return + } + + if _, err := h.dbExec(r.Context(), ` + UPDATE cars SET photo_s3_key = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? + `, key, car.ID); err != nil { + writeError(w, http.StatusInternalServerError, "failed to save photo reference") + return + } + + if oldKey != nil && *oldKey != key { + _ = h.Storage.Delete(r.Context(), *oldKey) + } + + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +// GetCarPhoto streams the car's photo from storage. +func (h *Handlers) GetCarPhoto(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + if car.PhotoS3Key == nil { + writeError(w, http.StatusNotFound, "no photo set") + return + } + + body, err := h.Storage.Get(r.Context(), *car.PhotoS3Key) + if err != nil { + writeError(w, http.StatusNotFound, "photo not found") + return + } + defer body.Close() + + w.Header().Set("Content-Type", contentTypeForExtension(*car.PhotoS3Key)) + w.Header().Set("Cache-Control", "private, max-age=60") + io.Copy(w, body) +} + +// UpdateOdometer is a lightweight endpoint for just bumping the odometer +// reading — quicker than resending the whole car record via UpdateCar. +func (h *Handlers) UpdateOdometer(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + + var body struct { + Odometer int `json:"odometer"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return + } + if body.Odometer < 0 { + writeError(w, http.StatusBadRequest, "odometer must be positive") + return + } + + var updated models.Car + err := h.dbGet(r.Context(), &updated, ` + UPDATE cars SET odometer = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? RETURNING * + `, body.Odometer, car.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to update odometer") + return + } + updated.HasPhoto = updated.PhotoS3Key != nil + writeJSON(w, http.StatusOK, updated) +} + +// GenerateShareLink turns on (or regenerates, invalidating the previous +// link/QR code) public read-only sharing for a car. +func (h *Handlers) GenerateShareLink(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + + token := randomID() + randomID() // 64 hex chars of entropy — not guessable + var updated models.Car + err := h.dbGet(r.Context(), &updated, ` + UPDATE cars SET share_token = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? RETURNING * + `, token, car.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to generate share link") + return + } + updated.HasPhoto = updated.PhotoS3Key != nil + writeJSON(w, http.StatusOK, updated) +} + +// RevokeShareLink turns off public sharing for a car. +func (h *Handlers) RevokeShareLink(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + if _, err := h.dbExec(r.Context(), ` + UPDATE cars SET share_token = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ? + `, car.ID); err != nil { + writeError(w, http.StatusInternalServerError, "failed to revoke share link") + return + } + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func (h *Handlers) loadOwnedCar(w http.ResponseWriter, r *http.Request) (*models.Car, bool) { + userID, _ := auth.UserIDFromContext(r.Context()) + carID := r.PathValue("carId") + + var car models.Car + err := h.dbGet(r.Context(), &car, ` + SELECT * FROM cars WHERE id = ? AND user_id = ? + `, carID, userID) + if errors.Is(err, sql.ErrNoRows) { + writeError(w, http.StatusNotFound, "car not found") + return nil, false + } + if err != nil { + writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to load car: %v", err)) + return nil, false + } + return &car, true +} diff --git a/backend/internal/handlers/dashboard.go b/backend/internal/handlers/dashboard.go new file mode 100644 index 0000000..cce81d9 --- /dev/null +++ b/backend/internal/handlers/dashboard.go @@ -0,0 +1,64 @@ +package handlers + +import ( + "net/http" + + "github.com/jmoiron/sqlx" + + "vlog/internal/auth" + "vlog/internal/models" +) + +// Dashboard computes the "what's coming up" view for the current user: +// open reminders due soon/overdue (real + synthesized rego/WoF/service-due), +// across every car. It's computed at request time — no scheduler, no +// email, matching the in-app-only reminder decision. Shares its synthesis +// logic with the car-scoped ListReminders (see reminder_view.go) so the two +// views never disagree about what's due. +func (h *Handlers) Dashboard(w http.ResponseWriter, r *http.Request) { + userID, _ := auth.UserIDFromContext(r.Context()) + todayDate := today() + + var cars []models.Car + if err := h.dbSelect(r.Context(), &cars, `SELECT * FROM cars WHERE user_id = ?`, userID); err != nil { + writeError(w, http.StatusInternalServerError, "failed to load dashboard") + return + } + + carByID := make(map[string]models.Car, len(cars)) + carIDs := make([]string, len(cars)) + for i, c := range cars { + carByID[c.ID] = c + carIDs[i] = c.ID + } + + items := []models.ReminderView{} // not "var" — an empty result must encode as [], not null + + if len(carIDs) > 0 { + query, args, err := sqlx.In(`SELECT * FROM reminders WHERE car_id IN (?) AND completed_at IS NULL`, carIDs) + if err == nil { + var reminders []models.Reminder + if err := h.dbSelect(r.Context(), &reminders, query, args...); err == nil { + for _, rem := range reminders { + car := carByID[rem.CarID] + view := reminderToView(rem, car.Rego, car.Odometer, todayDate) + if view.Status == "overdue" || view.Status == "upcoming" { + items = append(items, view) + } + } + } + } + } + + for _, c := range cars { + car := c // local copy — synthesizedReminders takes a pointer + for _, view := range synthesizedReminders(r.Context(), h, &car, todayDate) { + if view.Status == "overdue" || view.Status == "upcoming" { + items = append(items, view) + } + } + } + + sortReminderViews(items) + writeJSON(w, http.StatusOK, items) +} diff --git a/backend/internal/handlers/dates.go b/backend/internal/handlers/dates.go new file mode 100644 index 0000000..36a0418 --- /dev/null +++ b/backend/internal/handlers/dates.go @@ -0,0 +1,18 @@ +package handlers + +import "time" + +const dateLayout = "2006-01-02" + +// parseOptionalDate parses a "YYYY-MM-DD" string, treating nil/empty as no +// value. Used for the optional date fields on car/reminder inputs. +func parseOptionalDate(s *string) (*time.Time, error) { + if s == nil || *s == "" { + return nil, nil + } + t, err := time.Parse(dateLayout, *s) + if err != nil { + return nil, err + } + return &t, nil +} diff --git a/backend/internal/handlers/files.go b/backend/internal/handlers/files.go new file mode 100644 index 0000000..0199eb9 --- /dev/null +++ b/backend/internal/handlers/files.go @@ -0,0 +1,149 @@ +package handlers + +import ( + "crypto/rand" + "database/sql" + "encoding/hex" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "path/filepath" + "strings" + + "vlog/internal/auth" + "vlog/internal/models" + "vlog/internal/storage" +) + +// parseUploadedFile extracts the "file" multipart field, enforces maxBytes, +// and sniffs+validates its real content type against allowed (never trusts +// the client-declared type/extension). Returns the file handle reset to the +// start, ready to stream to storage — caller must Close it. +func parseUploadedFile(w http.ResponseWriter, r *http.Request, maxBytes int64, allowed map[string]bool) (multipart.File, string, bool) { + r.Body = http.MaxBytesReader(w, r.Body, maxBytes) + if err := r.ParseMultipartForm(maxBytes); err != nil { + writeError(w, http.StatusBadRequest, "file too large or invalid upload") + return nil, "", false + } + + file, _, err := r.FormFile("file") + if err != nil { + writeError(w, http.StatusBadRequest, "missing file") + return nil, "", false + } + + contentType, err := storage.DetectAndValidate(file, allowed) + if err != nil { + file.Close() + writeError(w, http.StatusUnsupportedMediaType, err.Error()) + return nil, "", false + } + + return file, contentType, true +} + +func extensionForContentType(ct string) string { + switch ct { + case "image/png": + return "png" + case "image/jpeg": + return "jpg" + case "application/pdf": + return "pdf" + default: + return "bin" + } +} + +func contentTypeForExtension(key string) string { + switch { + case strings.HasSuffix(key, ".png"): + return "image/png" + case strings.HasSuffix(key, ".jpg"), strings.HasSuffix(key, ".jpeg"): + return "image/jpeg" + case strings.HasSuffix(key, ".pdf"): + return "application/pdf" + default: + return "application/octet-stream" + } +} + +func randomID() string { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return hex.EncodeToString(b) +} + +// sanitizeFileName strips any path components and whitespace so it's safe +// to embed in a storage key and to send back in Content-Disposition. +func sanitizeFileName(name string) string { + name = filepath.Base(name) + name = strings.ReplaceAll(name, " ", "_") + if name == "" || name == "." || name == "/" { + return "file" + } + return name +} + +// GetFile streams a service-entry attachment after verifying the requesting +// user owns the car the entry belongs to. +func (h *Handlers) GetFile(w http.ResponseWriter, r *http.Request) { + file, ok := h.loadOwnedFile(w, r) + if !ok { + return + } + + body, err := h.Storage.Get(r.Context(), file.S3Key) + if err != nil { + writeError(w, http.StatusNotFound, "file not found in storage") + return + } + defer body.Close() + + w.Header().Set("Content-Type", file.ContentType) + w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, file.FileName)) + io.Copy(w, body) +} + +// DeleteFile removes a single attachment. +func (h *Handlers) DeleteFile(w http.ResponseWriter, r *http.Request) { + file, ok := h.loadOwnedFile(w, r) + if !ok { + return + } + + if _, err := h.dbExec(r.Context(), `DELETE FROM service_entry_files WHERE id = ?`, file.ID); err != nil { + writeError(w, http.StatusInternalServerError, "failed to delete file") + return + } + _ = h.Storage.Delete(r.Context(), file.S3Key) + + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func (h *Handlers) loadOwnedFile(w http.ResponseWriter, r *http.Request) (*models.ServiceEntryFile, bool) { + userID, _ := auth.UserIDFromContext(r.Context()) + fileID := r.PathValue("fileId") + + var file models.ServiceEntryFile + err := h.dbGet(r.Context(), &file, ` + SELECT sef.* + FROM service_entry_files sef + JOIN service_entries se ON se.id = sef.service_entry_id + JOIN cars c ON c.id = se.car_id + WHERE sef.id = ? AND c.user_id = ? + `, fileID, userID) + if errors.Is(err, sql.ErrNoRows) { + writeError(w, http.StatusNotFound, "file not found") + return nil, false + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to load file") + return nil, false + } + return &file, true +} diff --git a/backend/internal/handlers/fuel_entries.go b/backend/internal/handlers/fuel_entries.go new file mode 100644 index 0000000..628e245 --- /dev/null +++ b/backend/internal/handlers/fuel_entries.go @@ -0,0 +1,149 @@ +package handlers + +import ( + "database/sql" + "encoding/json" + "errors" + "net/http" + "time" + + "github.com/google/uuid" + + "vlog/internal/auth" + "vlog/internal/models" +) + +// ListFuelEntries returns one page of a car's fuel-up history, newest +// first. Paginated for the same reason as service entries — no unbounded +// fetch regardless of how long the car's been tracked. +func (h *Handlers) ListFuelEntries(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + limit, offset := parsePagination(r) + + entries := []models.FuelEntry{} // not "var" — empty result must encode as [], not null + err := h.dbSelect(r.Context(), &entries, ` + SELECT * FROM fuel_entries WHERE car_id = ? + ORDER BY entry_date DESC, created_at DESC + LIMIT ? OFFSET ? + `, car.ID, limit+1, offset) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to list fuel entries") + return + } + + entries, hasMore := paginate(limit, entries) + writeJSON(w, http.StatusOK, page[models.FuelEntry]{Items: entries, HasMore: hasMore}) +} + +// CreateFuelEntry adds a fuel-up to a car. +func (h *Handlers) CreateFuelEntry(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + + in, entryDate, ok := decodeFuelEntryInput(w, r) + if !ok { + return + } + + var entry models.FuelEntry + err := h.dbGet(r.Context(), &entry, ` + INSERT INTO fuel_entries (id, car_id, entry_date, litres, cost, odometer, location, notes) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + RETURNING * + `, uuid.New().String(), car.ID, entryDate, in.Litres, in.Cost, in.Odometer, in.Location, in.Notes) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to create fuel entry") + return + } + + writeJSON(w, http.StatusCreated, entry) +} + +// UpdateFuelEntry edits a fuel entry's fields. +func (h *Handlers) UpdateFuelEntry(w http.ResponseWriter, r *http.Request) { + entry, ok := h.loadOwnedFuelEntry(w, r) + if !ok { + return + } + + in, entryDate, ok := decodeFuelEntryInput(w, r) + if !ok { + return + } + + var updated models.FuelEntry + err := h.dbGet(r.Context(), &updated, ` + UPDATE fuel_entries + SET entry_date = ?, litres = ?, cost = ?, odometer = ?, location = ?, notes = ? + WHERE id = ? + RETURNING * + `, entryDate, in.Litres, in.Cost, in.Odometer, in.Location, in.Notes, entry.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to update fuel entry") + return + } + + writeJSON(w, http.StatusOK, updated) +} + +// DeleteFuelEntry removes a fuel entry. +func (h *Handlers) DeleteFuelEntry(w http.ResponseWriter, r *http.Request) { + entry, ok := h.loadOwnedFuelEntry(w, r) + if !ok { + return + } + if _, err := h.dbExec(r.Context(), `DELETE FROM fuel_entries WHERE id = ?`, entry.ID); err != nil { + writeError(w, http.StatusInternalServerError, "failed to delete fuel entry") + return + } + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func decodeFuelEntryInput(w http.ResponseWriter, r *http.Request) (models.FuelEntryInput, time.Time, bool) { + var in models.FuelEntryInput + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return in, time.Time{}, false + } + if in.Litres <= 0 { + writeError(w, http.StatusBadRequest, "litres must be greater than 0") + return in, time.Time{}, false + } + if in.Cost <= 0 { + writeError(w, http.StatusBadRequest, "cost must be greater than 0") + return in, time.Time{}, false + } + entryDate, err := time.Parse(dateLayout, in.EntryDate) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid entryDate") + return in, time.Time{}, false + } + return in, entryDate, true +} + +func (h *Handlers) loadOwnedFuelEntry(w http.ResponseWriter, r *http.Request) (*models.FuelEntry, bool) { + userID, _ := auth.UserIDFromContext(r.Context()) + entryID := r.PathValue("entryId") + + var entry models.FuelEntry + err := h.dbGet(r.Context(), &entry, ` + SELECT fe.* + FROM fuel_entries fe + JOIN cars c ON c.id = fe.car_id + WHERE fe.id = ? AND c.user_id = ? + `, entryID, userID) + if errors.Is(err, sql.ErrNoRows) { + writeError(w, http.StatusNotFound, "fuel entry not found") + return nil, false + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to load fuel entry") + return nil, false + } + return &entry, true +} diff --git a/backend/internal/handlers/handlers.go b/backend/internal/handlers/handlers.go new file mode 100644 index 0000000..36fbdde --- /dev/null +++ b/backend/internal/handlers/handlers.go @@ -0,0 +1,125 @@ +// Package handlers implements the JSON API. All handlers hang off Handlers, +// which carries the shared dependencies (DB, storage, auth) they need. +package handlers + +import ( + "context" + "database/sql" + "encoding/json" + "net/http" + "strconv" + "strings" + + "github.com/jmoiron/sqlx" + + "vlog/internal/auth" + "vlog/internal/storage" +) + +type Handlers struct { + DB *sqlx.DB + Storage storage.Storage + Authenticator *auth.Authenticator + JWTSecret string + SecureCookies bool +} + +func New(db *sqlx.DB, store storage.Storage, authenticator *auth.Authenticator, jwtSecret string, secureCookies bool) *Handlers { + return &Handlers{ + DB: db, + Storage: store, + Authenticator: authenticator, + JWTSecret: jwtSecret, + SecureCookies: secureCookies, + } +} + +// All queries in this package are written with "?" placeholders (SQLite's +// native style) and go through these three helpers, which rebind to "$1, +// $2, ..." automatically when running against Postgres. This is what lets +// the same query strings work against both DB_DRIVER options. + +func (h *Handlers) dbGet(ctx context.Context, dest interface{}, query string, args ...interface{}) error { + return h.DB.GetContext(ctx, dest, h.DB.Rebind(query), args...) +} + +func (h *Handlers) dbSelect(ctx context.Context, dest interface{}, query string, args ...interface{}) error { + return h.DB.SelectContext(ctx, dest, h.DB.Rebind(query), args...) +} + +func (h *Handlers) dbExec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + return h.DB.ExecContext(ctx, h.DB.Rebind(query), args...) +} + +// writeJSON marshals v as the response body, or 500s if it fails. +func writeJSON(w http.ResponseWriter, status int, v interface{}) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if v == nil { + return + } + if err := json.NewEncoder(w).Encode(v); err != nil { + // Response is already partially written at this point; just log. + // (No logger wired up yet — keep it dead simple and let it be silent + // in the rare case encoding itself fails.) + _ = err + } +} + +func writeError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, map[string]string{"error": message}) +} + +// isUniqueConstraintErr distinguishes an actual unique-constraint violation +// (e.g. duplicate rego) from any other DB error, so a schema/column problem +// during development doesn't get mislabeled as "already exists" and hide +// the real cause. Postgres and SQLite word this differently, so it's a +// substring match on the driver's own error text rather than a typed +// sentinel — good enough since the only thing we do with it is pick the +// response code/message, not branch on a specific constraint. +func isUniqueConstraintErr(err error) bool { + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "unique constraint") || strings.Contains(msg, "duplicate key") +} + +// page is the response shape for every paginated list endpoint — long lists +// (service history, knowledgebase) load a page at a time instead of +// dumping everything into one response/DOM. +type page[T any] struct { + Items []T `json:"items"` + HasMore bool `json:"hasMore"` +} + +const ( + defaultPageSize = 20 + maxPageSize = 100 +) + +// parsePagination reads ?limit=&offset= from the query string, applying +// sane defaults/bounds so a bad or missing value can't blow up the page +// size or request something nonsensical. +func parsePagination(r *http.Request) (limit, offset int) { + limit = defaultPageSize + if v, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && v > 0 { + limit = v + } + if limit > maxPageSize { + limit = maxPageSize + } + offset = 0 + if v, err := strconv.Atoi(r.URL.Query().Get("offset")); err == nil && v > 0 { + offset = v + } + return limit, offset +} + +// paginate expects rows fetched with LIMIT limit+1, so it can tell whether +// there's a next page without a separate COUNT(*) query — then trims back +// down to limit. +func paginate[T any](limit int, rows []T) (trimmed []T, hasMore bool) { + hasMore = len(rows) > limit + if hasMore { + rows = rows[:limit] + } + return rows, hasMore +} diff --git a/backend/internal/handlers/knowledge.go b/backend/internal/handlers/knowledge.go new file mode 100644 index 0000000..57b054e --- /dev/null +++ b/backend/internal/handlers/knowledge.go @@ -0,0 +1,140 @@ +package handlers + +import ( + "database/sql" + "encoding/json" + "errors" + "net/http" + + "github.com/google/uuid" + + "vlog/internal/auth" + "vlog/internal/models" +) + +// ListKnowledge returns one page of a car's knowledgebase entries +// (procedures, common problems, reference info like coolant type), most +// recently updated first. Paginated (?limit=&offset=) for the same reason +// as service entries — a big knowledgebase shouldn't mean one giant fetch. +func (h *Handlers) ListKnowledge(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + limit, offset := parsePagination(r) + + entries := []models.KnowledgeEntry{} // not "var" — empty result must encode as [], not null + err := h.dbSelect(r.Context(), &entries, ` + SELECT * FROM knowledge_entries WHERE car_id = ? + ORDER BY updated_at DESC + LIMIT ? OFFSET ? + `, car.ID, limit+1, offset) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to list knowledge entries") + return + } + + entries, hasMore := paginate(limit, entries) + writeJSON(w, http.StatusOK, page[models.KnowledgeEntry]{Items: entries, HasMore: hasMore}) +} + +// CreateKnowledge adds a new knowledgebase entry to a car. +func (h *Handlers) CreateKnowledge(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + + in, ok := decodeKnowledgeInput(w, r) + if !ok { + return + } + + var entry models.KnowledgeEntry + err := h.dbGet(r.Context(), &entry, ` + INSERT INTO knowledge_entries (id, car_id, title, body) + VALUES (?, ?, ?, ?) + RETURNING * + `, uuid.New().String(), car.ID, in.Title, in.Body) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to create knowledge entry") + return + } + + writeJSON(w, http.StatusCreated, entry) +} + +// UpdateKnowledge edits a knowledgebase entry's title/body. +func (h *Handlers) UpdateKnowledge(w http.ResponseWriter, r *http.Request) { + entry, ok := h.loadOwnedKnowledge(w, r) + if !ok { + return + } + + in, ok := decodeKnowledgeInput(w, r) + if !ok { + return + } + + var updated models.KnowledgeEntry + err := h.dbGet(r.Context(), &updated, ` + UPDATE knowledge_entries + SET title = ?, body = ?, updated_at = CURRENT_TIMESTAMP + WHERE id = ? + RETURNING * + `, in.Title, in.Body, entry.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to update knowledge entry") + return + } + + writeJSON(w, http.StatusOK, updated) +} + +// DeleteKnowledge removes a knowledgebase entry. +func (h *Handlers) DeleteKnowledge(w http.ResponseWriter, r *http.Request) { + entry, ok := h.loadOwnedKnowledge(w, r) + if !ok { + return + } + if _, err := h.dbExec(r.Context(), `DELETE FROM knowledge_entries WHERE id = ?`, entry.ID); err != nil { + writeError(w, http.StatusInternalServerError, "failed to delete knowledge entry") + return + } + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func decodeKnowledgeInput(w http.ResponseWriter, r *http.Request) (models.KnowledgeEntryInput, bool) { + var in models.KnowledgeEntryInput + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return in, false + } + if in.Title == "" { + writeError(w, http.StatusBadRequest, "title is required") + return in, false + } + return in, true +} + +func (h *Handlers) loadOwnedKnowledge(w http.ResponseWriter, r *http.Request) (*models.KnowledgeEntry, bool) { + userID, _ := auth.UserIDFromContext(r.Context()) + entryID := r.PathValue("knowledgeId") + + var entry models.KnowledgeEntry + err := h.dbGet(r.Context(), &entry, ` + SELECT k.* + FROM knowledge_entries k + JOIN cars c ON c.id = k.car_id + WHERE k.id = ? AND c.user_id = ? + `, entryID, userID) + if errors.Is(err, sql.ErrNoRows) { + writeError(w, http.StatusNotFound, "knowledge entry not found") + return nil, false + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to load knowledge entry") + return nil, false + } + return &entry, true +} diff --git a/backend/internal/handlers/mileage.go b/backend/internal/handlers/mileage.go new file mode 100644 index 0000000..45a242a --- /dev/null +++ b/backend/internal/handlers/mileage.go @@ -0,0 +1,72 @@ +package handlers + +import ( + "net/http" + "sort" + "time" +) + +type MileageResponse struct { + CurrentOdometer *int `json:"currentOdometer"` + KmPerYear *float64 `json:"kmPerYear"` + // YearsPer100k/Next100kEta answer "how long does it take to put another + // 100,000km on this car at my current rate" — a throughput figure, not + // tied to the odometer's current position (68,420km → 100,000km is a + // misleadingly small gap; this is always a full 100,000km from today). + YearsPer100k *float64 `json:"yearsPer100k"` + Next100kEta *string `json:"next100kEta"` +} + +// milestoneDistance is the block of driving the "how long" estimate is +// measured over — a generic throughput unit, not a specific odometer target. +const milestoneDistance = 100_000 + +// Mileage reports the car's usage rate: an estimated km/year (derived from +// every known odometer+date pair across service and fuel entries, plus the +// car's own current reading) and how long, at that rate, it takes to add +// another 100,000km from today. Needs at least two data points to estimate +// a rate — with fewer, it just reports the current reading. +func (h *Handlers) Mileage(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + + type odometerPoint struct { + EntryDate time.Time `db:"entry_date"` + Odometer int `db:"odometer"` + } + + var points []odometerPoint + _ = h.dbSelect(r.Context(), &points, ` + SELECT entry_date, odometer FROM service_entries WHERE car_id = ? AND odometer IS NOT NULL + UNION ALL + SELECT entry_date, odometer FROM fuel_entries WHERE car_id = ? AND odometer IS NOT NULL + `, car.ID, car.ID) + // best-effort: a query error just means we fall back to "current reading + // only" below, rather than failing the whole endpoint. + + if car.Odometer != nil { + points = append(points, odometerPoint{EntryDate: today(), Odometer: *car.Odometer}) + } + sort.Slice(points, func(i, j int) bool { return points[i].EntryDate.Before(points[j].EntryDate) }) + + resp := MileageResponse{CurrentOdometer: car.Odometer} + + if len(points) >= 2 { + first, last := points[0], points[len(points)-1] + days := last.EntryDate.Sub(first.EntryDate).Hours() / 24 + if days > 0 && last.Odometer > first.Odometer { + kmPerYear := float64(last.Odometer-first.Odometer) / days * 365 + resp.KmPerYear = &kmPerYear + + years := milestoneDistance / kmPerYear + resp.YearsPer100k = &years + + eta := today().AddDate(0, 0, int(years*365)).Format(dateLayout) + resp.Next100kEta = &eta + } + } + + writeJSON(w, http.StatusOK, resp) +} diff --git a/backend/internal/handlers/public.go b/backend/internal/handlers/public.go new file mode 100644 index 0000000..f69c143 --- /dev/null +++ b/backend/internal/handlers/public.go @@ -0,0 +1,136 @@ +// Public, unauthenticated read-only endpoints for a car whose owner has +// turned on sharing (POST /api/cars/{id}/share) — e.g. a QR code stuck in +// the glovebox a mechanic can scan, or a link sent to a buyer. Deliberately +// a separate, narrow surface (not just "the normal endpoints minus auth") +// so there's no risk of it ever exposing more than intended: car identity, +// service history, and its attachments — no reminders, no knowledgebase, no +// owner info. +package handlers + +import ( + "database/sql" + "errors" + "io" + "net/http" + + "vlog/internal/models" +) + +func (h *Handlers) loadCarByShareToken(w http.ResponseWriter, r *http.Request) (*models.Car, bool) { + token := r.PathValue("shareToken") + if token == "" { + writeError(w, http.StatusNotFound, "not found") + return nil, false + } + + var car models.Car + err := h.dbGet(r.Context(), &car, `SELECT * FROM cars WHERE share_token = ?`, token) + if errors.Is(err, sql.ErrNoRows) { + writeError(w, http.StatusNotFound, "not found") + return nil, false + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to load car") + return nil, false + } + return &car, true +} + +// PublicCar returns just enough to identify the car — no owner/user info. +func (h *Handlers) PublicCar(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadCarByShareToken(w, r) + if !ok { + return + } + writeJSON(w, http.StatusOK, map[string]interface{}{ + "rego": car.Rego, + "make": car.Make, + "model": car.Model, + "year": car.Year, + "color": car.Color, + "hasPhoto": car.PhotoS3Key != nil, + }) +} + +// PublicCarPhoto streams the car's photo — helps confirm it's the right car. +func (h *Handlers) PublicCarPhoto(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadCarByShareToken(w, r) + if !ok { + return + } + if car.PhotoS3Key == nil { + writeError(w, http.StatusNotFound, "no photo set") + return + } + body, err := h.Storage.Get(r.Context(), *car.PhotoS3Key) + if err != nil { + writeError(w, http.StatusNotFound, "photo not found") + return + } + defer body.Close() + w.Header().Set("Content-Type", contentTypeForExtension(*car.PhotoS3Key)) + io.Copy(w, body) +} + +// PublicServiceEntries returns one page of service history, including +// attachments — read-only, no edit/delete affordance on this surface. +func (h *Handlers) PublicServiceEntries(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadCarByShareToken(w, r) + if !ok { + return + } + limit, offset := parsePagination(r) + + var entries []models.ServiceEntry + err := h.dbSelect(r.Context(), &entries, ` + SELECT * FROM service_entries WHERE car_id = ? + ORDER BY entry_date DESC, created_at DESC + LIMIT ? OFFSET ? + `, car.ID, limit+1, offset) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to list service entries") + return + } + + entries, hasMore := paginate(limit, entries) + writeJSON(w, http.StatusOK, page[ServiceEntryWithFiles]{ + Items: h.attachFiles(r, entries), + HasMore: hasMore, + }) +} + +// PublicFile streams a service-entry attachment, verified to belong to a +// car reachable via this exact share token (not just "any file the caller +// asks for"). +func (h *Handlers) PublicFile(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadCarByShareToken(w, r) + if !ok { + return + } + fileID := r.PathValue("fileId") + + var file models.ServiceEntryFile + err := h.dbGet(r.Context(), &file, ` + SELECT sef.* + FROM service_entry_files sef + JOIN service_entries se ON se.id = sef.service_entry_id + WHERE sef.id = ? AND se.car_id = ? + `, fileID, car.ID) + if errors.Is(err, sql.ErrNoRows) { + writeError(w, http.StatusNotFound, "file not found") + return + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to load file") + return + } + + body, err := h.Storage.Get(r.Context(), file.S3Key) + if err != nil { + writeError(w, http.StatusNotFound, "file not found in storage") + return + } + defer body.Close() + w.Header().Set("Content-Type", file.ContentType) + io.Copy(w, body) +} diff --git a/backend/internal/handlers/reminder_view.go b/backend/internal/handlers/reminder_view.go new file mode 100644 index 0000000..128cf10 --- /dev/null +++ b/backend/internal/handlers/reminder_view.go @@ -0,0 +1,153 @@ +package handlers + +import ( + "context" + "sort" + "time" + + "vlog/internal/models" +) + +// reminderWindowDays is how far ahead items are surfaced as "upcoming" +// (overdue items always show regardless of age). +const reminderWindowDays = 30 + +func today() time.Time { + now := time.Now().UTC() + return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC) +} + +// statusFor computes overdue/upcoming/future for a due date and/or due +// odometer against today and the car's current odometer reading. Either +// dueDate or dueOdometer (or both) may be nil. +func statusFor(dueDate *time.Time, dueOdometer, currentOdometer *int, today time.Time) string { + overdue, upcoming := false, false + if dueDate != nil { + if dueDate.Before(today) { + overdue = true + } else if !dueDate.After(today.AddDate(0, 0, reminderWindowDays)) { + upcoming = true + } + } + if dueOdometer != nil && currentOdometer != nil { + if *currentOdometer >= *dueOdometer { + overdue = true + } else if *dueOdometer-*currentOdometer <= 1000 { + upcoming = true + } + } + if overdue { + return "overdue" + } + if upcoming { + return "upcoming" + } + return "future" +} + +// reminderToView converts a stored Reminder row into the unified view shape. +func reminderToView(r models.Reminder, carRego string, currentOdometer *int, todayDate time.Time) models.ReminderView { + status := "done" + if r.CompletedAt == nil { + status = statusFor(r.DueDate, r.DueOdometer, currentOdometer, todayDate) + } + id := r.ID + return models.ReminderView{ + ID: &id, CarID: r.CarID, CarRego: carRego, ReminderType: r.ReminderType, + Label: r.Label, DueDate: r.DueDate, DueOdometer: r.DueOdometer, + Notes: r.Notes, CompletedAt: r.CompletedAt, Status: status, + } +} + +// synthesizedReminders returns the rego/WoF/next-service-due items derived +// from a car's own fields — never stored, always computed fresh, so there's +// nothing to keep in sync when the car (or its service history) changes. +// ID is left nil, which is how the frontend knows these aren't editable +// directly — change the car's rego/WoF/service-interval fields instead. +func synthesizedReminders(ctx context.Context, h *Handlers, car *models.Car, todayDate time.Time) []models.ReminderView { + var views []models.ReminderView + + if car.RegoExpiry != nil { + views = append(views, models.ReminderView{ + CarID: car.ID, CarRego: car.Rego, ReminderType: "rego", + DueDate: car.RegoExpiry, Status: statusFor(car.RegoExpiry, nil, nil, todayDate), + }) + } + if car.WofExpiry != nil { + views = append(views, models.ReminderView{ + CarID: car.ID, CarRego: car.Rego, ReminderType: "wof", + DueDate: car.WofExpiry, Status: statusFor(car.WofExpiry, nil, nil, todayDate), + }) + } + + if car.ServiceIntervalKM != nil || car.ServiceIntervalMonths != nil { + var last models.ServiceEntry + err := h.dbGet(ctx, &last, ` + SELECT * FROM service_entries + WHERE car_id = ? AND is_service = ? + ORDER BY entry_date DESC, created_at DESC + LIMIT 1 + `, car.ID, true) + if err == nil { + var dueDate *time.Time + if car.ServiceIntervalMonths != nil { + d := last.EntryDate.AddDate(0, *car.ServiceIntervalMonths, 0) + dueDate = &d + } + var dueOdometer *int + if car.ServiceIntervalKM != nil && last.Odometer != nil { + o := *last.Odometer + *car.ServiceIntervalKM + dueOdometer = &o + } + if dueDate != nil || dueOdometer != nil { + views = append(views, models.ReminderView{ + CarID: car.ID, CarRego: car.Rego, ReminderType: "service", + DueDate: dueDate, DueOdometer: dueOdometer, + Status: statusFor(dueDate, dueOdometer, car.Odometer, todayDate), + }) + } + } + } + + return views +} + +// sortReminderViews orders overdue-first, then by due date (nulls last), +// then by due odometer (nulls last), with completed items always last. +func sortReminderViews(views []models.ReminderView) { + rank := func(v models.ReminderView) int { + switch v.Status { + case "overdue": + return 0 + case "upcoming": + return 1 + case "future": + return 2 + default: // "done" + return 3 + } + } + sort.SliceStable(views, func(i, j int) bool { + a, b := views[i], views[j] + if ra, rb := rank(a), rank(b); ra != rb { + return ra < rb + } + switch { + case a.DueDate == nil && b.DueDate != nil: + return false + case a.DueDate != nil && b.DueDate == nil: + return true + case a.DueDate != nil && b.DueDate != nil && !a.DueDate.Equal(*b.DueDate): + return a.DueDate.Before(*b.DueDate) + } + switch { + case a.DueOdometer == nil && b.DueOdometer != nil: + return false + case a.DueOdometer != nil && b.DueOdometer == nil: + return true + case a.DueOdometer != nil && b.DueOdometer != nil: + return *a.DueOdometer < *b.DueOdometer + } + return false + }) +} diff --git a/backend/internal/handlers/reminders.go b/backend/internal/handlers/reminders.go new file mode 100644 index 0000000..7b78e68 --- /dev/null +++ b/backend/internal/handlers/reminders.go @@ -0,0 +1,210 @@ +package handlers + +import ( + "database/sql" + "encoding/json" + "errors" + "net/http" + + "github.com/google/uuid" + + "vlog/internal/auth" + "vlog/internal/models" +) + +var validReminderTypes = map[string]bool{ + "service": true, + "wheel_rotation": true, + "alignment": true, + "custom": true, +} + +// ListReminders returns a car's reminders — real ones (service/custom/etc, +// completed ones hidden unless ?completed=1) plus rego/WoF/next-service-due +// synthesized from the car's own fields, all in one unified list. +func (h *Handlers) ListReminders(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + includeCompleted := r.URL.Query().Get("completed") == "1" + todayDate := today() + + query := `SELECT * FROM reminders WHERE car_id = ?` + if !includeCompleted { + query += ` AND completed_at IS NULL` + } + var reminders []models.Reminder + if err := h.dbSelect(r.Context(), &reminders, query, car.ID); err != nil { + writeError(w, http.StatusInternalServerError, "failed to list reminders") + return + } + + views := make([]models.ReminderView, 0, len(reminders)) + for _, rem := range reminders { + views = append(views, reminderToView(rem, car.Rego, car.Odometer, todayDate)) + } + views = append(views, synthesizedReminders(r.Context(), h, car, todayDate)...) + sortReminderViews(views) + + writeJSON(w, http.StatusOK, views) +} + +// CreateReminder adds a reminder to a car — either a built-in type (service, +// wheel_rotation, alignment) or a fully custom one with its own label. +func (h *Handlers) CreateReminder(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + + in, ok := h.decodeReminderInput(w, r) + if !ok { + return + } + + dueDate, err := parseOptionalDate(in.DueDate) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid dueDate") + return + } + + var reminder models.Reminder + err = h.dbGet(r.Context(), &reminder, ` + INSERT INTO reminders (id, car_id, reminder_type, label, due_date, due_odometer, notes) + VALUES (?, ?, ?, ?, ?, ?, ?) + RETURNING * + `, uuid.New().String(), car.ID, in.ReminderType, in.Label, dueDate, in.DueOdometer, in.Notes) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to create reminder") + return + } + + writeJSON(w, http.StatusCreated, reminder) +} + +// UpdateReminder edits a reminder's fields, or marks/unmarks it complete +// (send completed: true/false in the body). +func (h *Handlers) UpdateReminder(w http.ResponseWriter, r *http.Request) { + reminder, ok := h.loadOwnedReminder(w, r) + if !ok { + return + } + + var body struct { + models.ReminderInput + Completed *bool `json:"completed"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return + } + + // Marking complete/incomplete is a lightweight partial update that + // doesn't require the other fields to be present. + if body.Completed != nil && body.ReminderType == "" { + var updated models.Reminder + var err error + if *body.Completed { + err = h.dbGet(r.Context(), &updated, ` + UPDATE reminders SET completed_at = CURRENT_TIMESTAMP WHERE id = ? RETURNING * + `, reminder.ID) + } else { + err = h.dbGet(r.Context(), &updated, ` + UPDATE reminders SET completed_at = NULL WHERE id = ? RETURNING * + `, reminder.ID) + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to update reminder") + return + } + writeJSON(w, http.StatusOK, updated) + return + } + + if !validateReminderFields(w, body.ReminderInput) { + return + } + dueDate, err := parseOptionalDate(body.DueDate) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid dueDate") + return + } + + var updated models.Reminder + err = h.dbGet(r.Context(), &updated, ` + UPDATE reminders + SET reminder_type = ?, label = ?, due_date = ?, due_odometer = ?, notes = ? + WHERE id = ? + RETURNING * + `, body.ReminderType, body.Label, dueDate, body.DueOdometer, body.Notes, reminder.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to update reminder") + return + } + + writeJSON(w, http.StatusOK, updated) +} + +// DeleteReminder removes a reminder. +func (h *Handlers) DeleteReminder(w http.ResponseWriter, r *http.Request) { + reminder, ok := h.loadOwnedReminder(w, r) + if !ok { + return + } + if _, err := h.dbExec(r.Context(), `DELETE FROM reminders WHERE id = ?`, reminder.ID); err != nil { + writeError(w, http.StatusInternalServerError, "failed to delete reminder") + return + } + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func (h *Handlers) decodeReminderInput(w http.ResponseWriter, r *http.Request) (models.ReminderInput, bool) { + var in models.ReminderInput + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return in, false + } + if !validateReminderFields(w, in) { + return in, false + } + return in, true +} + +func validateReminderFields(w http.ResponseWriter, in models.ReminderInput) bool { + if !validReminderTypes[in.ReminderType] { + writeError(w, http.StatusBadRequest, "reminderType must be one of service, wheel_rotation, alignment, custom") + return false + } + if in.ReminderType == "custom" && (in.Label == nil || *in.Label == "") { + writeError(w, http.StatusBadRequest, "label is required for custom reminders") + return false + } + if (in.DueDate == nil || *in.DueDate == "") && in.DueOdometer == nil { + writeError(w, http.StatusBadRequest, "either dueDate or dueOdometer is required") + return false + } + return true +} + +func (h *Handlers) loadOwnedReminder(w http.ResponseWriter, r *http.Request) (*models.Reminder, bool) { + userID, _ := auth.UserIDFromContext(r.Context()) + reminderID := r.PathValue("reminderId") + + var reminder models.Reminder + err := h.dbGet(r.Context(), &reminder, ` + SELECT rm.* + FROM reminders rm + JOIN cars c ON c.id = rm.car_id + WHERE rm.id = ? AND c.user_id = ? + `, reminderID, userID) + if errors.Is(err, sql.ErrNoRows) { + writeError(w, http.StatusNotFound, "reminder not found") + return nil, false + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to load reminder") + return nil, false + } + return &reminder, true +} diff --git a/backend/internal/handlers/service_entries.go b/backend/internal/handlers/service_entries.go new file mode 100644 index 0000000..42a29a7 --- /dev/null +++ b/backend/internal/handlers/service_entries.go @@ -0,0 +1,267 @@ +package handlers + +import ( + "database/sql" + "encoding/json" + "errors" + "fmt" + "net/http" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + + "vlog/internal/auth" + "vlog/internal/models" + "vlog/internal/storage" +) + +// ServiceEntryWithFiles is the shape returned to the frontend: an entry plus +// its attachments, so the timeline can render everything in one fetch. +type ServiceEntryWithFiles struct { + models.ServiceEntry + Files []models.ServiceEntryFile `json:"files"` +} + +// ListServiceEntries returns one page of a car's service history, newest +// first — the "timeline" is just this list rendered chronologically, +// nothing fancier. Paginated (?limit=&offset=) so a long history doesn't +// mean dumping thousands of rows into a single response/DOM. +func (h *Handlers) ListServiceEntries(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + limit, offset := parsePagination(r) + + var entries []models.ServiceEntry + err := h.dbSelect(r.Context(), &entries, ` + SELECT * FROM service_entries WHERE car_id = ? + ORDER BY entry_date DESC, created_at DESC + LIMIT ? OFFSET ? + `, car.ID, limit+1, offset) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to list service entries") + return + } + + entries, hasMore := paginate(limit, entries) + writeJSON(w, http.StatusOK, page[ServiceEntryWithFiles]{ + Items: h.attachFiles(r, entries), + HasMore: hasMore, + }) +} + +// attachFiles batches a single query for all files belonging to entries, +// rather than one query per entry. +func (h *Handlers) attachFiles(r *http.Request, entries []models.ServiceEntry) []ServiceEntryWithFiles { + result := make([]ServiceEntryWithFiles, len(entries)) + ids := make([]string, len(entries)) + for i, e := range entries { + result[i] = ServiceEntryWithFiles{ServiceEntry: e, Files: []models.ServiceEntryFile{}} + ids[i] = e.ID + } + if len(ids) == 0 { + return result + } + + // sqlx.In expands the slice into the right number of "?" placeholders; + // Rebind then adapts those for whichever driver is actually connected. + query, args, err := sqlx.In(`SELECT * FROM service_entry_files WHERE service_entry_id IN (?) ORDER BY created_at`, ids) + if err != nil { + return result // best-effort: entries without file metadata beats a 500 + } + + var files []models.ServiceEntryFile + if err := h.dbSelect(r.Context(), &files, query, args...); err != nil { + return result + } + + byEntry := make(map[string][]models.ServiceEntryFile, len(ids)) + for _, f := range files { + byEntry[f.ServiceEntryID] = append(byEntry[f.ServiceEntryID], f) + } + for i := range result { + if fs, ok := byEntry[result[i].ID]; ok { + result[i].Files = fs + } + } + return result +} + +// CreateServiceEntry adds a new history entry to a car. +func (h *Handlers) CreateServiceEntry(w http.ResponseWriter, r *http.Request) { + car, ok := h.loadOwnedCar(w, r) + if !ok { + return + } + + var in models.ServiceEntryInput + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return + } + if in.EntryType == "" { + writeError(w, http.StatusBadRequest, "entryType is required") + return + } + entryDate, err := time.Parse(dateLayout, in.EntryDate) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid entryDate") + return + } + + var entry models.ServiceEntry + err = h.dbGet(r.Context(), &entry, ` + INSERT INTO service_entries (id, car_id, entry_date, entry_type, description, performed_at, odometer, is_service) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + RETURNING * + `, uuid.New().String(), car.ID, entryDate, in.EntryType, in.Description, in.PerformedAt, in.Odometer, in.IsService) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to create service entry") + return + } + + writeJSON(w, http.StatusCreated, ServiceEntryWithFiles{ServiceEntry: entry, Files: []models.ServiceEntryFile{}}) +} + +// GetServiceEntry returns one entry with its attachments. +func (h *Handlers) GetServiceEntry(w http.ResponseWriter, r *http.Request) { + entry, ok := h.loadOwnedServiceEntry(w, r) + if !ok { + return + } + result := h.attachFiles(r, []models.ServiceEntry{*entry}) + writeJSON(w, http.StatusOK, result[0]) +} + +// UpdateServiceEntry edits an entry's fields. +func (h *Handlers) UpdateServiceEntry(w http.ResponseWriter, r *http.Request) { + entry, ok := h.loadOwnedServiceEntry(w, r) + if !ok { + return + } + + var in models.ServiceEntryInput + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return + } + if in.EntryType == "" { + writeError(w, http.StatusBadRequest, "entryType is required") + return + } + entryDate, err := time.Parse(dateLayout, in.EntryDate) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid entryDate") + return + } + + var updated models.ServiceEntry + err = h.dbGet(r.Context(), &updated, ` + UPDATE service_entries + SET entry_date = ?, entry_type = ?, description = ?, performed_at = ?, odometer = ?, is_service = ? + WHERE id = ? + RETURNING * + `, entryDate, in.EntryType, in.Description, in.PerformedAt, in.Odometer, in.IsService, entry.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to update service entry") + return + } + + result := h.attachFiles(r, []models.ServiceEntry{updated}) + writeJSON(w, http.StatusOK, result[0]) +} + +// DeleteServiceEntry removes an entry (DB cascades to its files; storage +// cleanup of each attached file is best-effort). +func (h *Handlers) DeleteServiceEntry(w http.ResponseWriter, r *http.Request) { + entry, ok := h.loadOwnedServiceEntry(w, r) + if !ok { + return + } + + var files []models.ServiceEntryFile + _ = h.dbSelect(r.Context(), &files, `SELECT * FROM service_entry_files WHERE service_entry_id = ?`, entry.ID) + + if _, err := h.dbExec(r.Context(), `DELETE FROM service_entries WHERE id = ?`, entry.ID); err != nil { + writeError(w, http.StatusInternalServerError, "failed to delete service entry") + return + } + + for _, f := range files { + _ = h.Storage.Delete(r.Context(), f.S3Key) + } + + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +// UploadServiceEntryFile attaches one PNG/PDF file to an entry. Call once +// per file for multi-file uploads. +func (h *Handlers) UploadServiceEntryFile(w http.ResponseWriter, r *http.Request) { + entry, ok := h.loadOwnedServiceEntry(w, r) + if !ok { + return + } + + file, contentType, ok := parseUploadedFile(w, r, 15<<20, storage.AllowedAttachmentTypes) + if !ok { + return + } + defer file.Close() + + _, header, _ := r.FormFile("file") + originalName := "attachment" + if header != nil { + originalName = sanitizeFileName(header.Filename) + } + + userID, _ := auth.UserIDFromContext(r.Context()) + key := fmt.Sprintf("users/%s/cars/%s/service/%s/%s-%s", + userID, entry.CarID, entry.ID, randomID(), originalName) + + var sizeBytes int64 + if header != nil { + sizeBytes = header.Size + } + + if err := h.Storage.Upload(r.Context(), key, contentType, file); err != nil { + writeError(w, http.StatusInternalServerError, "failed to upload file") + return + } + + var saved models.ServiceEntryFile + err := h.dbGet(r.Context(), &saved, ` + INSERT INTO service_entry_files (id, service_entry_id, s3_key, file_name, content_type, size_bytes) + VALUES (?, ?, ?, ?, ?, ?) + RETURNING * + `, uuid.New().String(), entry.ID, key, originalName, contentType, sizeBytes) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to save file reference") + return + } + + writeJSON(w, http.StatusCreated, saved) +} + +func (h *Handlers) loadOwnedServiceEntry(w http.ResponseWriter, r *http.Request) (*models.ServiceEntry, bool) { + userID, _ := auth.UserIDFromContext(r.Context()) + entryID := r.PathValue("entryId") + + var entry models.ServiceEntry + err := h.dbGet(r.Context(), &entry, ` + SELECT se.* + FROM service_entries se + JOIN cars c ON c.id = se.car_id + WHERE se.id = ? AND c.user_id = ? + `, entryID, userID) + if errors.Is(err, sql.ErrNoRows) { + writeError(w, http.StatusNotFound, "service entry not found") + return nil, false + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to load service entry") + return nil, false + } + return &entry, true +} diff --git a/backend/internal/models/models.go b/backend/internal/models/models.go new file mode 100644 index 0000000..5d19815 --- /dev/null +++ b/backend/internal/models/models.go @@ -0,0 +1,160 @@ +// Package models holds the plain structs shared between the db layer and +// the HTTP handlers. Field tags do double duty: `db` for sqlx scanning, +// `json` for API responses. +package models + +import "time" + +type User struct { + ID string `db:"id" json:"id"` + OIDCSub string `db:"oidc_sub" json:"-"` + Email string `db:"email" json:"email"` + Name *string `db:"name" json:"name"` + CreatedAt time.Time `db:"created_at" json:"createdAt"` +} + +type Car struct { + ID string `db:"id" json:"id"` + UserID string `db:"user_id" json:"userId"` + Rego string `db:"rego" json:"rego"` + Make *string `db:"make" json:"make"` + Model *string `db:"model" json:"model"` + Year *int `db:"year" json:"year"` + Color *string `db:"color" json:"color"` + Odometer *int `db:"odometer" json:"odometer"` + RegoExpiry *time.Time `db:"rego_expiry" json:"regoExpiry"` + WofExpiry *time.Time `db:"wof_expiry" json:"wofExpiry"` + PhotoS3Key *string `db:"photo_s3_key" json:"-"` + HasPhoto bool `db:"-" json:"hasPhoto"` + ShareToken *string `db:"share_token" json:"shareToken"` + ServiceIntervalKM *int `db:"service_interval_km" json:"serviceIntervalKm"` + ServiceIntervalMonths *int `db:"service_interval_months" json:"serviceIntervalMonths"` + CreatedAt time.Time `db:"created_at" json:"createdAt"` + UpdatedAt time.Time `db:"updated_at" json:"updatedAt"` +} + +// CarInput is the JSON body accepted for car create/update requests. Share +// links are managed separately (POST/DELETE .../share) since they're not +// really "car info" the way these fields are. +type CarInput struct { + Rego string `json:"rego"` + Make *string `json:"make"` + Model *string `json:"model"` + Year *int `json:"year"` + Color *string `json:"color"` + Odometer *int `json:"odometer"` + RegoExpiry *string `json:"regoExpiry"` // "YYYY-MM-DD" or null + WofExpiry *string `json:"wofExpiry"` + ServiceIntervalKM *int `json:"serviceIntervalKm"` + ServiceIntervalMonths *int `json:"serviceIntervalMonths"` +} + +type ServiceEntry struct { + ID string `db:"id" json:"id"` + CarID string `db:"car_id" json:"carId"` + EntryDate time.Time `db:"entry_date" json:"entryDate"` + EntryType string `db:"entry_type" json:"entryType"` + Description *string `db:"description" json:"description"` + PerformedAt *string `db:"performed_at" json:"performedAt"` + Odometer *int `db:"odometer" json:"odometer"` + // IsService marks this entry as "a full service" — the baseline the + // synthesized next-service-due reminder counts forward from, using the + // car's configured ServiceIntervalKM/ServiceIntervalMonths. + IsService bool `db:"is_service" json:"isService"` + CreatedAt time.Time `db:"created_at" json:"createdAt"` +} + +type ServiceEntryInput struct { + EntryDate string `json:"entryDate"` + EntryType string `json:"entryType"` + Description *string `json:"description"` + PerformedAt *string `json:"performedAt"` + Odometer *int `json:"odometer"` + IsService bool `json:"isService"` +} + +type ServiceEntryFile struct { + ID string `db:"id" json:"id"` + ServiceEntryID string `db:"service_entry_id" json:"serviceEntryId"` + S3Key string `db:"s3_key" json:"-"` + FileName string `db:"file_name" json:"fileName"` + ContentType string `db:"content_type" json:"contentType"` + SizeBytes int64 `db:"size_bytes" json:"sizeBytes"` + CreatedAt time.Time `db:"created_at" json:"createdAt"` +} + +type Reminder struct { + ID string `db:"id" json:"id"` + CarID string `db:"car_id" json:"carId"` + ReminderType string `db:"reminder_type" json:"reminderType"` + Label *string `db:"label" json:"label"` + DueDate *time.Time `db:"due_date" json:"dueDate"` + DueOdometer *int `db:"due_odometer" json:"dueOdometer"` + Notes *string `db:"notes" json:"notes"` + CompletedAt *time.Time `db:"completed_at" json:"completedAt"` + CreatedAt time.Time `db:"created_at" json:"createdAt"` +} + +type ReminderInput struct { + ReminderType string `json:"reminderType"` + Label *string `json:"label"` + DueDate *string `json:"dueDate"` + DueOdometer *int `json:"dueOdometer"` + Notes *string `json:"notes"` +} + +type KnowledgeEntry struct { + ID string `db:"id" json:"id"` + CarID string `db:"car_id" json:"carId"` + Title string `db:"title" json:"title"` + Body string `db:"body" json:"body"` + CreatedAt time.Time `db:"created_at" json:"createdAt"` + UpdatedAt time.Time `db:"updated_at" json:"updatedAt"` +} + +type KnowledgeEntryInput struct { + Title string `json:"title"` + Body string `json:"body"` +} + +// ReminderView is the unified shape for every "reminder-like" row shown to +// the user — real stored Reminder rows, plus rego/WoF expiry and next- +// service-due items synthesized on the fly from the car's own fields (no +// separate stored row to keep in sync). ID is nil for synthesized items, +// which is how the frontend knows there's nothing to edit/delete/complete — +// to change those, edit the car's rego/WoF/service-interval fields instead. +// Used by both GET /api/dashboard (across all cars) and the car-scoped +// GET /api/cars/{id}/reminders. +type ReminderView struct { + ID *string `db:"id" json:"id"` + CarID string `db:"car_id" json:"carId"` + CarRego string `db:"car_rego" json:"carRego"` + ReminderType string `db:"reminder_type" json:"reminderType"` // 'service' | 'wheel_rotation' | 'alignment' | 'custom' | 'rego' | 'wof' + Label *string `db:"label" json:"label"` + DueDate *time.Time `db:"due_date" json:"dueDate"` + DueOdometer *int `db:"due_odometer" json:"dueOdometer"` + Notes *string `db:"notes" json:"notes"` + CompletedAt *time.Time `db:"completed_at" json:"completedAt"` + Status string `db:"status" json:"status"` // 'overdue' | 'upcoming' | 'future' | 'done' +} + +type FuelEntry struct { + ID string `db:"id" json:"id"` + CarID string `db:"car_id" json:"carId"` + EntryDate time.Time `db:"entry_date" json:"entryDate"` + Litres float64 `db:"litres" json:"litres"` + Cost float64 `db:"cost" json:"cost"` + Odometer *int `db:"odometer" json:"odometer"` + Location *string `db:"location" json:"location"` + Notes *string `db:"notes" json:"notes"` + CreatedAt time.Time `db:"created_at" json:"createdAt"` +} + +type FuelEntryInput struct { + EntryDate string `json:"entryDate"` + Litres float64 `json:"litres"` + Cost float64 `json:"cost"` + Odometer *int `json:"odometer"` + Location *string `json:"location"` + Notes *string `json:"notes"` +} diff --git a/backend/internal/storage/local.go b/backend/internal/storage/local.go new file mode 100644 index 0000000..468ab02 --- /dev/null +++ b/backend/internal/storage/local.go @@ -0,0 +1,78 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" +) + +// LocalStorage writes uploads to a directory on disk instead of S3 — for +// STORAGE_DRIVER=local, so the app can be tested without a real S3 bucket. +// Keys are the same "users/{id}/cars/{id}/..." paths used for S3; they're +// just joined onto basePath instead of being S3 object keys. +type LocalStorage struct { + basePath string +} + +func NewLocal(basePath string) (*LocalStorage, error) { + if err := os.MkdirAll(basePath, 0o755); err != nil { + return nil, fmt.Errorf("create local storage dir: %w", err) + } + return &LocalStorage{basePath: basePath}, nil +} + +func (l *LocalStorage) Upload(ctx context.Context, key, contentType string, r io.Reader) error { + path, err := l.resolve(key) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return fmt.Errorf("create dir for %s: %w", key, err) + } + f, err := os.Create(path) + if err != nil { + return fmt.Errorf("create %s: %w", key, err) + } + defer f.Close() + if _, err := io.Copy(f, r); err != nil { + return fmt.Errorf("write %s: %w", key, err) + } + return nil +} + +func (l *LocalStorage) Get(ctx context.Context, key string) (io.ReadCloser, error) { + path, err := l.resolve(key) + if err != nil { + return nil, err + } + f, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("open %s: %w", key, err) + } + return f, nil +} + +func (l *LocalStorage) Delete(ctx context.Context, key string) error { + path, err := l.resolve(key) + if err != nil { + return err + } + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("delete %s: %w", key, err) + } + return nil +} + +// resolve joins key onto basePath, rejecting anything that would escape it. +// Keys are always built internally from UUIDs + sanitized filenames, so +// this is defense in depth rather than a load-bearing check. +func (l *LocalStorage) resolve(key string) (string, error) { + if strings.Contains(key, "..") { + return "", fmt.Errorf("invalid storage key %q", key) + } + return filepath.Join(l.basePath, filepath.FromSlash(key)), nil +} diff --git a/backend/internal/storage/s3.go b/backend/internal/storage/s3.go new file mode 100644 index 0000000..a39ae93 --- /dev/null +++ b/backend/internal/storage/s3.go @@ -0,0 +1,118 @@ +// Package storage wraps S3 upload/download/delete plus the content-type +// sniffing used to validate uploaded photos and PNG/PDF attachments. The +// bucket is treated as fully private — everything is proxied through the Go +// backend, so there are no presigned URLs or bucket CORS rules to manage. +package storage + +import ( + "context" + "fmt" + "io" + "mime/multipart" + "net/http" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/feature/s3/manager" + "github.com/aws/aws-sdk-go-v2/service/s3" +) + +// Storage is what handlers depend on — satisfied by S3Storage (production) +// and LocalStorage (STORAGE_DRIVER=local, for testing without a real S3 +// bucket). Handlers never need to know which one they're talking to. +type Storage interface { + Upload(ctx context.Context, key, contentType string, r io.Reader) error + Get(ctx context.Context, key string) (io.ReadCloser, error) + Delete(ctx context.Context, key string) error +} + +type S3Storage struct { + client *s3.Client + bucket string +} + +func NewS3(ctx context.Context, region, bucket string) (*S3Storage, error) { + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region)) + if err != nil { + return nil, fmt.Errorf("load aws config: %w", err) + } + return &S3Storage{ + client: s3.NewFromConfig(cfg), + bucket: bucket, + }, nil +} + +// Upload streams r to S3 under key with the given content type. Uses the +// managed uploader so large files aren't buffered fully in memory. +func (s *S3Storage) Upload(ctx context.Context, key, contentType string, r io.Reader) error { + uploader := manager.NewUploader(s.client) + _, err := uploader.Upload(ctx, &s3.PutObjectInput{ + Bucket: aws.String(s.bucket), + Key: aws.String(key), + Body: r, + ContentType: aws.String(contentType), + }) + if err != nil { + return fmt.Errorf("upload %s: %w", key, err) + } + return nil +} + +// Get returns a stream of the object's body. Caller must Close it. +func (s *S3Storage) Get(ctx context.Context, key string) (io.ReadCloser, error) { + out, err := s.client.GetObject(ctx, &s3.GetObjectInput{ + Bucket: aws.String(s.bucket), + Key: aws.String(key), + }) + if err != nil { + return nil, fmt.Errorf("get %s: %w", key, err) + } + return out.Body, nil +} + +// Delete removes the object. Callers should treat failures as non-fatal +// (log and move on) since the DB row is the source of truth. +func (s *S3Storage) Delete(ctx context.Context, key string) error { + _, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{ + Bucket: aws.String(s.bucket), + Key: aws.String(key), + }) + if err != nil { + return fmt.Errorf("delete %s: %w", key, err) + } + return nil +} + +// DetectAndValidate sniffs the real content type of an uploaded file from +// its first bytes (never trusts the client-declared type/extension) and +// checks it against the allowed set. Returns the sniffed content type, or an +// error if it's not in allowed. The file's read position is reset to the +// start afterwards so it can still be uploaded. +func DetectAndValidate(file multipart.File, allowed map[string]bool) (string, error) { + buf := make([]byte, 512) + n, err := file.Read(buf) + if err != nil && err != io.EOF { + return "", fmt.Errorf("read file header: %w", err) + } + contentType := http.DetectContentType(buf[:n]) + + if _, err := file.Seek(0, io.SeekStart); err != nil { + return "", fmt.Errorf("reset file position: %w", err) + } + + if !allowed[contentType] { + return "", fmt.Errorf("unsupported file type %q", contentType) + } + return contentType, nil +} + +var ( + AllowedPhotoTypes = map[string]bool{ + "image/png": true, + "image/jpeg": true, + } + AllowedAttachmentTypes = map[string]bool{ + "image/png": true, + "application/pdf": true, + } +) diff --git a/backend/migrations/migrations.go b/backend/migrations/migrations.go new file mode 100644 index 0000000..ed143b5 --- /dev/null +++ b/backend/migrations/migrations.go @@ -0,0 +1,16 @@ +// Package migrations embeds the DB schema for both supported drivers so the +// server can apply it on startup with no separate migrate step. +// +// Postgres uses versioned golang-migrate .sql files (PostgresFS). SQLite +// uses one idempotent schema file applied directly (SQLiteSchemaSQL) — it's +// a local dev/testing convenience DB, not something that needs migration +// history. +package migrations + +import "embed" + +//go:embed postgres/*.sql +var PostgresFS embed.FS + +//go:embed sqlite/schema.sql +var SQLiteSchemaSQL string diff --git a/backend/migrations/postgres/0001_init.down.sql b/backend/migrations/postgres/0001_init.down.sql new file mode 100644 index 0000000..063f865 --- /dev/null +++ b/backend/migrations/postgres/0001_init.down.sql @@ -0,0 +1,5 @@ +DROP TABLE IF EXISTS reminders; +DROP TABLE IF EXISTS service_entry_files; +DROP TABLE IF EXISTS service_entries; +DROP TABLE IF EXISTS cars; +DROP TABLE IF EXISTS users; diff --git a/backend/migrations/postgres/0001_init.up.sql b/backend/migrations/postgres/0001_init.up.sql new file mode 100644 index 0000000..c0c881e --- /dev/null +++ b/backend/migrations/postgres/0001_init.up.sql @@ -0,0 +1,68 @@ +-- IDs are generated in Go (uuid.New()) rather than via a DB default, so the +-- same INSERT statements work unchanged against SQLite too — no pgcrypto +-- extension needed. + +CREATE TABLE users ( + id UUID PRIMARY KEY, + oidc_sub TEXT NOT NULL UNIQUE, + email TEXT NOT NULL, + name TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE cars ( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + rego TEXT NOT NULL, + make TEXT, + model TEXT, + year INT, + color TEXT, + odometer INT, + rego_expiry DATE, + wof_expiry DATE, + photo_s3_key TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (user_id, rego) +); +CREATE INDEX idx_cars_user_id ON cars(user_id); + +CREATE TABLE service_entries ( + id UUID PRIMARY KEY, + car_id UUID NOT NULL REFERENCES cars(id) ON DELETE CASCADE, + entry_date DATE NOT NULL, + entry_type TEXT NOT NULL, + description TEXT, + performed_at TEXT, + odometer INT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX idx_service_entries_car_id ON service_entries(car_id); +CREATE INDEX idx_service_entries_date ON service_entries(entry_date); + +CREATE TABLE service_entry_files ( + id UUID PRIMARY KEY, + service_entry_id UUID NOT NULL REFERENCES service_entries(id) ON DELETE CASCADE, + s3_key TEXT NOT NULL, + file_name TEXT NOT NULL, + content_type TEXT NOT NULL, + size_bytes BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX idx_service_entry_files_entry_id ON service_entry_files(service_entry_id); + +CREATE TABLE reminders ( + id UUID PRIMARY KEY, + car_id UUID NOT NULL REFERENCES cars(id) ON DELETE CASCADE, + reminder_type TEXT NOT NULL, + label TEXT, + due_date DATE, + due_odometer INT, + notes TEXT, + completed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (due_date IS NOT NULL OR due_odometer IS NOT NULL) +); +CREATE INDEX idx_reminders_car_id ON reminders(car_id); +CREATE INDEX idx_reminders_due_date ON reminders(due_date) WHERE completed_at IS NULL; diff --git a/backend/migrations/postgres/0002_knowledge.down.sql b/backend/migrations/postgres/0002_knowledge.down.sql new file mode 100644 index 0000000..65dc928 --- /dev/null +++ b/backend/migrations/postgres/0002_knowledge.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS knowledge_entries; diff --git a/backend/migrations/postgres/0002_knowledge.up.sql b/backend/migrations/postgres/0002_knowledge.up.sql new file mode 100644 index 0000000..11312a9 --- /dev/null +++ b/backend/migrations/postgres/0002_knowledge.up.sql @@ -0,0 +1,9 @@ +CREATE TABLE knowledge_entries ( + id UUID PRIMARY KEY, + car_id UUID NOT NULL REFERENCES cars(id) ON DELETE CASCADE, + title TEXT NOT NULL, + body TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX idx_knowledge_entries_car_id ON knowledge_entries(car_id); diff --git a/backend/migrations/postgres/0003_sharing_fuel_and_reminders.down.sql b/backend/migrations/postgres/0003_sharing_fuel_and_reminders.down.sql new file mode 100644 index 0000000..e557875 --- /dev/null +++ b/backend/migrations/postgres/0003_sharing_fuel_and_reminders.down.sql @@ -0,0 +1,5 @@ +DROP TABLE IF EXISTS fuel_entries; +ALTER TABLE cars DROP COLUMN IF EXISTS share_token; +ALTER TABLE cars DROP COLUMN IF EXISTS service_interval_km; +ALTER TABLE cars DROP COLUMN IF EXISTS service_interval_months; +ALTER TABLE service_entries DROP COLUMN IF EXISTS is_service; diff --git a/backend/migrations/postgres/0003_sharing_fuel_and_reminders.up.sql b/backend/migrations/postgres/0003_sharing_fuel_and_reminders.up.sql new file mode 100644 index 0000000..6f44b35 --- /dev/null +++ b/backend/migrations/postgres/0003_sharing_fuel_and_reminders.up.sql @@ -0,0 +1,28 @@ +-- Nullable, unique when set: NULL means sharing is off for that car. A +-- random opaque token (not the car's own id) so a share link can't be +-- guessed and doesn't leak the car's real UUID. +ALTER TABLE cars ADD COLUMN share_token TEXT UNIQUE; + +-- Either/both may be set; whichever comes first triggers the synthesized +-- "service due" reminder (computed from the most recent is_service entry). +ALTER TABLE cars ADD COLUMN service_interval_km INT; +ALTER TABLE cars ADD COLUMN service_interval_months INT; + +-- Marks a service_entries row as "this was a full service" — i.e. the +-- baseline the next service-due reminder counts forward from. Most entries +-- (oil top-up, tyre rotation, etc.) won't set this. +ALTER TABLE service_entries ADD COLUMN is_service BOOLEAN NOT NULL DEFAULT false; + +CREATE TABLE fuel_entries ( + id UUID PRIMARY KEY, + car_id UUID NOT NULL REFERENCES cars(id) ON DELETE CASCADE, + entry_date DATE NOT NULL, + litres DOUBLE PRECISION NOT NULL, + cost DOUBLE PRECISION NOT NULL, + odometer INT, + location TEXT, + notes TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX idx_fuel_entries_car_id ON fuel_entries(car_id); +CREATE INDEX idx_fuel_entries_date ON fuel_entries(entry_date); diff --git a/backend/migrations/sqlite/schema.sql b/backend/migrations/sqlite/schema.sql new file mode 100644 index 0000000..ebcd977 --- /dev/null +++ b/backend/migrations/sqlite/schema.sql @@ -0,0 +1,110 @@ +-- Applied idempotently (CREATE ... IF NOT EXISTS) on every startup rather +-- than through golang-migrate — this is a local dev/testing convenience DB, +-- not something that needs versioned migration history. For production, use +-- Postgres (DB_DRIVER=postgres) and the versioned migrations/postgres/ set. +-- +-- Column types matter here beyond documentation: modernc.org/sqlite only +-- auto-converts to/from Go's time.Time when a column's declared type +-- contains DATE/DATETIME/TIMESTAMP (plain TEXT would come back as a string +-- and fail to scan), and only auto-converts to/from Go's bool when the +-- declared type is BOOLEAN — both verified empirically, not assumed. +-- +-- NOTE: "IF NOT EXISTS" means new columns added to an existing table +-- definition here do NOT retroactively appear in an already-created local +-- .db file — CREATE TABLE IF NOT EXISTS is a no-op once the table exists. +-- db.go's ensureSQLiteColumns() handles that: it ALTER TABLE ADD COLUMNs +-- anything new (see internal/db/sqlite_migrate.go), so an existing local +-- .db file picks up schema growth automatically — no need to delete it. + +CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + oidc_sub TEXT NOT NULL UNIQUE, + email TEXT NOT NULL, + name TEXT, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS cars ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + rego TEXT NOT NULL, + make TEXT, + model TEXT, + year INTEGER, + color TEXT, + odometer INTEGER, + rego_expiry DATE, + wof_expiry DATE, + photo_s3_key TEXT, + share_token TEXT UNIQUE, + service_interval_km INTEGER, + service_interval_months INTEGER, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (user_id, rego) +); +CREATE INDEX IF NOT EXISTS idx_cars_user_id ON cars(user_id); + +CREATE TABLE IF NOT EXISTS service_entries ( + id TEXT PRIMARY KEY, + car_id TEXT NOT NULL REFERENCES cars(id) ON DELETE CASCADE, + entry_date DATE NOT NULL, + entry_type TEXT NOT NULL, + description TEXT, + performed_at TEXT, + odometer INTEGER, + is_service BOOLEAN NOT NULL DEFAULT 0, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_service_entries_car_id ON service_entries(car_id); +CREATE INDEX IF NOT EXISTS idx_service_entries_date ON service_entries(entry_date); + +CREATE TABLE IF NOT EXISTS service_entry_files ( + id TEXT PRIMARY KEY, + service_entry_id TEXT NOT NULL REFERENCES service_entries(id) ON DELETE CASCADE, + s3_key TEXT NOT NULL, + file_name TEXT NOT NULL, + content_type TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_service_entry_files_entry_id ON service_entry_files(service_entry_id); + +CREATE TABLE IF NOT EXISTS reminders ( + id TEXT PRIMARY KEY, + car_id TEXT NOT NULL REFERENCES cars(id) ON DELETE CASCADE, + reminder_type TEXT NOT NULL, + label TEXT, + due_date DATE, + due_odometer INTEGER, + notes TEXT, + completed_at DATETIME, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (due_date IS NOT NULL OR due_odometer IS NOT NULL) +); +CREATE INDEX IF NOT EXISTS idx_reminders_car_id ON reminders(car_id); +CREATE INDEX IF NOT EXISTS idx_reminders_due_date ON reminders(due_date) WHERE completed_at IS NULL; + +CREATE TABLE IF NOT EXISTS knowledge_entries ( + id TEXT PRIMARY KEY, + car_id TEXT NOT NULL REFERENCES cars(id) ON DELETE CASCADE, + title TEXT NOT NULL, + body TEXT NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_knowledge_entries_car_id ON knowledge_entries(car_id); + +CREATE TABLE IF NOT EXISTS fuel_entries ( + id TEXT PRIMARY KEY, + car_id TEXT NOT NULL REFERENCES cars(id) ON DELETE CASCADE, + entry_date DATE NOT NULL, + litres REAL NOT NULL, + cost REAL NOT NULL, + odometer INTEGER, + location TEXT, + notes TEXT, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_fuel_entries_car_id ON fuel_entries(car_id); +CREATE INDEX IF NOT EXISTS idx_fuel_entries_date ON fuel_entries(entry_date);