1import{r as e,j as t}from"./react-core-DL6E4rCD.js";import{u as n,U as a}from"./useOverlay-BYb9mGO9.js";import{b as s,c as r,L as i}from"./router-D2UMI1Us.js";import{E as o}from"./EmptyState-D_EYmjvO.js";import{P as l}from"./pdfTheme-BYbI-8W4.js";import{B as c}from"./BillingShell-DOpaaevE.js";import{B as d}from"./BillingWorkspaceNav-DrmC492X.js";import{c as u,I as p,s as m,l as x}from"./InterventionPdf-BYwf4ePb.js";import{D as h,a as f,b as g,d as b,c as v,e as j,s as _,P as y}from"./sendTracking-I4uzmddZ.js";import{p as N,u as w}from"./pdfShare-B7ZrtyOF.js";import{f as k,r as C}from"./emailTemplates-Dpf1lRkK.js";import{p as S}from"./documentSync-CP0yElTp.js";import{S as q}from"./SignaturePad-BnImx-GE.js";import{B as z}from"./button-CRXB9dWi.js";import{I as A}from"./input-CUknIeaV.js";import{L as R}from"./label-DgU0LYLz.js";import{T as $}from"./textarea-UB8vXcNb.js";import{D as P,a as T,b as D,c as L}from"./dropdown-menu-DwNmAjNC.js";import{S as B,a as E,b as I,c as F,d as O}from"./sheet-DZ1I0kZ-.js";import{h as M,f as V,g as U,a as K,c as W}from"./billing-CEClf2Q4.js";import{b as Q}from"./billingShare-DGakhCyc.js";import{y as J,z as H,A as G,B as Z,l as X,C as Y,k as ee,D as te}from"./billingActions-vwrWPQND.js";import{s as ne,c as ae}from"./main-CgSL9a_g.js";import{F as se,_ as re,aI as ie,$ as oe,aa as le,aJ as ce,a9 as de,a3 as ue,p as pe,n as me,ap as xe,aA as he,a2 as fe,ae as ge,an as be,ar as ve,J as je,w as _e,X as ye,aK as Ne,A as we}from"./icons-DX6s9CRQ.js";import{l as ke,a as Ce,b as Se,M as qe,q as ze}from"./MobileAnnualFollowUp-DFHkRUF8.js";import{l as Ae}from"./billingSettings-CE9hfMGS.js";import{r as Re,t as $e,n as Pe}from"./reportTemplates-By1DzeGY.js";import{d as Te}from"./agenda-SbVcdxrv.js";import{P as De,C as Le,a as Be,c as Ee,l as Ie,i as Fe,S as Oe,v as Me,r as Ve,s as Ue,b as Ke,A as We,d as Qe,E as Je,p as He,e as Ge,g as Ze,h as Xe,f as Ye,j as et}from"./reportTemplates-C7t3bq9g.js";import{p as tt,P as nt,S as at,a as st,r as rt,b as it,c as ot,d as lt,F as ct,n as dt,e as ut,A as pt}from"./AddressAutocomplete-pwDflrs5.js";import{P as mt}from"./SubServiceChips-_p7qHg_p.js";import{refreshCompanyData as xt,loadActiveClients as ht,loadDocuments as ft,loadInterventions as gt}from"./companyData-ztMOAWAc.js";import{f as bt,g as vt}from"./ClientEquipmentPanel-D5il8jHR.js";import{t as jt}from"./today-C-V2_UhU.js";import{B as _t}from"./BillingMoreFilters-BH7UAck4.js";import{d as yt,m as Nt}from"./interventionFilters-GJvZdC_T.js";import{s as wt,k as kt}from"./offlinePhotos-D-lWgKZn.js";import"./index-DUEh1MDD.js";import"./supabase-BcDZgFaI.js";import"./browser-BQw80PQ2.js";import"./index-BI1WapHf.js";import"./popover-VKtKf899.js";import"./radix-CC_5lH4a.js";import"./InstallAppHint-BWA6OoeH.js";import"./proAppInstall-CdiguXM-.js";import"./contracts-CJdXSgBS.js";import"./index-Czjg5zhY.js";import"./ui-utils-fzKV8Oe-.js";import"./browser-DVa0ZLbF.js";import"./dataCache-DwNFnin6.js";import"./query-DIX-EoJg.js";import"./switch-lLafDC4m.js";import"./use-toast-CpGB7dqh.js";import"./equipmentTypes-Bgw72TUX.js";const Ct=e=>new Intl.NumberFormat("fr-BE",{style:"currency",currency:"EUR"}).format(e/100);function St({quoteId:n,hasLines:a,onUseLines:s}){const[r,i]=e.useState(null);if(e.useEffect(()=>{let e=!0;if(i(null),n)return ne.rpc("app_quote_balance",{_quote_id:n}).then(({data:t})=>{e&&i(t??null)}),()=>{e=!1}},[n]),!n||!r)return null;const o=Number(r.total_incl_cents??0),l=Number(r.deposit_paid_cents??0)+Number(r.final_paid_cents??0),c=Number(r.remaining_cents??0),d=o>0&&c<=0;return t.jsxs("div",{className:"space-y-2 rounded-2xl border border-primary/30 bg-primary/5 p-3 sm:col-span-2",children:[t.jsxs("p",{className:"flex items-center gap-2 text-sm font-semibold",children:[t.jsx(se,{className:"h-4 w-4 text-primary"}),"Devis ",r.number??"",r.title?` â ${r.title}`:""]}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-xs text-muted-foreground",children:"Prix du devis"}),t.jsx("p",{className:"font-semibold",children:Ct(o)})]}),t.jsxs("div",{children:[t.jsx("p",{className:"text-xs text-muted-foreground",children:"Déjà payé"}),t.jsx("p",{className:"font-semibold",children:l>0?Ct(l):"Rien"})]}),t.jsxs("div",{children:[t.jsx("p",{className:"text-xs text-muted-foreground",children:"Reste à payer"}),t.jsx("p",{className:d?"font-semibold text-primary":"font-semibold",children:d?"Soldé":Ct(c)})]})]}),d?t.jsxs("p",{className:"flex items-center gap-1 text-xs font-semibold text-primary",children:[t.jsx(re,{className:"h-3.5 w-3.5"}),"Solde fait : rien à encaisser chez le client."]}):l>0?t.jsxs("p",{className:"text-xs text-muted-foreground",children:["Acompte reçu : encaissez seulement ",Ct(c),"."]}):t.jsx("p",{className:"text-xs text-muted-foreground",children:"Aucun paiement reçu : le montant total reste à encaisser."}),!a&&t.jsxs(z,{type:"button",variant:"outline",className:"w-full",onClick:()=>{(async()=>{const{data:e}=await ne.from("app_document_lines").select("description, quantity, unit, unit_price_cents, vat_rate, discount_percent").eq("document_id",n).order("position"),t=e??[];t.length&&s(t.map(e=>({...e,unit:e.unit??"pièce",discount_percent:e.discount_percent??0})))})()},children:[t.jsx(ie,{className:"h-4 w-4"}),"Reprendre les prestations du devis"]})]})}function qt({lines:n,onChange:a,catalog:s,defaultVatRate:r=6}
1){const i=M(n),[o,l]=e.useState(null),[c,d]=e.useState(""),[u,p]=e.useState("service"),m=s.filter(e=>"product"===e.kind),x=s.filter(e=>"product"!==e.kind),h=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""),f=e.useMemo(()=>{const e="product"===u?m:x,t=h(c.trim());return(t?e.filter(e=>h(e.label).includes(t)):e).slice(0,40)},[s,u,c]),g=(e,t)=>a(n.map((n,a)=>a===e?{...n,...t}:n));return t.jsxs("div",{className:"space-y-4 sm:col-span-2 border border-border bg-card p-3 shadow-sm sm:p-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-accent",children:"Prix du rapport"}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"Ajoutez vos prestations : elles alimentent la facture brouillon après signature."})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[t.jsx(z,{type:"button",variant:"service"===u?"default":"outline",className:"h-11",onClick:()=>p("service"),children:"Prestations"}),t.jsx(z,{type:"button",variant:"product"===u?"default":"outline",className:"h-11",onClick:()=>p("product"),children:"Produits"})]}),t.jsxs("div",{className:"relative",children:[t.jsx(oe,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),t.jsx(A,{value:c,onChange:e=>d(e.target.value),placeholder:"product"===u?"Rechercher un produitâ¦":"Rechercher une prestationâ¦",className:"h-12 pl-9","aria-label":"product"===u?"Rechercher un produit":"Rechercher une prestation"})]}),t.jsx("div",{className:"max-h-56 space-y-1 overflow-y-auto rounded-md border border-border bg-background p-1",children:0===f.length?t.jsx("p",{className:"px-1 py-2 text-xs text-muted-foreground",children:"product"===u?"Aucun produit ne correspond.":"Aucune prestation ne correspond."}):f.map(e=>t.jsxs("button",{type:"button",onClick:()=>{(e=>{const t=s.find(t=>t.id===e);t&&a([...n,{description:t.label,quantity:1,unit:t.unit,unit_price_cents:t.unit_price_cents,vat_rate:Number(t.vat_rate),discount_percent:0}])})(e.id),d("")},className:"flex w-full items-center justify-between gap-2 rounded-sm border border-border bg-card px-3 py-3 text-left text-sm active:bg-secondary",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:e.label}),t.jsxs("span",{className:"shrink-0 text-xs font-semibold text-muted-foreground",children:[V(Math.round(e.unit_price_cents*(1+Number(e.vat_rate)/100)))," TVAC"]}),t.jsx(le,{className:"size-4 shrink-0 text-accent"})]},e.id))}),t.jsxs(z,{type:"button",variant:"outline",className:"h-11 w-full",onClick:()=>a([...n,{description:"",quantity:1,unit:"pièce",unit_price_cents:0,vat_rate:r,discount_percent:0}]),children:[t.jsx(le,{className:"mr-2 size-4"})," Article libre"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"Prix du catalogue affichés TVA comprise, au taux enregistré pour chaque prestation. Vous pouvez tout modifier ensuite."})]}),0===n.length?t.jsx("p",{className:"text-xs text-muted-foreground",children:"Aucun poste pour lâinstant."}):t.jsxs("div",{className:"space-y-2",children:[n.map((e,s)=>{const r=M([e]),i=o===s;return t.jsxs("div",{className:"rounded-md border border-border bg-background shadow-sm",children:[t.jsxs("div",{className:"flex items-start gap-2 p-3",children:[t.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[t.jsx(A,{value:e.description,onChange:e=>g(s,{description:e.target.value}),placeholder:"Description de la prestation",className:"h-11 border-0 border-b border-border px-0 text-sm focus-visible:ring-0"}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsxs("div",{className:"flex items-center rounded-md border border-border bg-card",children:[t.jsx(z,{type:"button",variant:"ghost",size:"icon",className:"size-9","aria-label":"Diminuer la quantité",onClick:()=>g(s,{quantity:Math.max(0,Number((e.quantity-1).toFixed(2)))}),children:t.jsx(ce,{className:"size-3.5"})}),t.jsx("input",{type:"number",inputMode:"decimal",value:e.quantity,onChange:e=>g(s,{quantity:Number(e.target.value)||0}),className:"h-9 w-12 bg-transparent text-center text-sm outline-none","aria-label":"Quantité"}),t.jsx(z,{type:"button",variant:"ghost",size:"icon",className:"size-9","aria-label":"Augmenter la quantité",onClick:()=>g(s,{quantity:Number((e.quantity+1).toFixed(2))}),children:t.jsx(le,{className:"size-3.5"})})]}),t.jsxs("div",{className:"flex items-center gap-1 rounded-md border border-border bg-card px-2",children:[t.jsx("input",{type:"number",inputMode:"decimal",step:"0.01",value:Number((e.unit_price_cents*(1-e.discount_percent/100)*(1+e.vat_rate/100)/100).toFixed(2)),onChange:t=>g(s,{unit_price_cents:e.discount_percent>=100?e.unit_price_cents:Math.round(100*(Number(t.target.value)||0)/((1-e.discount_percent/100)*(1+e.vat_rate/100)))}),disabled:e.discount_percent>=100,className:"h-9 w-20 bg-transparent text-right text-sm outline-none","aria-label":"Prix TVA comprise"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"⬠TVAC"})]}),t.jsx("span",{className:"ml-auto text-sm font-semibold",children:V(r.incl)})]})]}),t.jsx(z,{type:"button",variant:"ghost",size:"icon",className:"size-9","aria-label":"Supprimer le poste",onClick:()=>a(n.filter((e,t)=>
1t!==s)),children:t.jsx(de,{className:"size-4"})})]}),t.jsxs("button",{type:"button",onClick:()=>l(i?null:s),className:"flex w-full items-center justify-between border-t border-border px-3 py-2 text-xs text-muted-foreground",children:[t.jsxs("span",{children:[e.unit," · TVA ",e.vat_rate,"%",e.discount_percent?` · -${e.discount_percent}%`:""]}),t.jsx(ue,{className:"size-4 transition-transform "+(i?"rotate-180":"")})]}),i&&t.jsxs("div",{className:"grid grid-cols-3 gap-2 border-t border-border p-3",children:[t.jsx(zt,{label:"Unité",children:t.jsx(A,{value:e.unit,onChange:e=>g(s,{unit:e.target.value}),className:"h-11"})}),t.jsx(zt,{label:"TVA %",children:t.jsxs("select",{value:String(e.vat_rate),onChange:e=>g(s,{vat_rate:Number(e.target.value)}),className:"h-11 w-full border border-input bg-background px-2 text-sm",children:[t.jsx("option",{value:"21",children:"21 %"}),t.jsx("option",{value:"6",children:"6 %"}),t.jsx("option",{value:"0",children:"0 %"})]})}),t.jsx(zt,{label:"Remise %",children:t.jsx(A,{type:"number",inputMode:"decimal",value:e.discount_percent,onChange:e=>g(s,{discount_percent:Number(e.target.value)||0}),className:"h-11"})})]})]},s)}),t.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border bg-background px-3 py-2 text-sm shadow-sm",children:[t.jsxs("span",{className:"text-xs text-muted-foreground",children:["HTVA ",V(i.excl)," · TVA ",V(i.vat)]}),t.jsx("strong",{children:V(i.incl)})]})]})]})}function zt({label:e,children:n}){return t.jsxs("div",{className:"space-y-1",children:[t.jsx(R,{className:"text-[11px] text-muted-foreground",children:e}),n]})}const At=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g," ").trim();function Rt(e,t){const n=At(t??"");if(!n)return null;const a=e.find(e=>At(e.serviceType)===n);return a||(e.find(e=>{const t=At(e.serviceType);return Boolean(t)&&(n.includes(t)||t.includes(n))})??null)}function $t(e){return e?6:21}const Pt=["details","technical","validation","signature"],Tt={details:"Arrivée",technical:"Rapport",validation:"Paiement",review:"Relecture",signature:"Signature"};function Dt(e){return Tt[e]}function Lt(e){const t=Pt.indexOf("review"===e?"signature":e);return t<0?0:t}function Bt(e){return"technical"===e?"Passer au paiement":"validation"===e?"Faire signer":"signature"===e?"Valider le rapport":"Continuer"}function Et(e,t){if("details"===e)return t.companyLoaded?t.clientId?"":"Choisissez le client avant de continuer.":"Les données de lâentreprise ne sont pas encore chargées. Fermez puis rouvrez le rapport.";if("technical"===e){if(!t.workDone.trim())return"Indiquez le travail réalisé.";const e=t.fields.find(e=>e.required&&!String(t.templateData[e.key]??"").trim());return e?`Complétez le champ obligatoire « ${e.label} ».`:""}if("validation"===e)return t.visitDone?"":"Indiquez si le rendez-vous a été effectué.";if("signature"===e){if(!1===t.requireSignature)return"";if(!t.clientSignature)return"Faites signer le client dans la zone de signature."}return""}const It=/^(ok$|effectué|conforme|bon tirage|aucune anomalie|appareil nettoyé et en bon|appareil entretenu et en bon)/i;function Ft(e){const t={};for(const n of e){const e=n.options?.[0];"select"===n.type&&e&&It.test(e.trim())&&(t[n.key]=e)}return t}function Ot({id:e,label:n,options:a,value:s,onChange:r,required:i,invalid:o}){const l=a.length>0&&a.length<=4&&a.every(e=>e.length<=26);return t.jsxs("div",{className:"min-w-0 space-y-2",children:[t.jsxs(R,{htmlFor:e,className:ae(o&&"text-destructive"),children:[n,i?" *":""]}),l?t.jsx("div",{id:e,role:"radiogroup","aria-label":n,className:"grid gap-2 sm:grid-cols-2",children:a.map(e=>{const n=s===e;return t.jsx("button",{type:"button",role:"radio","aria-checked":n,onClick:()=>r(n?"":e),className:ae("min-h-12 w-full break-words rounded-md border px-3 py-2 text-left text-sm transition",n?"border-primary bg-primary font-semibold text-primary-foreground shadow-sm":"border-input bg-card text-foreground active:bg-secondary",o&&!n&&"border-destructive/60"),children:e},e)})}):t.jsxs("select",{id:e,value:s,onChange:e=>r(e.target.value),className:ae("flex h-12 w-full max-w-full rounded-md border border-input bg-card px-3 text-base shadow-sm sm:h-10 sm:text-sm",o&&"border-destructive"),children:[t.jsx("option",{value:"",children:"â"}),a.map(e=>t.jsx("option",{value:e,children:e},e))]})]})}function Mt({reportId:e,selected:n,invalid:a,onToggle:s,planned:r=[],onReset:i}){const o=r.length>0&&(r.length!==n.length||r.some(e=>!n.includes(e))),l=tt(e),c=[...nt].sort((e,t)=>
1Number(t.key===l)-Number(e.key===l));return t.jsxs("div",{"data-report-field":"sub_services",className:ae("min-w-0 space-y-3 rounded-2xl border p-4",a?"border-destructive":"border-border bg-secondary/30"),children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-accent",children:"Sous-services réalisés *"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Cochez tout ce qui a été fait : le rapport ajoute les contrôles utiles."}),r.length>0&&t.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[t.jsxs("span",{className:"rounded-full bg-accent/15 px-2.5 py-1 text-xs font-semibold text-accent",children:["Prévu au rendez-vous : ",r.length]}),o&&i&&t.jsx("button",{type:"button",onClick:i,className:"min-h-11 text-xs font-semibold text-accent underline underline-offset-2",children:"Revenir à la sélection du rendez-vous"})]})]}),c.map(e=>{const a=at.filter(t=>t.pole===e.key).sort((e,t)=>Number(r.includes(t.key))-Number(r.includes(e.key))),i=a.filter(e=>n.includes(e.key)).length,o=t.jsx("div",{className:"flex min-w-0 flex-wrap gap-2",children:a.map(e=>{const a=n.includes(e.key);return t.jsxs("button",{type:"button","aria-pressed":a,onClick:()=>s(e.key),className:ae(r.includes(e.key)&&!a&&"border-dashed border-accent/60","inline-flex min-h-11 max-w-full items-center gap-1.5 rounded-full border px-3 py-2 text-left text-sm transition-colors",a?"border-accent bg-accent text-accent-foreground":"border-border bg-background text-foreground hover:border-accent/60"),children:[a&&t.jsx(pe,{className:"h-4 w-4 shrink-0"}),t.jsx("span",{className:"min-w-0 break-words",children:e.label})]},e.key)})});return e.key===l?t.jsxs("div",{className:"space-y-2",children:[t.jsx("p",{className:"text-sm font-semibold",children:e.label}),o]},e.key):t.jsxs("details",{open:i>0,className:"space-y-2",children:[t.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-muted-foreground",children:["Ajouter : ",e.label,i?` (${i})`:""]}),t.jsx("div",{className:"pt-2",children:o})]},e.key)}),a&&!n.length&&t.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"Cochez au moins un sous-service."})]})}function Vt({open:n,onOpenChange:a,currentTemplateId:s,planned:r,otherTemplates:i,onChoose:o}){const[l,c]=e.useState([]);e.useEffect(()=>{n&&c([])},[n]);const d=l[0]?st(l[0]):null;return t.jsx(h,{open:n,onOpenChange:a,children:t.jsxs(f,{className:"max-h-[90dvh] max-w-lg overflow-y-auto rounded-2xl",children:[t.jsxs(g,{children:[t.jsx(b,{children:"Quâavez-vous réellement fait ?"}),t.jsxs(v,{children:["Cochez le travail réel. Le bon rapport sâouvre ; client, adresse, photos et paiement sont gardés.",r.length>0&&" Les prestations prévues non faites ne seront pas dans ce rapport."]})]}),t.jsxs("div",{className:"space-y-4",children:[nt.map(e=>t.jsxs("div",{className:"space-y-2",children:[t.jsxs("p",{className:"flex items-center gap-2 text-sm font-semibold",children:[t.jsx("span",{className:ae("h-2 w-2 rounded-full",mt[e.key]),"aria-hidden":!0}),e.label]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:at.filter(t=>t.pole===e.key).map(e=>{const n=l.includes(e.key);return t.jsxs("button",{type:"button","aria-pressed":n,onClick:()=>{return t=e.key,c(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t]);var t},className:ae("inline-flex min-h-11 items-center gap-1.5 rounded-full border px-3 py-2 text-left text-sm transition-colors",n?"border-accent bg-accent text-accent-foreground":"border-border bg-background hover:border-accent/60",r.includes(e.key)&&!n&&"border-dashed"),children:[n&&t.jsx(pe,{className:"h-4 w-4"}),e.label,r.includes(e.key)&&t.jsx("span",{className:"text-[10px] opacity-70",children:"prévu"})]},e.key)})})]},e.key)),i.length>0&&t.jsxs("details",{className:"rounded-2xl border border-border p-3",children:[t.jsx("summary",{className:"cursor-pointer text-sm font-medium text-muted-foreground",children:"Autres modèles de rapport"}),t.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:i.map(e=>t.jsx(z,{type:"button",variant:e.id===s?"secondary":"outline",size:"sm",className:"h-10 rounded-full",onClick:()=>o({templateId:e.id,subServices:[]}),children:e.label},e.id))})]})]}),t.jsx("div",{className:"sticky bottom-0 -mx-6 -mb-6 border-t border-border bg-background p-4",children:t.jsx(z,{type:"button",className:"h-12 w-full rounded-full",disabled:!d,onClick:()=>d&&o({templateId:rt(d.pole),subServices:l}),children:d?`Ouvrir le rapport ${nt.find(e=>e.key===d.pole).label}`:"Cochez au moins un travail"})})]})})}const Ut=(e,t)=>
1({label:e,target:"findings",text:t}),Kt=(e,t)=>({label:e,target:"work_done",text:t}),Wt=(e,t)=>({label:e,target:"recommendations",text:t}),Qt=Wt("Prochain passage dans 12 mois","Prochain entretien conseillé dans 12 mois."),Jt={entretien_gaz:[Kt("Entretien chaudière effectué","Entretien de la chaudière gaz : nettoyage du brûleur et de lâéchangeur, contrôle visuel des sécurités, essai de fonctionnement chauffage et eau chaude."),Ut("Chaudière en bon état","Chaudière en bon état apparent de fonctionnement au jour du passage."),Ut("Pression basse","Pression de lâinstallation basse, remise à niveau effectuée."),Qt],entretien_mazout:[Kt("Entretien mazout effectué","Entretien de la chaudière mazout : nettoyage du foyer et de lâéchangeur, remplacement du gicleur et du filtre si prévu, essai de fonctionnement."),Ut("Suie importante","Dépôt de suie important constaté dans le foyer, nettoyage effectué."),Qt],entretien_chauffe_eau_gaz:[Kt("Entretien chauffe-eau gaz effectué","Entretien du chauffe-eau gaz / convecteur : nettoyage du brûleur, contrôle visuel des sécurités, essai de fonctionnement."),Qt],depannage_chauffage:[Ut("Panne constatée","Panne constatée à lâarrivée : appareil à lâarrêt / en sécurité."),Ut("Code erreur relevé","Code erreur relevé sur lâappareil, voir champ « Code erreur affiché »."),Kt("Panne réparée","Recherche de panne effectuée, pièce défectueuse remplacée, remise en service et essai de fonctionnement conformes."),Kt("Remise en service","Réarmement et remise en service de lâappareil, fonctionnement vérifié."),Wt("Pièce à commander","Pièce à commander : un nouveau passage sera planifié dès réception.")],detartrage_chaudiere:[Kt("Détartrage effectué","Détartrage de lâéchangeur effectué, circuit rincé et remis en pression, essai de fonctionnement."),Wt("Adoucisseur conseillé","Eau calcaire : un adoucisseur est conseillé pour protéger lâappareil.")],remplacement_chaudiere:[Kt("Chaudière posée","Dépose de lâancien appareil, pose et raccordement du nouvel appareil, test dâétanchéité gaz, mise en service et explications au client.")],remplacement_radiateur:[Kt("Radiateur remplacé","Radiateur remplacé, raccords contrôlés, purge et remise en pression de lâinstallation.")],thermostat:[Kt("Thermostat posé","Thermostat installé et raccordé, essai de régulation conforme, programmation expliquée au client.")],vanne_thermostatique:[Kt("Vannes remplacées","Vannes thermostatiques remplacées, essai dâouverture et de fermeture conforme.")],plomberie_generale:[Kt("Réparation effectuée","Réparation de plomberie effectuée, contrôle dâétanchéité conforme.")],fuite_eau:[Ut("Fuite localisée","Fuite localisée et identifiée."),Kt("Fuite réparée","Fuite réparée, contrôle dâétanchéité conforme après remise en eau."),Wt("Surveiller lâhumidité","Surveiller lâassèchement de la zone touchée ; les dégâts antérieurs ne relèvent pas de lâintervention.")],entretien_boiler:[Kt("Entretien boiler effectué","Entretien du chauffe-eau électrique : vidange, détartrage de la cuve et de la résistance, contrôle de lâanode et du groupe de sécurité."),Qt],depannage_boiler:[Ut("Plus dâeau chaude","Plus dâeau chaude constatée à lâarrivée."),Kt("Boiler réparé","Recherche de panne effectuée, pièce défectueuse remplacée, retour de lâeau chaude vérifié.")],detartrage_eau_chaude:[Kt("Détartrage effectué","Détartrage du circuit dâeau chaude effectué, débit vérifié.")],robinetterie:[Kt("Robinet remplacé","Robinetterie remplacée / réparée, contrôle dâétanchéité conforme.")],salle_de_bain:[Kt("Sanitaire raccordé","Appareil sanitaire posé et raccordé, contrôle dâétanchéité et dâécoulement conforme.")],debouchage_canalisation:[Ut("Bouchon localisé","Obstruction localisée dans la canalisation."),Kt("Canalisation débouchée","Canalisation débouchée, écoulement contrôlé et rétabli en fin dâintervention."),Wt("Inspection caméra conseillée","Bouchons répétés : une inspection caméra est conseillée pour vérifier lâétat du réseau.")],debouchage_egout:[Kt("Ãgout débouché","Ãgout débouché par hydrocurage, écoulement rétabli et contrôlé."),Ut("Racines constatées","Présence de racines constatée dans le réseau.")],debouchage_toilette:[Kt
1("WC débouché","WC débouché, plusieurs chasses dâeau effectuées, écoulement normal.")],debouchage_evier:[Kt("Ãvier débouché","Ãvier débouché, siphon nettoyé, écoulement normal.")],travaux_egouttage:[Kt("Travaux dâégouttage","Travaux dâégouttage réalisés selon devis, écoulement contrôlé.")],inspection_egout_camera:[Kt("Inspection caméra effectuée","Inspection caméra du réseau effectuée, constats repris ci-dessous et sur les photos."),Wt("Travaux à prévoir","Défauts structurels constatés : travaux à prévoir sur devis.")],ramonage:[Kt("Ramonage effectué","Ramonage du conduit effectué sur toute sa longueur, conduit dégagé et contrôlé visuellement."),Ut("Conduit en bon état","Conduit en bon état apparent, aucune obstruction constatée."),Wt("Ramonage annuel","Ramonage à refaire au moins une fois par an.")],entretien_pellets:[Kt("Entretien poêle effectué","Entretien du poêle à pellets : nettoyage du foyer, du creuset, de lâéchangeur et du conduit, essai de fonctionnement."),Qt],debistrage_nids:[Kt("Débistrage effectué","Débistrage / retrait de nid effectué, conduit dégagé et contrôlé.")],tubage:[Kt("Tubage posé","Tubage posé et raccordé, fixations et sortie de toit contrôlées.")],chapeau:[Kt("Chapeau posé","Chapeau de cheminée posé et fixé.")],inspection_fumigene:[Kt("Test fumigène effectué","Inspection caméra et test fumigène du conduit effectués, constats repris ci-dessous.")]},Ht=[Ut("Installation conforme","Installation contrôlée visuellement, aucun défaut apparent constaté."),Ut("Accès impossible","Accès à lâappareil ou au conduit impossible le jour du passage."),Wt("Rien à signaler","Aucune recommandation particulière.")];function Gt(e){const t=it(e).flatMap(e=>Jt[e]??[]);return Array.from(new Map([...t,...Ht].map(e=>[e.text,e])).values())}const Zt={depannage_chauffage:[{label:"Chaudière en sécurité",text:"Chaudière en sécurité à lâarrivée."},{label:"Pas dâeau chaude",text:"Pas dâeau chaude sanitaire."},{label:"Pas de chauffage",text:"Pas de chauffage."},{label:"Pression basse / fuite",text:"Pression dâeau basse ou fuite sur lâinstallation."},{label:"Bruit anormal",text:"Bruit anormal de lâappareil."}],depannage_boiler:[{label:"Plus dâeau chaude",text:"Plus dâeau chaude."},{label:"Fuite",text:"Fuite constatée sur le chauffe-eau ou ses raccords."},{label:"Groupe de sécurité goutte",text:"Groupe de sécurité qui goutte en permanence."},{label:"Pression trop forte",text:"Pression dâeau trop forte sur le réseau."}]};function Xt(e){return it(e).flatMap(e=>Zt[e]??[])}function Yt(e,t){const n=e.split("\n").map(e=>e.trim()).filter(Boolean);return n.includes(t)?e:[...n,t].join("\n")}const en={replaced:"border-accent bg-accent text-accent-foreground",added:"border-success bg-success/15 text-success",missing:"border-destructive bg-destructive/10 text-destructive"};function tn({parts:n,status:a,onChange:s}){const[r,i]=e.useState(null),[o,l]=e.useState(""),c=Array.from(new Set([...n,...Object.keys(a)])),d=(e,t)=>{const n={...a};t?n[e]=t:delete n[e],s(n),i(null)},u=()=>{const e=o.trim();e&&(l(""),i(e),a[e]||s({...a,[e]:"replaced"}))};return t.jsxs("div",{className:"min-w-0 space-y-2",children:[t.jsx("div",{className:"flex flex-wrap gap-2",children:c.map(e=>{const n=a[e];return t.jsxs("button",{type:"button","aria-expanded":r===e,onClick:()=>i(r===e?null:e),className:ae("inline-flex min-h-10 items-center rounded-full border px-3 py-1.5 text-sm transition-colors",n?en[n]:"border-border bg-background hover:border-accent/60"),children:[e,n&&t.jsxs("span",{className:"ml-1 text-xs opacity-80",children:["· ","replaced"===n?"remplacée":"added"===n?"posée":"à prévoir"]})]},e)})}),r&&t.jsxs("div",{className:"flex flex-wrap gap-2 rounded-2xl border border-border bg-card p-2",role:"radiogroup","aria-label":r,children:[t.jsx("p",{className:"w-full px-1 text-xs font-semibold text-muted-foreground",children:r}),Object.keys(De).map(e=>t.jsx("button",{type:"button",role:"radio","aria-checked":a[r]===e,onClick:()=>d(r,e),className:ae("min-h-10 rounded-full border px-3 text-sm",a[r]===e?en[e]:"border-border bg-background"),children:De[e]},e)),a[r]&&t.jsx("button",{type:"button",onClick:()=>d(r,null),className:"min-h-10 px-3 text-sm text-muted-foreground underline",children:"Retirer"})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(A,{value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),u())},placeholder:"Autre pièceâ¦","aria-label":"Autre pièce",className:"h-11"}),t.jsxs("button",{type:"button",onClick:u,"aria-label":"Ajouter la pièce",className:"inline-flex h-11 shrink-0 items-center gap-1 rounded-xl border border-border px-3 text-sm font-semibold text-primary",children:[t.jsx(le,{className:"h-4 w-4"}),"Ajouter"]})]})]})}function nn({enabled:e,title:n,summary:a,open:s,onOpen:r,onNext:i,children:o}){return e?t.jsxs("section",{"data-report-section":"technical",className:ae("min-w-0 rounded-2xl border bg-card sm:col-span-2",s?"border-accent/50":"border-border"),children:[t.jsxs("button",{type:"button",onClick:r,"aria-expanded":s,className:"flex min-h-14 w-full items-center justify-between gap-3 px-4 text-left",children:[t.jsxs("span",{className:"min-w-0",children:[t.jsx("span",{className:"block text-sm font-semibold",children:n}),!s&&a&&t.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:a})]}),t.jsx(ue,{className:ae("h-4 w-4 shrink-0 text-muted-foreground transition-transform",s&&"rotate-180")}
1)]}),s&&t.jsxs("div",{className:"grid min-w-0 gap-4 px-4 pb-4 sm:grid-cols-2",children:[o,i&&t.jsx("button",{type:"button",onClick:i,className:"min-h-11 rounded-xl bg-primary px-4 text-sm font-semibold text-primary-foreground sm:col-span-2",children:"Suivant"})]})]}):t.jsx(t.Fragment,{children:o})}const an=e=>"Non conforme"===e?"bg-destructive/15 text-destructive":"Remplacé"===e?"bg-accent/15 text-accent":"Sans objet"===e?"bg-muted text-muted-foreground":"bg-success/15 text-success";function sn({checks:n,values:a,invalidKeys:s,onChange:r,onAdd:i}){const[o,l]=e.useState(null),[c,d]=e.useState(!1),u=Object.keys(Le).filter(e=>!n.includes(e));return t.jsxs("div",{className:"min-w-0 space-y-1.5",children:[t.jsx("ul",{className:"divide-y divide-border overflow-hidden rounded-2xl border border-border bg-card",children:n.map(e=>{const n=Ee(e),i=a[n]||"",c=o===n;return t.jsxs("li",{"data-report-field":n,className:ae(s?.has(n)&&"bg-destructive/5"),children:[t.jsxs("button",{type:"button",onClick:()=>l(c?null:n),"aria-expanded":c,className:"flex min-h-12 w-full items-center justify-between gap-3 px-3 text-left text-sm",children:[t.jsx("span",{className:"min-w-0",children:Le[e]}),t.jsx("span",{className:ae("shrink-0 rounded-full px-3 py-1 text-xs font-semibold",i?an(i):"bg-destructive/15 text-destructive"),children:i||"à choisir"})]}),c&&t.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-3",role:"radiogroup","aria-label":Le[e],children:Be.map(e=>t.jsx("button",{type:"button",role:"radio","aria-checked":i===e,onClick:()=>{r(n,e),l(null)},className:ae("min-h-10 rounded-full border px-3 text-sm",i===e?"border-accent bg-accent text-accent-foreground":"border-border bg-background"),children:e},e))})]},n)})}),c?t.jsx("div",{className:"flex flex-wrap gap-2 pt-1",children:u.map(e=>t.jsx("button",{type:"button",onClick:()=>{i(e),d(!1)},className:"min-h-10 rounded-full border border-dashed border-border px-3 text-sm hover:border-accent/60",children:Le[e]},e))}):t.jsxs("button",{type:"button",onClick:()=>d(!0),className:"inline-flex min-h-11 items-center gap-1 text-sm font-semibold text-primary",children:[t.jsx(le,{className:"h-4 w-4"}),"Ajouter un contrôle"]})]})}const rn=e=>String(e??"").trim(),on=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g," ").trim(),ln=/^(non conforme|fuite constat|d[ée]faut constat|dangereuse)/i,cn=({item:n,onClose:a,onDone:s})=>{const[r,i]=e.useState(""),[o,l]=e.useState(""),[c,d]=e.useState(""),[p,m]=e.useState(!0),[x,_]=e.useState(!1),[y,N]=e.useState("");e.useEffect(()=>{n&&(i(n.address_line1??""),l(n.postal_code??""),d(n.city??""),N(""))},[n]);const w=n?[n.address_line1,[n.postal_code,n.city].filter(Boolean).join(" ")].filter(Boolean).join(", "):"";return t.jsx(h,{open:Boolean(n),onOpenChange:e=>!e&&a(),children:t.jsxs(f,{children:[t.jsxs(g,{children:[t.jsxs(b,{children:["Corriger l'adresse du rapport ",n?.number??""]}),t.jsxs(v,{children:["Le rapport garde son numéro. L'ancienne adresse (",w||"â",") reste dans l'historique et le PDF est refait automatiquement."]})]}),t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx(R,{children:"Rue et numéro"}),t.jsx(A,{value:r,onChange:e=>i(e.target.value)})]}),t.jsxs("div",{className:"grid grid-cols-[110px_1fr] gap-2",children:[t.jsxs("div",{children:[t.jsx(R,{children:"Code postal"}),t.jsx(A,{value:o,onChange:e=>l(e.target.value),inputMode:"numeric"})]}),t.jsxs("div",{children:[t.jsx(R,{children:"Commune"}),t.jsx(A,{value:c,onChange:e=>d(e.target.value)})]})]}),t.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[t.jsx("input",{type:"checkbox",checked:p,onChange:e=>m(e.target.checked)}),"Enregistrer comme lieu d'intervention du client (prochains passages)"]}),y&&t.jsx("p",{className:"text-sm text-destructive",children:y})]}),t.jsxs(j,{children:[t.jsx(z,{variant:"outline",onClick:a,children:"Annuler"}),t.jsx(z,{onClick:()=>{(async()=>{if(!n)return;if(!r.trim()||!o.trim()||!c.trim())return N("Rue, code postal et commune sont nécessaires.");_(!0),N("");const{error:e}=await ne.from("app_interventions").update({address_line1:r.trim(),postal_code:o.trim(),city:c.trim(),address_corrected_at:(new Date).toISOString(),address_corrected_from:w||"â",pdf_url:null}).eq("id",n.id);if(e)return _(!1),N("Correction refusée : seul un administrateur peut rectifier un rapport validé.");if(p&&n.client_id&&n.company_id)try{const e=await u({company_id:n.company_id,client_id:n.client_id,label:"Lieu d'intervention",address_line1:r.trim(),postal_code:o.trim(),city:c.trim()});await ne.from("app_appointments").update({site_id:e.id}).eq("client_id",n.client_id).in("status",["planned","confirmed"]).is("site_id",null).eq("address_line1",n.address_line1??"")}catch{}_(!1),s(),a()})()},disabled:x,children:x?"Enregistrementâ¦":"Corriger le rapport"})]})]})})},dn={details:"Vérifiez le client et les prestations, puis continuez.",technical:"Les contrôles sont déjà c
1ochés « conforme » : changez seulement les anomalies.",validation:"Touchez le moyen de paiement utilisé, ou « Pas payé ».",review:"Relisez puis faites signer le client.",signature:"Relisez, faites signer le client, puis validez : le rapport part tout seul."};function un({step:e,onBack:n,title:a,onStepSelect:s,onChangeReport:r}){const i=Lt(e);return t.jsxs("div",{className:"-mx-4 -mt-4 min-w-0 space-y-3 border-b border-nav bg-nav px-4 pb-4 pt-3 text-nav-foreground sm:-mx-6 sm:-mt-6 sm:px-6",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[t.jsx(z,{type:"button",variant:"ghost",size:"icon",className:"size-10 shrink-0 text-nav-foreground hover:bg-nav-foreground/10 hover:text-nav-foreground",onClick:n,"aria-label":"Ãtape précédente",children:t.jsx(me,{className:"size-5"})}),t.jsx("p",{className:"min-w-0 flex-1 truncate font-heading text-base font-bold sm:text-lg",children:a??"Rapport dâintervention"}),r&&t.jsx(z,{type:"button",variant:"secondary",size:"sm",className:"h-9 shrink-0 rounded-full px-3 text-xs font-semibold",onClick:r,children:"Changer"})]}),t.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 pl-1",children:[t.jsxs("p",{className:"min-w-0 truncate text-xs font-semibold uppercase tracking-[0.14em] text-nav-foreground
1/85",children:["Ãtape ",i+1," sur ",Pt.length," · ",Dt(e)]}),t.jsxs("span",{className:"shrink-0 rounded-full bg-nav-foreground/10 px-2 py-0.5 text-xs text-nav-foreground/80",children:[i+1,"/",Pt.length]})]}),t.jsx("p",{className:"pl-1 text-xs text-nav-foreground/65",children:dn[e]}),t.jsx("div",{className:"grid gap-1",style:{gridTemplateColumns:`repeat(${Pt.length}, minmax(0, 1fr))`},children:Pt.map((e,n)=>{const a=n<i,r=n===i,o=n<=i&&Boolean(s);return t.jsx("button",{type:"button",disabled:!o,onClick:o?()=>s?.(e):void 0,"aria-label":`Ãtape ${n+1} : ${Dt(e)}`,"aria-current":r?"step":void 0,className:ae("flex h-6 items-center justify-center rounded-full text-[10px] font-semibold transition",r?"bg-primary text-primary-foreground":a?"bg-primary/25 text-nav-foreground":"bg-nav-foreground/10 text-nav-foreground/55"),children:a?t.jsx(pe,{className:"size-3"}):n+1},e)})})]})}const pn=["appliance_brand","appliance_model","appliance_capacity","appliance_orientation","appliance_kind","appliance_serial","appliance_power","appliance_type","burner_brand"],mn=["verdict","quote_outcome","next_control","follow_up_period"],xn={client_id:"",intervention_date:jt(),service_type:"",technician_name:"",address_line1:"",postal_code:"",city:"",findings:"",work_done:"",parts_used:"",duration_minutes:"",recommendations:"",occupant_name:"",occupant_phone:"",site_id:""};async function hn(e,t=()=>!0,n=4){let a,s;for(let i=0;i<n;i+=1){try{if(a=await e(),t(a))return a}catch(r){s=r}await new Promise(e=>setTimeout(e,1500*(i+1)))}if(void 0!==a)return a;throw s}function fn(){const[se,ie]=e.useState(),[ce,pe]=e.useState(null),[me,$e]=e.useState("draft"),[Pe,De]=e.useState([]),[Le,Be]=e.useState(!1),[Ee,tt]=e.useState([]),[nt,at]=e.useState({}),[mt,Ct]=e.useState(""),[zt,At]=e.useState(null),[Tt,Dt]=e.useState(""),[It,Ut]=s(),Kt=r(),[Wt,Qt]=e.useState(()=>"mobile"===new URLSearchParams(window.location.search).get("from")),[Jt,Ht]=e.useState("details"),[Zt,en]=e.useState(!1),an=e.useRef(null),[dn,fn]=e.useState(""),vn=e.useRef(!1),Nn=e.useRef(new Set),[wn,kn]=e.useState([]),[Cn,Sn]=e.useState([]),[qn,zn]=e.useState({}),[An,Rn]=e.useState([]),[$n,Pn]=e.useState(!1),[Tn,Dn]=e.useState(null),[Ln,Bn]=e.useState(null),[En,In]=e.useState(""),[Fn,On]=e.useState(xn),[Mn,Vn]=e.useState(null),[Un,Kn]=e.useState(!1);e.useEffect(()=>{Kn(!1),Vn(null)},[Fn.client_id,Fn.service_type]),e.useEffect(()=>{const e=Fn.client_id;if(!se||!e||"undefined"!=typeof navigator&&!navigator.onLine)return;let t=!1;return ke(se,e).then(e=>{t||Vn(Ce(e,Fn.service_type))}).catch(()=>{}),()=>{t=!0}},[se,Fn.client_id,Fn.service_type]);const[Wn,Qn]=e.useState(""),[Jn,Hn]=e.useState("general"),[Gn,Zn]=e.useState([]),[Xn,Yn]=e.useState(""),[ea,ta]=e.useState({}),[na,aa]=e.useState([]),[sa,ra]=e.useState([]),[ia,oa]=e.useState(!1),[la,ca]=e.useState(!1),[da,ua]=e.useState(!1),[pa,ma]=e.useState(!1),[xa,ha]=e.useState("controles"),fa=e.useRef({work_done:!1,findings:!1}),[ga,ba]=e.useState(()=>{const e=new URLSearchParams(window.location.search);return"mobile"===e.get("from")&&Boolean(e.get("appointment"))}),[va,ja]=e.useState(!1),[_a,ya]=e.useState(""),[Na,wa]=e.useState(""),[ka,Ca]=e.useState(!1),[Sa,qa]=e.useState({}),[za,Aa]=e.useState({}),[Ra,$a]=e.useState(null),[Pa,Ta]=e.useState(!0),[Da,La]=e.useState({}),[Ba,Ea]=e.useState(!1),[Ia,Fa]=e.useState(null),[Oa,Ma]=e.useState(""),[Va,Ua]=e.useState(!1),[Ka,Wa]=e.useState(!1),[Qa,Ja]=e.useState(""),[Ha,Ga]=e.useState(jt()),[Za,Xa]=e.useState(""),[Ya,es]=e.useState(""),[ts,ns]=e.useState(""),[as,ss]=e.useState(""),[rs,is]=e.useState(""),[os,ls]=e.useState(!0),[cs,ds]=e.useState(""),[us,ps]=e.useState(""),[ms,xs]=e.useState(null),[hs,fs]=e.useState(!1),[gs,bs]=e.useState(null),[vs,js]=e.useState(!1),[_s,ys]=e.useState([]),[Ns,ws]=e.useState(!1),[ks,Cs]=e.useState(""),[Ss,qs]=e.useState(null),[zs,As]=e.useState(null),[Rs,$s]=e.useState(""),[Ps,Ts]=e.useState(""),[Ds,Ls]=e.useState(""),[Bs,Es]=e.useState({}),[Is,Fs]=e.useState(""),[Os,Ms]=e.useState(""),[Vs,Us]=e.useState(""),[Ks,Ws]=e.useState(""),[Qs,Js]=e.useState(""),[Hs,Gs]=e.useState(""),[Zs,Xs]=e.useState(""),[Ys,er]=e.useState(!1),[tr,nr]=e.useState(50),ar=e.useRef(!0);e.useEffect(()=>{nr(50)},[Ds,Ps,Is,Bs,Os,Vs,Ks,Qs,Hs,Zs]),e.useEffect(()=>{if(!$n)return;const e=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=e}},[$n]);const sr=async e=>{ar.current||(xt(e,"interventions"),xt(e,"documents")),ar.current=!1;const t=(await ne.auth.getUser()).data.user?.id??"",n=ht(e),a=ft(e),[s,r,i]=await Promise.all([gt(e),W(t),ne.from("app_technicians").select("id, full_name").eq("company_id",e)]),o=s,l=o.map(e=>e.id),c=((l.length?await ne.from("app_intervention_photos").select("id, intervention_id, url, caption, phase").in("intervention_id",l).order("position"):{data:[]}).data??[]).reduce((e,t)=>
1(e[t.intervention_id]=[...e[t.intervention_id]??[],t],e),{});De(o),Be(!0),zn(c),n.then(tt).catch(()=>{}),at(Object.fromEntries((i.data??[]).map(e=>[e.id,e.full_name]))),pe(r??null);const d=r??null;d?.id&&Ae(d.id).then(e=>{$e(e.appointment_invoice_mode),Aa({hidePhotos:e.report_hide_photos,showPrices:e.report_show_prices,headerText:e.report_header_text,footerText:e.report_footer_text}),Ta(e.report_require_signature),$a(e.header_info??null)}).catch(()=>$e("draft")),a.then(e=>{Sn(e),kn(e.filter(e=>"quote"===e.doc_type))}).catch(()=>{});const[u,p,m]=await Promise.allSettled([Ye(e),x(e),X(e)]);"fulfilled"===u.status&&qa(u.value),La("fulfilled"===p.status?p.value:{}),ra("fulfilled"===m.status?m.value:[])};e.useEffect(()=>{if(!Fn.client_id)return void Zn([]);let e=!0;return bt(Fn.client_id).then(t=>{e&&Zn(t)}).catch(()=>{e&&Zn([])}),()=>{e=!1}},[Fn.client_id]),e.useEffect(()=>{(async()=>{const{data:e}=await ne.auth.getUser();if(!e.user)return;const t=await U(e.user.id);t&&(ie(t.company_id),await sr(t.company_id))})()},[]),e.useEffect(()=>{if(!se)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>{e=null,sr(se)},700)},n=ne.channel(`interventions-${se}`).on("postgres_changes",{event:"*",schema:"public",table:"app_interventions",filter:`company_id=eq.${se}`},t).on("postgres_changes",{event:"*",schema:"public",table:"app_documents",filter:`company_id=eq.${se}`},t).on("postgres_changes",{event:"*",schema:"public",table:"app_payments"},t).subscribe();return()=>{e&&clearTimeout(e),ne.removeChannel(n)}},[se]),e.useEffect(()=>{const e=It.get("client");if(!e||vn.current||!Ee.some(t=>t.id===e))return;vn.current=!0,Ct(e),ba(!0);const t=new URLSearchParams(It);t.delete("client"),Ut(t,{replace:!0})},[Ee,It,Ut]),e.useEffect(()=>{if(!ce)return;const e=Pe.filter(e=>!("validated"!==e.status&&"signed"!==e.status||e.pdf_url||Nn.current.has(e.id))).slice(0,3);if(0===e.length)return;let t=!1;return(async()=>{for(const n of e){Nn.current.add(n.id);try{await zr(n)}catch{}if(t)return}!t&&Pe[0]&&await sr(Pe[0].company_id)})(),()=>{t=!0}},[Pe,ce]),e.useEffect(()=>{const e=It.get("appointment");e&&zt?.id!==e&&("mobile"===It.get("from")&&ba(!0),se&&(Dt(It.get("service")??""),"mobile"===It.get("from")&&Qt(!0),(async()=>{const{data:t}=await ne.from("app_appointments").select("*").eq("company_id",se).eq("id",e).maybeSingle();if(!t)return;At(t);const n=t.document_id;if(n){const{data:e}=await ne.from("app_documents").select("doc_type").eq("id",n).maybeSingle();"quote"===e?.doc_type&&Qn(n)}Rn(await Se(e));const a=t.equipment_id;a&&Yn(a);const s=t.client_id??"";if(Ct(s),s){const{data:e}=await ne.from("app_clients").select("*").eq("id",s).maybeSingle();e&&tt(t=>t.some(t=>t.id===e.id)?t:[...t,e].sort((e,t)=>e.name.localeCompare(t.name)))}ba(!0)})()))},[se,zt?.id,It]);const rr=async(e,t)=>{const n=Number(e.sent_count??0)+1,a=(new Date).toISOString();await ne.from("app_interventions").update({sent_at:a,sent_channel:t,sent_count:n}).eq("id",e.id),await S(e,t),De(s=>s.map(s=>s.id===e.id?{...s,sent_at:a,sent_channel:t,sent_count:n}:s))},ir=e=>{const t=function(e,t=""){if(!e)return{};const n=function(e){const t=new Date(e.starts_at).getTime(),n=new Date(e.ends_at).getTime();return Number.isNaN(t)||Number.isNaN(n)?0:Math.max(0,Math.round((n-t)/6e4))}(e);return{client_id:e.client_id??t,site_id:e.site_id??"",intervention_date:Te(new Date(e.starts_at)),service_type:e.service_type??"",address_line1:e.address_line1??"",postal_code:e.postal_code??"",city:e.city??"",occupant_name:e.occupant_name??"",occupant_phone:e.occupant_phone??"",duration_minutes:n?String(n):""}}(zt,mt),n=Tt.trim(),a=n&&e?.serviceType&&Rt(lr,n)?.id!==e.id?"":n,s=a?sa.find(e=>e.label.trim().toLowerCase()===a.toLowerCase())?.duration_minutes??null:null,r=Rt(lr,zt?.service_type??null);return{...t,...Boolean(e?.serviceType&&r&&r.id!==e.id)?{service_type:e.serviceType}:{},...a?{service_type:a}:{},...s?{duration_minutes:String(s)}:{},technician_name:zt?.technician_id?nt[zt.technician_id]??"":""}},or=()=>{null!=zt?.latitude&&null!=zt?.longitude&&Fa({lat:Number(zt.latitude),lon:Number(zt.longitude)})},lr=Ie(Sa),cr=Tt?ot(Tt):lt(zt),dr=cr[0]?rt(cr[0].pole):null,ur=(dr&&lr.some(e=>e.id===dr)?dr:null)??Rt(lr,Tt||zt?.service_type||null)?.id??null,pr=ur?[...lr].sort((e,t)=>
1Number(t.id===ur)-Number(e.id===ur)):lr;e.useEffect(()=>{if(!Wt||!ga||$n||!Le||!zt)return;if(an.current===zt.id)return;const e=lr.find(e=>e.id===ur);e&&"general"!==e.id&&(!Pe.some(e=>e.appointment_id===zt.id)||Tt.trim()?(an.current=zt.id,xr(e)):an.current=zt.id)},[Wt,ga,$n,Le,zt?.id,ur]);const mr=()=>{ba(!0),$s("")},xr=e=>{ba(!1),Dn(null),Hn(e.id);const t=Fe(e.id)?cr.map(e=>e.key):[],n=t.length?{[Oe]:ut(t),...dt(t)?{quote_follow_up:ct}:{}}:{};ta({...Ft(Me(e.fields,n)),...n}),en(!1),ca(!1),ua(!1),ma(!1),fa.current={work_done:!1,findings:!1},On({...xn,client_id:mt,service_type:e.serviceType,findings:e.defaults?.findings??"",work_done:e.defaults?.work_done??"",recommendations:e.defaults?.recommendations??"",...ir(e)}),or(),Qn(e=>e&&e===zt?.document_id?e:""),aa(jn(e,sa,t)),Ua(!1),Wa(!1),Ja(""),Ga(jt()),Xa(""),es(""),ns(""),is(zt?"oui":""),ls(!0),ds(""),ps(""),ys(An.map((e,t)=>({id:`appt-${e.id}`,url:e.url,caption:e.caption,phase:"before",position:t}))),$s(""),Pn(!0),Ht("details")},hr=async e=>{const{data:t}=await ne.from("app_intervention_photos").select("id, url, caption, phase").eq("intervention_id",e.id).order("position"),n=wn.find(t=>t.intervention_id===e.id);Dn(e),Hn(e.report_type??"general"),ta(e.template_data??{}),On({client_id:e.client_id??"",intervention_date:e.intervention_date,service_type:e.service_type??"",technician_name:e.technician_name??"",address_line1:e.address_line1??"",postal_code:e.postal_code??"",city:e.city??"",findings:e.findings??"",work_done:e.work_done??"",parts_used:e.parts_used??"",duration_minutes:e.duration_minutes?String(e.duration_minutes):"",recommendations:e.recommendations??"",occupant_name:e.occupant_name??"",occupant_phone:e.occupant_phone??"",site_id:e.site_id??""}),Qn(n?.id??""),aa(H(e)),Yn(e.equipment_id??"");const a=J(e);Ua(a.received),Wa(Boolean(e.template_data?.billed_on_visit));{const t=String(e.template_data?.payment_method??"");Ja(Z.includes(t)?t:"")}Ga(a.date),Xa(a.amountCents?(a.amountCents/100).toFixed(2):""),es(e.client_signature_url??""),ns(e.signed_by??"");const s=e.template_data??{};is("non"===s.visit_done?"non":"oui"===s.visit_done?"oui":""),ls(!1!==s.housing_over_2_years),ds("string"==typeof s.technician_signature?s.technician_signature:""),ys(t??[]),$s(""),Pn(!0)},fr=()=>{Pn(!1),Dn(null),fs(!1),Wt&&Kt("/app/mobile",{replace:!0})};n($n,fr,a);const gr=()=>({companyLoaded:Boolean(se&&ce),clientId:Fn.client_id,workDone:Fn.work_done,visitDone:rs,fields:Or,templateData:ea,technicianSignature:cs,clientSignature:Ya,requireSignature:Pa,signedBy:ts}),br=e.useRef(null),vr=e=>{"signature"===e&&"undefined"!=typeof navigator&&navigator.geolocation&&navigator.geolocation.getCurrentPosition(e=>{br.current={lat:Number(e.coords.latitude.toFixed(5)),lng:Number(e.coords.longitude.toFixed(5)),accuracy_m:Math.round(e.coords.accuracy),at:(new Date).toISOString()}},()=>{},{enableHighAccuracy:!0,timeout:8e3,maximumAge:12e4}),$s(""),fn(""),Ht(e)},jr=()=>{const e=function(e){const t=Lt(e);return t<=0?null:Pt[t-1]}(Jt);e?vr(e):fr()},_r=zt?.id??Tn?.appointment_id??null,yr=Pe.find(e=>e.id!==Tn?.id&&"draft"!==e.status&&(Boolean(_r)&&e.appointment_id===_r||Boolean(Fn.client_id)&&e.client_id===Fn.client_id&&Boolean(Fn.intervention_date)&&e.intervention_date===Fn.intervention_date))??null,Nr=Boolean(yr);e.useEffect(()=>{$n&&!Tn&&Nr&&(Wa(!0),Ua(!1))},[$n,Tn,Nr]);const wr=`${Fn.address_line1.trim()}|${Fn.postal_code.trim()}|${Fn.city.trim()}`.toLowerCase(),kr=async()=>{const{data:e}=await ne.auth.getUser().catch(()=>({data:{user:null}}));return{...Fn,company_id:se,created_by:e.user?.id??null,technician_id:zt?.technician_id??Tn?.technician_id??null,number:Tn?.number??null,duration_minutes:Fn.duration_minutes?Number(Fn.duration_minutes):null,site_id:Fn.site_id||null,appointment_id:zt?.id??Tn?.appointment_id??null,occupant_name:Fn.occupant_name.trim()||null,occupant_phone:Fn.occupant_phone.trim()||null,status:Tn?.status??"draft",report_type:Jn,template_data:{...ea,...br.current?{signature_geo:br.current}:{},visit_done:rs,housing_over_2_years:os,technician_signature:cs||null,billing_lines:Ka?[]:na,billed_on_visit:Ka,payment_received:!Ka&&Va,payment_method:Qa,payment_date:Va?Ha:null,payment_amount_cents:Va&&Number(Za)>0?Math.round(100*Number(Za)):null},legal_mentions:et(Lr,ea),legal_basis:Lr.legalBasis||null,equipment_id:Xn||null,client_signature_url:Tn?.client_signature_url??null,signed_by:Tn?.signed_by??null,signed_at:Tn?.signed_at??null,review_requested:!1}},Cr=async()=>
1{if(!se||!Fn.client_id||!Fn.work_done.trim())return $s("Sélectionnez un client et indiquez le travail réalisé."),null;if("signed"===Tn?.status||"validated"===Tn?.status)return $s("Un rapport signé est conservé comme preuve et ne peut plus être modifié."),null;const e=await kr(),t=Tn?await ne.from("app_interventions").update(e).eq("id",Tn.id).select("*").single():await ne.from("app_interventions").insert(e).select("*").single();return t.error||!t.data?($s(t.error?.message??"Impossible dâenregistrer le rapport."),null):t.data},Sr=async(e,t,n)=>{const a=await qr(e,t,n);return ce&&"quote"!==a?.doc_type&&await te(e,ce,t),a},qr=async(e,t,n)=>{if(!ce)throw new Error("Les données de lâentreprise ne sont pas disponibles. Réessayez dans quelques secondes.");if("quote"===Re(e.report_type??Jn))return await Y(e,ce,t);const a=e.appointment_id;if(!H(e).length&&!n){if(a){const{count:t}=await ne.from("app_interventions").select("id",{count:"exact",head:!0}).eq("appointment_id",a).neq("id",e.id);if((t??0)>0)return null}if(Boolean(e.template_data?.billed_on_visit)&&e.client_id&&e.intervention_date){const{count:t}=await ne.from("app_interventions").select("id",{count:"exact",head:!0}).eq("client_id",e.client_id).eq("intervention_date",e.intervention_date).neq("id",e.id);if((t??0)>0)return null}}return await ee(e,ce,t,n)},zr=async e=>{const n=e.pdf_url;if(n)return n;const a=Ee.find(t=>t.id===e.client_id),{data:s}=await ne.from("app_intervention_photos").select("id, url, caption, phase").eq("intervention_id",e.id).order("position"),r=Ve(e.report_type??"general",Sa),i=await N(t.jsx(p,{intervention:e,photos:s??[],clientName:a?.name??"Client",company:ce??{},template:r,options:za,headerInfo:Ra}),`rapport-${e.number??e.id}.pdf`),o=await w(i,`interventions/${e.id}`),{error:l}=await ne.from("app_interventions").update({pdf_url:o}).eq("id",e.id);if(l)throw l;return o},Ar=async(e,t,n,a=!1)=>{const s=a?J(e):null,r=s?s.received:Va;if(!r)return"unpaid";if(!t?.email)return"no_email";if(!n)return"failed";try{const i=String(ce?.name??"VDKchauffconfort SRL"),o=M(a?H(e):na),l=s?s.method:Qa,c=s?s.amountCents??o.incl:Number(Za)>0?Math.round(100*Number(Za)):o.incl;let d=`Rapport dâintervention ${e.number??""} â ${i}`.replace(" "," "),u=Q({number:e.number,companyName:i,clientName:t.name,date:e.intervention_date});try{const n=await k(e.company_id),a=C(r?n.report_paid:n.report,{client:t.name,numero:e.number??"",entreprise:i,date:K(e.intervention_date),total:V(o.incl),moyen:l,montant:V(c)});d=a.subject||d,u=a.body||u}catch{}const p=e.service_type??"",{data:m,error:x}=await hn(()=>ne.functions.invoke("send-document",{body:{to:t.email,subject:d,message:u,pdfUrl:n,companyId:e.company_id,documentLabel:"rapport dâintervention",idempotencyKey:`report-${e.id}`,maintenanceType:/ramon/i.test(p)?"ramonage":/entretien|chaudi/i.test(p)?"entretien":void 0}}),e=>!e.error&&Boolean(e.data?.success),3);return x||!m?.success?"failed":(await rr(e,"e-mail"),"sent")}catch{return"failed"}},Rr=e.useRef(new Set);e.useEffect(()=>{if(!Le||!ce||0===Ee.length)return;const e=Date.now()-6048e5,t=e=>e,n=Pe.filter(t=>!Rr.current.has(t.id)&&t.client_signature_url&&t.signed_at&&t.client_id&&("signed"===t.status||"validated"===t.status&&!t.sent_at&&Boolean(t.pdf_url)&&new Date(t.signed_at).getTime()>e&&Boolean(J(t)?.received)));n.length&&(n.forEach(e=>Rr.current.add(e.id)),(async()=>{let e=!1;for(const a of n)try{const n=Ee.find(e=>e.id===a.client_id);if("validated"===a.status){"sent"===await Ar(a,n??null,t(a).pdf_url??null,!0)&&(e=!0);continue}e=!0;const s=await hn(()=>Sr(a,n,null)),{error:r}=await hn(()=>ne.from("app_interventions").update({status:"validated"}).eq("id",a.id),e=>!e.error);if(r)throw r;const i={...a,status:"validated"};await wt(i);const o=t(a).appointment_id;if(o){const{data:e}=await ne.from("app_appointments").select("intervention_id, document_id").eq("id",o).maybeSingle();await ne.from("app_appointments").update({status:"done",intervention_id:e?.intervention_id??a.id,...s&&!e?.document_id?{document_id:s.id}:{}}).eq("id",o)}let l=null;try{l=await zr(i)}catch{l=t(a).pdf_url??null}a.sent_at||await Ar(i,n??null,l,!0)}catch{Rr.current.delete(a.id)}e&&(xt(ce.id,"interventions"),xt(ce.id,"documents"),sr(ce.id))})())},[Le,ce,Ee,Pe]);const $r=()=>{bs(null),Wt&&Kt("/app/mobile"+(zt?.id?`?appointment=${zt.id}`:""),{replace:!0})},Pr=async()=>{const e=function(e){if(!e.companyLoaded)return"Les données de lâentreprise ne sont pas encore chargées. Fermez puis rouvrez le rapport.";if(!e.clientId)return"Sélectionnez un client avant de valider le rapport.";if(!e.workDone.trim())return"Indiquez le travail réalisé avant de valider le rapport.";if(!e.visitDone)return"Indiquez si le rendez-vous a été effectué.";const t=e.fields.find(t=>t.required&&!String(e.templateData[t.key]??"").trim());return t?`Complétez le champ obligatoire « ${t.label} ».`:!1===e.requireSignature||e.clientSignature?"":"Faites signer le client dans la zone de signature."}(gr())||Mr;
1if(Va&&!Z.includes(Qa))return void $s("Choisissez comment le client a payé : Espèces, Bancontact ou Virement / QR code.");if(e)return void $s(e);if(ws(!0),$s(""),"undefined"!=typeof navigator&&!1===navigator.onLine){try{if(!(await(async()=>{const e=zt?.technician_id??Tn?.technician_id??null;if(!se||!e)return $s("Ce rapport ne peut pas être conservé hors connexion : reconnectez-vous pour lâenregistrer."),!1;if(!Fn.client_id||!Fn.work_done.trim())return $s("Sélectionnez un client et indiquez le travail réalisé."),!1;const t={companyId:se,technicianId:e},n=Tn?.id??crypto.randomUUID(),a=as||(new Date).toISOString(),s=await kr(),r=[];for(const[o,l]of _s.entries()){const e=crypto.randomUUID();l.file?(await kt(e,l.file),r.push({id:e,caption:null,phase:"after",position:o,stored:!0})):l.url&&r.push({id:e,caption:l.caption??null,phase:l.phase??"before",position:o,url:l.url})}const i=Ee.find(e=>e.id===Fn.client_id);return ze(t,{kind:"report",intervention_id:n,values:{...s,status:"signed",client_signature_url:Ya,signed_by:ts.trim()||i?.name||null,signed_at:a},photos:r,appointment_id:zt?.id??Tn?.appointment_id??null,quote_id:Wn||null,output:"quote"===Re(Jn)?"quote":"invoice",label:Fn.service_type||"Rapport dâintervention",client_name:i?.name??"Client",total_incl_cents:M(na).incl}),!0})()))return void ws(!1)}catch(a){return $s(a instanceof Error?a.message:"Le rapport nâa pas pu être conservé sur lâappareil."),void ws(!1)}return ws(!1),fs(!1),Pn(!1),Dn(null),Wt?void Kt("/app/mobile"+(zt?.id?`?appointment=${zt.id}`:""),{replace:!0}):void ps("Rapport signé conservé sur lâappareil : il sera envoyé automatiquement au retour du réseau.")}let t=null;if(Tn?.id){const{data:e}=await ne.from("app_interventions").select("*").eq("id",Tn.id).maybeSingle(),n=e;if("validated"===n?.status)return ws(!1),fs(!1),Pn(!1),Dn(null),ps("Ce rapport est déjà validé."),void(Wt&&Kt("/app/mobile"+(zt?.id?`?appointment=${zt.id}`:""),{replace:!0}));"signed"===n?.status&&n.client_signature_url&&(t=n)}if(!t){const e=await Cr();if(!e)return void ws(!1);Tn||Dn(e);const n=as||(new Date).toISOString(),a=ts.trim()||Ee.find(t=>t.id===e.client_id)?.name||null,{data:s,error:r}=await hn(()=>ne.from("app_interventions").update({client_signature_url:Ya,signed_by:a,signed_at:n,status:"signed"}).eq("id",e.id).select("id, client_signature_url").maybeSingle(),e=>!e.error&&Boolean(e.data?.client_signature_url));if(r||!s?.client_signature_url)return $s(r?.message??"La signature du client nâa pas été enregistrée. Réessayez."),void ws(!1);t={...e,client_signature_url:Ya,signed_by:a,signed_at:n,status:"signed"},Dn(t)}const n=t;try{Cs(Ka&&Nr?"Rattachement à la facture du premier rapportâ¦":"Création de la facture en projetâ¦"),await Tr(n,_s).catch(e=>{}),await Dr(n.id,Wn).catch(e=>{});const e=wn.find(e=>e.id===Wn)??null;let t=Ee.find(e=>e.id===n.client_id);if(!t&&n.client_id){const{data:e}=await ne.from("app_clients").select("*").eq("id",n.client_id).maybeSingle();t=e??void 0}if(!ce)throw new Error("Les données de lâentreprise ne sont pas disponibles. Réessayez dans quelques secondes.");const a=await hn(()=>Sr(n,t,e));Cs("Validation du rapportâ¦");const{error:s}=await hn(()=>ne.from("app_interventions").update({status:"validated"}).eq("id",n.id),e=>!e.error);if(s)throw s;await wt(n);const r=zt?.id??n.appointment_id;if(r){const{data:e}=await ne.from("app_appointments").select("intervention_id, document_id").eq("id",r).maybeSingle(),{error:t}=await ne.from("app_appointments").update({status:"done",intervention_id:e?.intervention_id??n.id,...a&&!e?.document_id?{document_id:a.id}:{}}).eq("id",r);t&&await ne.from("app_appointments").update({status:"done"}).eq("id",r)}const i=async()=>{let e=null;try{e=await Promise.race([zr({...n,status:"validated"}),new Promise(e=>setTimeout(()=>e(null),9e4))])}catch{}if(!e){const{data:t}=await ne.from("app_interventions").select("pdf_url").eq("id",n.id).maybeSingle();e=t?.pdf_url??null}return Ar({...n,status:"validated"},t??null,e)};if(Wt)return i().catch(()=>"failed").then(e=>{window.dispatchEvent(new CustomEvent("vdk-report-mail",{detail:e})),xt(n.company_id,"interventions"),xt(n.company_id,"documents")}),Cs(""),xt(n.company_id,"interventions"),ws(!1),fs(!1),Pn(!1),Dn(null),void Kt(`/app/mobile?${r?`appointment=${r}&`:""}report=validated&mail=pending`,{replace:!0});Cs("Fabrication et envoi du rapportâ¦");const o=await i();Cs("");const l=!1;if(xt(n.company_id,"interventions"),xt(n.company_id,"documents"),Wt?sr(n.company_id):await sr(n.company_id),ws(!1),fs(!1),Wt&&!l)return Pn(!1),Dn(null),void Kt(`/app/mobile?${r?`appointment=${r}&`:""}report=validated&mail=${o}`,{replace:!0});if(Wt)return Pn(!1),void Dn(null);if(fr(),!l){xs(n);const e="unpaid"===o?" Non payé : rapport conservé dans la fiche client, non envoyé automatiquement."
1:"sent"===o?` Envoyé par e-mail à ${t?.email}.`:"no_email"===o?" Le client nâa pas dâadresse e-mail : rapport non envoyé.":" Lâe-mail nâa pas pu partir : envoyez-le avec le bouton e-mail.";ps(`Le rapport ${n.number??""} a bien été validé et enregistré.${e}`.replace(" "," "))}return}catch(s){Cs("");const e=s?.message;$s(e?`Le rapport est signé et conservé. Validation interrompue : ${e}. Touchez « Confirmer et valider » pour reprendre.`:"Le rapport est signé et conservé. Validation interrompue (réseau). Touchez « Confirmer et valider » pour reprendre.")}ws(!1)},Tr=async(e,t)=>{const n=t.filter(e=>!e.file&&String(e.id??"").startsWith("appt-"));for(const[s,r]of n.entries()){const{error:t}=await ne.from("app_intervention_photos").insert({intervention_id:e.id,url:r.url,caption:r.caption??null,phase:r.phase??"before",position:s});if(t)throw t}const a=t.filter(e=>e.file);for(const[s,r]of a.entries()){const n=r.file;if(!n)continue;const a=`interventions/${e.id}/${crypto.randomUUID()}-${n.name.replace(/[^a-zA-Z0-9._-]/g,"-")}`,{error:i}=await ne.storage.from("app-quote-attachments").upload(a,n,{upsert:!1});if(i)throw i;const{data:o,error:l}=await ne.storage.from("app-quote-attachments").createSignedUrl(a,31536e3);if(l)throw l;const{error:c}=await ne.from("app_intervention_photos").insert({intervention_id:e.id,url:o.signedUrl,caption:null,phase:"after",position:t.length+s});if(c)throw c}},Dr=async(e,t)=>{const n=wn.filter(n=>n.intervention_id===e&&n.id!==t);for(const a of n){const{error:e}=await ne.from("app_documents").update({intervention_id:null}).eq("id",a.id);if(e)throw e}if(t){const{error:n}=await ne.from("app_documents").update({intervention_id:e}).eq("id",t).eq("doc_type","quote");if(n)throw n}},Lr=Ve(Jn,Sa),Br=(()=>{if(!Fn.client_id)return null;const e=Pe.filter(e=>e.client_id===Fn.client_id&&e.id!==Tn?.id).sort((e,t)=>String(t.intervention_date??"").localeCompare(String(e.intervention_date??""))).map(e=>e.template_data??{}).find(e=>pn.some(t=>String(e[t]??"").trim()));if(!e)return null;const t=Object.fromEntries(pn.filter(t=>String(e[t]??"").trim()).map(t=>[t,String(e[t])]));return pn.some(e=>t[e]&&!String(ea[e]??"").trim())?t:null})(),Er=Fe(Lr.id)?function(e,t=[],n=0){const a={},s=new Set,r=[],i=it(e.sub_services),o=rn(e.work_status);/partiel|impossible/i.test(o)&&s.add("work_limit_reason"),/impossible/i.test(o)&&!rn(e.quote_follow_up).startsWith("Oui")&&r.push({level:"warning",message:"Travaux impossibles : proposez un devis ou un nouveau rendez-vous.",fieldKey:"quote_follow_up"});const l=rn(e.installation_safety),c=l.startsWith("Dangereuse"),d=Object.entries(e).some(([e,t])=>"installation_safety"!==e&&"client_refusal"!==e&&ln.test(rn(t)));if(l.startsWith("Non conforme")||c||d){s.add("anomalies_outside"),s.add("recommendation_urgency");const t=rn(e.recommendation_urgency);t&&"Aucune"!==t||(a.recommendation_urgency="à prévoir")}c&&(a.recommendation_urgency="Urgent",0===n&&r.push({level:"blocking",message:"Installation dangereuse : ajoutez au moins une photo."})),rn(e.client_refusal).startsWith("Refusés")&&s.add("technician_reservations"),"Urgent"===(a.recommendation_urgency??rn(e.recommendation_urgency))&&!rn(e.quote_follow_up)&&(a.quote_follow_up="Oui â devis à établir");const u=t.map(e=>on(rn(e.description))).filter(Boolean);if(u.length&&i.length)for(const p of i){const e=st(p);if(!e)continue;const t=[e.label,...e.aliases,...e.catalogLabels].map(on).filter(Boolean);u.some(e=>t.some(t=>e.includes(t)||t.includes(e)))||r.push({level:"warning",message:`« ${e.label} » est coché mais aucune prestation correspondante nâest facturée.`})}for(const p of s)rn(e[p])||a[p]||r.push({level:"blocking",message:"Champ devenu obligatoire à compléter.",fieldKey:p});return{derived:a,required:Array.from(s),issues:r}}(ea,na,_s.length):null,Ir=new Set(Er?.required??[]),Fr=Me(Lr.fields,ea).map(e=>Ir.has(e.key)?{...e,required:!0}:e),Or=Fe(Lr.id)?[{key:Oe,label:"Sous-services réalisés",required:!0},...Fr]:Fr,Mr=Er?.issues.find(e=>"blocking"===e.level&&!e.fieldKey)?.message??"",Vr=Er?.issues.filter(e=>"warning"===e.level)??[];e.useEffect(()=>{if(!Er)return;const e=function(e,t){const n={};for(const[a,s]of Object.entries(t.derived))rn(e[a])!==s&&(n[a]=s);return n}(ea,Er);Object.keys(e).length&&ta(t=>({...t,...e}))},[ea,Lr.id]),e.useEffect(()=>
1{if(!$n||Tn||!Fe(Jn))return;const e=Ue(ea);On(t=>{const n={...t};return!fa.current.work_done&&e.work_done&&t.work_done!==e.work_done&&(n.work_done=e.work_done),fa.current.findings||!e.findings||t.findings.includes(e.findings)||(n.findings=Yt(t.findings.split("\n").filter(e=>!e.startsWith("Non conforme :")&&!e.startsWith("Pièce manquante :")).join("\n"),e.findings)),n.work_done===t.work_done&&n.findings===t.findings?t:n})},[$n,Tn,Jn,ea]);const Ur=Pe.filter(e=>Boolean(e.sent_at)),Kr={search:Ds,statusFilter:Ps,stateFilter:Is,range:Bs,numberFilter:Os,amountFilter:Vs,technicianFilter:Ks,reportTypeFilter:Qs,billingFilter:Hs,paymentFilter:Zs},Wr=yt(Kr),Qr=Pe.map(e=>{const t=M(H(e)).incl,n=Cn.filter(t=>t.intervention_id===e.id&&"invoice"===t.doc_type&&"cancelled"!==t.status);return{item:e,totalIncl:t,pay:G(e,t),invoiced:n.length>0}}).filter(({item:e,totalIncl:t,pay:n,invoiced:a})=>Nt({number:e.number??"",clientName:Ee.find(t=>t.id===e.client_id)?.name??"",serviceType:e.service_type??"",reportType:e.report_type??"",city:e.city??"",technicianName:e.technician_name??"",date:e.intervention_date??"",status:e.status??"draft",sent:Boolean(e.sent_at),invoiced:a,paymentState:n.state,totalInclCents:t},Kr)),Jr=Qr.map(({item:e})=>e),Hr=Jr.slice(0,tr),Gr=Qr.reduce((e,t)=>({incl:e.incl+t.totalIncl,due:e.due+t.pay.dueCents,signed:e.signed+Number("signed"===t.item.status||"validated"===t.item.status),invoiced:e.invoiced+Number(t.invoiced)}),{incl:0,due:0,signed:0,invoiced:0}),Zr=Array.from(new Set(Pe.map(e=>String(e.report_type??"")).filter(Boolean))).sort(),Xr=Array.from(new Set([...Object.values(nt),...Pe.map(e=>e.technician_name??"")].filter(Boolean))).sort((e,t)=>e.localeCompare(t,"fr"));return t.jsxs(c,{children:[t.jsxs("div",{className:"space-y-3",children:[t.jsx(d,{active:"interventions",onInvoiceInterventions:mr}),Rs&&t.jsx("p",{role:"alert",className:"border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive",children:Rs}),t.jsxs("section",{className:"billing-panel overflow-hidden",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-b border-border px-3 py-2.5",children:[t.jsxs("div",{className:"relative min-w-56 flex-1 sm:max-w-md",children:[t.jsx(oe,{className:"pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-muted-foreground"}),t.jsx(A,{value:Ds,onChange:e=>Ls(e.target.value),placeholder:"Client, numéro, prestation ou ville",className:"h-9 bg-card pl-9"})]}),t.jsxs(z,{type:"button",className:"h-9 min-w-32 uppercase",onClick:()=>nr(50),children:[t.jsx(oe,{}),"Rechercher"]}),t.jsx("button",{type:"button",className:"text-sm text-muted-foreground underline-offset-4 transition hover:text-foreground hover:underline",onClick:()=>{Ls(""),Es({}),Ts(""),Fs(""),Ms(""),Us(""),Ws(""),Js(""),Gs(""),Xs("")},children:"Réinitialiser"}),t.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"billing-ghost ml-auto font-semibold",onClick:()=>er(e=>!e),children:[t.jsx(xe,{}),Ys?"Masquer les statistiques":"Afficher les statistiques"]}),t.jsx("span",{className:"text-sm text-muted-foreground","aria-live":"polite",children:Le?`${Jr.length} résultat${Jr.length>1?"s":""}`:"Recherche en coursâ¦"})]}),t.jsxs("div",{className:"space-y-2 p-3 text-sm",children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-start gap-x-6 gap-y-2",children:[t.jsxs("fieldset",{className:"flex items-center gap-x-4 gap-y-2",children:[t.jsx("legend",{className:"float-left mr-4 font-semibold",children:"Rapport :"}),[["signed","Signé"],["draft","En projet"],["","Les deux"]].map(([e,n])=>t.jsxs("label",{className:"flex items-center gap-1.5",children:[t.jsx("input",{type:"radio",name:"report-state",value:e,checked:Is===e,onChange:()=>Fs(e)}),n]},n))]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"font-semibold",children:"Ãtat :"}),t.jsxs("select",{value:Ps,onChange:e=>Ts(e.target.value),"aria-label":"Filtrer par état",className:"h-8 rounded-md border border-input bg-card px-2",children:[t.jsxs("option",{value:"",children:["Tous (",Pe.length,")"]}),t.jsx("option",{value:"draft",children:"Brouillons"}),t.jsxs("option",{value:"sent",children:["Envoyés (",Ur.length,")"]}),t.jsx("option",{value:"signed",children:"Signés"}),t.jsx("option",{value:"validated",children:"Terminés"})]})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"font-semibold",children:"Entre le :"}),t.jsx(A,{type:"date","aria-label":"Rapport entre le",value:Bs.from??"",onChange:e=>Es(t=>({...t,from:e.target.value||void 0})),className:"h-8 w-auto"}),t.jsx("span",{children:"et le"}),t.jsx(A,{type:"date","aria-label":"Rapport et le",value:Bs.to??"",onChange:e=>Es(t=>({...t,to:e.target.value||void 0})),className:"h-8 w-auto"})]})]}),t.jsxs(_t,{activeCount:Wr,children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-start gap-x-6 gap-y-2",children:[t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"font-semibold",children:"Numéro :"}),t.jsx(A,{value:Os,onChange:e=>Ms(e.target.value),className:"h-8 w-32"})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"font-semibold",children:"Montant :"}),t.jsx(A,{value:Vs,onChange:e=>Us(e.target.value),inputMode:"decimal",className:"h-8 w-28"})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-semibold",children:"Intervenant :"}),t.jsxs("select",{value:Ks,onChange:e=>Ws(e.target.value),"aria-label":"Intervenant",className:"h-8 w-48 min-w-0 rounded-md border border-input bg-card px-2",children:[t.jsx("option",{value:"",children:"Tous les intervenants"}),Xr.map(e=>t.jsx("option",{value:e,children:e},e))]})]})]}),t.jsxs("div",{className:"flex flex-wrap items-center justify-start gap-x-6 gap-y-2",children:[t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-semibold",children:"Type de rapport :"}),t.jsxs("select",{value:Qs,onChange:e=>Js(e.target.value),"aria-label":"Type de rapport",className:"h-8 w-52 min-w-0 rounded-md border border-input bg-card px-2",children:[t.jsx("option",{value:"",children:"Tous les types"}),Zr.map(e=>t.jsx("option",{value:e,children:Ve(e,Sa).label},e))]})]}),t.jsxs("fieldset",{className:"flex items-center gap-x-4 gap-y-2",children:[t.jsx("legend",{className:"float-left mr-4 font-semibold",children:"Facturation :"}),[["invoiced","Facturé"],["not_invoiced","Non facturé"],["","Les deux"]].map(([e,n])=>t.jsxs("label",{className:"flex items-center gap-1.5",children:[t.jsx("input",{type:"radio",name:"report-billing",value:e,checked:Hs===e,onChange:()=>Gs(e)}),n]},n))]}),t.jsxs("fieldset",{className:"flex items-center gap-x-4 gap-y-2",children:[t.jsx("legend",{className:"float-left mr-4 font-semibold",children:"Paiement :"}),[["paid","Payé"],["unpaid","Impayé"],["","Les deux"]].map(([e,n])=>t.jsxs("label",{className:"flex items-center gap-1.5",children:[t.jsx("input",{type:"radio",name:"report-payment",value:e,checked:Zs===e,onChange:()=>Xs(e)}),n]},n))]})]})]})]})]}),Ys&&t.jsxs("section",{className:"grid grid-cols-2 gap-2 sm:grid-cols-5","aria-label":"Statistiques des rapports",children:[t.jsxs("div",{className:"billing-stat",children:[t.jsx("p",{className:"billing-stat-label",children:"Rapports"}),t.jsx("strong",{className:"billing-stat-value",children:Jr.length})]}),t.jsxs("div",{className:"billing-stat",children:[t.jsx("p",{className:"billing-stat-label",children:"Signés"}),t.jsx("strong",{className:"billing-stat-value",children:Gr.signed}
1)]}),t.jsxs("div",{className:"billing-stat",children:[t.jsx("p",{className:"billing-stat-label",children:"Facturés"}),t.jsx("strong",{className:"billing-stat-value",children:Gr.invoiced})]}),t.jsxs("div",{className:"billing-stat",children:[t.jsx("p",{className:"billing-stat-label",children:"Total TVAC"}),t.jsx("strong",{className:"billing-stat-value",children:V(Gr.incl)})]}),t.jsxs("div",{className:"billing-stat",children:[t.jsx("p",{className:"billing-stat-label",children:"Reste à payer"}),t.jsx("strong",{className:"billing-stat-value text-destructive",children:V(Gr.due)})]})]}),0===Jr.length?t.jsx(o,{icon:he,title:0===Pe.length?"Aucun rapport dâintervention":"Aucun résultat",hint:0===Pe.length?"Le prochain compte rendu sera enregistré ici.":"Aucun rapport ne correspond à cette recherche ou à ces critères.",action:t.jsxs(z,{onClick:mr,children:[t.jsx(le,{}),"Nouveau rapport"]})}):t.jsxs("div",{className:"space-y-2",children:[Hr.map(e=>{const n=Ee.find(t=>t.id===e.client_id),a="signed"===e.status||"validated"===e.status,s=Cn.filter(t=>t.intervention_id===e.id),r=s.filter(e=>"invoice"===e.doc_type),o=r.length>0&&r.every(e=>"cancelled"===e.status),c=M(H(e)).incl,d=G(e,c),u=_(e),m=t.jsx(p,{intervention:e,photos:qn[e.id]??[],clientName:n?.name??"Client",company:ce??{},template:Ve(e.report_type,Sa),options:za,headerInfo:Ra});return t.jsxs("div",{className:`doc-bar ${a?"doc-bar-report":"doc-bar-draft"} doc-row overflow-hidden`,children:[t.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("p",{className:"flex flex-wrap items-baseline gap-x-2 text-sm",children:[t.jsx("span",{className:"font-semibold text-primary",children:"R"}),t.jsx("strong",{className:"font-heading text-base",children:"Rapport"}),t.jsx("span",{className:"text-muted-foreground",children:e.number?`N°${e.number} du ${K(e.intervention_date)}`:`en projet â intervention du ${K(e.intervention_date)}`}),t.jsx("span",{className:"billing-badge billing-badge-neutral",children:"validated"===e.status?"Validé":"signed"===e.status?"Signé":"Brouillon"})]}),t.jsxs("p",{className:"mt-0.5 flex items-center gap-1.5 truncate text-sm text-muted-foreground",children:[t.jsx(fe,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.service_type||"Intervention"," · ",Ve(e.report_type,Sa).label]}),t.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(ge,{className:"h-3.5 w-3.5"}),e.client_id?t.jsx(i,{to:`/app/clients?client=${e.client_id}`,className:"font-semibold text-foreground underline-offset-2 hover:text-accent hover:underline",children:n?.name??"Client"}):t.jsx("strong",{className:"text-foreground",children:n?.name??"Client"})]}),e.technician_name&&t.jsx("span",{children:e.technician_name}),(qn[e.id]?.length??0)>0&&t.jsxs("span",{children:[qn[e.id].length," photo",qn[e.id].length>1?"s":""]})]}),e.occupant_name?t.jsxs("p",{className:"mt-1 truncate text-xs text-muted-foreground",children:["Sur place : ",String(e.occupant_name),[e.address_line1,e.postal_code,e.city].filter(Boolean).length?` â ${[e.address_line1,e.postal_code,e.city].filter(Boolean).join(", ")}`:""]}):null]}),t.jsxs("div",{className:"flex items-center justify-between gap-4 lg:justify-end",children:[t.jsx("span",{className:"hidden text-xs text-muted-foreground sm:inline",children:u||"E-mail non envoyé"}),t.jsxs("span",{className:"text-center text-xs",children:[t.jsx("span",{className:"block text-muted-foreground",children:"Paiement"}),t.jsx("strong",{children:o?"Annulé":d.label})]}),t.jsxs("span",{className:"text-right text-xs",children:[t.jsx("span",{className:"block text-muted-foreground",children:"Total TVAC"}),t.jsx("strong",{className:"font-heading text-base",children:V(c)})]}),!a&&t.jsxs(z,{size:"sm",className:"h-9 shrink-0",onClick:()=>{hr(e)},children:[t.jsx(be,{}),"Faire signer"]}),t.jsxs(P,{children:[t.jsx(T,{asChild:!0,children:t.jsx(z,{variant:"ghost",size:"sm",className:"h-9 w-9 p-0","aria-label":`Options du rapport ${e.number??"en projet"}`,children:t.jsx(ue,{className:"h-4 w-4"})})}),t.jsxs(D,{align:"end",className:"w-64",children:[!a&&t.jsxs(L,{onSelect:()=>{hr(e)},children:[t.jsx(ve,{}),"Modifier"]}),e.client_signature_url&&"signed"===e.status&&t.jsxs(L,{disabled:Ss===e.id,onSelect:()=>{(async e=>{if(e.client_id&&ce)if(e.client_signature_url&&e.signed_at){qs(e.id),$s("");try{const t=wn.find(t=>
1t.intervention_id===e.id)??null,n=Ee.find(t=>t.id===e.client_id),a=await Sr(e,n,t),{error:s}=await ne.from("app_interventions").update({status:"validated"}).eq("id",e.id);if(s)throw s;await wt(e);const r=e.appointment_id;if(r){const{data:t}=await ne.from("app_appointments").select("intervention_id, document_id").eq("id",r).maybeSingle(),{error:n}=await ne.from("app_appointments").update({status:"done",intervention_id:t?.intervention_id??e.id,...a&&!t?.document_id?{document_id:a.id}:{}}).eq("id",r);n&&await ne.from("app_appointments").update({status:"done"}).eq("id",r)}try{await zr({...e,status:"validated"})}catch{}xt(e.company_id,"interventions"),xt(e.company_id,"documents"),await sr(e.company_id)}catch(t){$s(t instanceof Error?t.message:"La facture brouillon nâa pas pu être créée.")}qs(null)}else $s("Faites signer le rapport par le client avant de le valider.")})(e)},children:[t.jsx(je,{}),Ss===e.id?"Créationâ¦":"Valider et créer la facture"]}),a&&!e.pdf_url&&t.jsxs(L,{disabled:zs===e.id,onSelect:()=>{(async e=>{As(e.id),$s("");try{await zr(e),await sr(e.company_id)}catch(t){$s(t instanceof Error?t.message:"Le PDF nâa pas pu être conservé.")}As(null)})(e)},children:[t.jsx(_e,{}),zs===e.id?"Enregistrementâ¦":"Conserver pour le client"]}),a&&t.jsxs(L,{onSelect:()=>Bn(e),children:[t.jsx(ve,{}),"Corriger l'adresse"]}),t.jsx(L,{asChild:!0,children:t.jsxs(l,{document:m,fileName:`rapport-${e.number??e.id}.pdf`,children:[t.jsx(_e,{}),"Télécharger le rapport"]})})]})]})]})]}),a&&t.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 border-t border-border pt-2 text-xs text-muted-foreground",children:[e.client_signature_url&&t.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-700",children:[t.jsx(re,{className:"h-3.5 w-3.5"}),"Signature enregistrée"]}),s.map(e=>t.jsxs("span",{children:["quote"===e.doc_type?"Devis":"credit_note"===e.doc_type?"Avoir":"Facture"," ",e.number??"en projet"]},e.id)),t.jsx(y,{document:m,fileName:`rapport-${e.number??e.id}.pdf`,folder:`interventions/${e.id}`,subject:`Rapport dâintervention ${e.number??""} â ${String(ce?.name??"VDK Chauffconfort SRL")}`.trim(),message:Q({number:e.number,companyName:String(ce?.name??"VDK Chauffconfort SRL"),clientName:n?.name??"Client",date:e.intervention_date}),email:n?.email,label:"Envoyer le rapport par e-mail",templateKind:"report",companyId:ce?.id,templateValues:{client:n?.name??"",numero:e.number??"",entreprise:String(ce?.name??"VDK Chauffconfort SRL"),date:K(e.intervention_date)},onSent:t=>{rr(e,t)}})]})]},e.id)}),t.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-border bg-card px-4 py-2 text-sm text-muted-foreground",children:[t.jsxs("span",{children:[Hr.length," rapport(s) affiché(s) sur ",Jr.length]}),tr<Jr.length&&t.jsx(z,{variant:"outline",size:"sm",onClick:()=>nr(e=>e+50),children:"Afficher 50 de plus"})]})]})]}),t.jsx(h,{open:ga,onOpenChange:ba,children:t.jsxs(f,{className:"flex max-h-[92dvh] max-w-3xl flex-col overflow-y-auto rounded-lg p-4 sm:p-6",children:[t.jsxs("div",{className:"mb-5 flex items-start justify-between",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-accent",children:"Choisir un modèle"}),t.jsx("h2",{className:"font-heading text-2xl font-bold",children:"Quel document devez-vous établir ?"}),t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Attestations et rapports conformes aux usages belges, adaptés à chaque service."})]}),Wt?t.jsxs(z,{type:"button",variant:"outline",className:"h-11",onClick:()=>{ba(!1),Kt("/app/mobile",{replace:!0})},children:[t.jsx(ye,{className:"h-4 w-4"}),"Retour à ma tournée"]}):t.jsx("span",{"aria-hidden":!0})]}),t.jsx("div",{className:"grid gap-3",children:pr.map(e=>t.jsxs("button",{type:"button",onClick:()=>"general"===e.id?(ba(!1),Dn(null),Hn("general"),ta({}),On({...xn,client_id:mt,...ir()}),or(),Qn(""),aa([]),Ua(!1),Wa(!1),Ja(""),Ga(jt()),Xa(""),es(""),ns(""),is(""),ls(!0),ds(""),ps(""),ys(An.map((e,t)=>({id:`appt-${e.id}`,url:e.url,caption:e.caption,phase:"before",position:t}))),$s(""),Pn(!0),void Ht("details")):xr(e),className:ae("border border-border bg-card p-4 text-left transition hover:border-accent",ur===e.id&&"border-accent bg-accent/5"),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"font-heading text-base font-semibold",children:e.label}),t.jsx("span",{className:"border border-border px-2 py-1 text-xs text-muted-foreground",children:ur===e.id?"Conseillé":e.category})]}),t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:e.description})]},e.id))})]})}),t.jsx(B,{open:va,onOpenChange:ja,children:t.jsxs(E,{side:"bottom",className:"flex h-auto max-h-[85dvh] flex-col rounded-t-2xl p-0 sm:h-auto sm:max-w-md
1sm:rounded-t-2xl",children:[t.jsxs(I,{className:"px-4 pb-2 pt-5 text-left sm:px-6",children:[t.jsx(F,{children:"Choisir un client"}),t.jsx(O,{children:"Recherchez par nom, téléphone ou ville, ou créez un nouveau client."})]}),t.jsxs("div",{className:"flex flex-col gap-3 overflow-hidden px-4 pb-4 sm:px-6",children:[t.jsx(A,{value:_a,onChange:e=>ya(e.target.value),placeholder:"Rechercher un clientâ¦",className:"h-12 flex-none text-base"}),t.jsxs("div",{className:"max-h-[50dvh] min-h-[160px] flex-1 space-y-1 overflow-y-auto rounded-md border border-border",children:[Ee.filter(e=>{const t=_a.toLowerCase().trim();return!t||`${e.name} ${e.phone??""} ${e.city??""} ${e.email??""}`.toLowerCase().includes(t)}).map(e=>t.jsxs("button",{type:"button",onClick:()=>{On(t=>({...t,client_id:e.id,address_line1:t.address_line1||(e.address_line1??""),postal_code:t.postal_code||(e.postal_code??""),city:t.city||(e.city??"")})),ja(!1),ya("")},className:"w-full border-b px-4 py-4 text-left text-sm last:border-b-0 active:bg-secondary "+(Fn.client_id===e.id?"border-accent bg-secondary":"border-border bg-background"),children:[t.jsx("span",{className:"block font-medium",children:e.name}),t.jsx("span",{className:"block text-xs text-muted-foreground",children:[e.phone,e.city].filter(Boolean).join(" · ")||"â"})]},e.id)),0===Ee.length&&t.jsx("p",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Aucun client enregistré pour lâinstant."})]}),t.jsxs("div",{className:"flex-none space-y-2 border-t border-border pt-3",children:[t.jsx(R,{children:"Nouveau client"}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(A,{value:Na,onChange:e=>wa(e.target.value),placeholder:"Nom du client",className:"h-12 flex-1 text-base"}),t.jsx(z,{type:"button",className:"h-12 px-4",disabled:ka||!Na.trim()||!se,onClick:async()=>{if(!se||!Na.trim())return;Ca(!0);const{data:e,error:t}=await ne.rpc("app_technician_create_client",{_company_id:se,_payload:{name:Na.trim()}});Ca(!1);const n=e;if(t||!n?.client)return void $s("Création du client impossible pour le moment. Réessayez.");const a=n.client;tt(e=>[...e,a].sort((e,t)=>e.name.localeCompare(t.name))),On(e=>({...e,client_id:a.id})),wa(""),ja(!1)},children:ka?"â¦":t.jsx(le,{})})]})]})]})]})}),$n&&t.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto overflow-x-hidden bg-background p-0 sm:bg-primary/40 sm:p-4",children:t.jsxs("div",{className:"mx-auto flex min-h-full w-full min-w-0 max-w-4xl flex-col border-border bg-background p-4 shadow-2xl sm:my-6 sm:min-h-0 sm:border sm:p-6",children:[t.jsxs("div",{className:ae("mb-4 flex items-start justify-between gap-3",!Tn?.client_signature_url&&"hidden sm:flex"),children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("p",{className:"truncate text-xs font-semibold uppercase tracking-[0.18em] text-accent",children:[Lr.category," · ",Tn?"Compte rendu":"Nouveau document"]}),t.jsx("h2",{className:"truncate font-heading text-xl font-bold sm:text-2xl",children:Tn?"Modifier le rapport":Lr.label})]}),Wt?t.jsxs(z,{type:"button",variant:"outline",className:"h-11 shrink-0",onClick:fr,children:[t.jsx(ye,{className:"h-4 w-4"}),"Retour à ma tournée"]}):t.jsx(z,{variant:"ghost",size:"icon",onClick:fr,"aria-label":"Fermer",children:t.jsx(ye,{})})]}),t.jsxs("form",{onSubmit:async e=>{e.preventDefault(),ws(!0),$s("");const t=!Tn,n=await Cr();if(n){try{if(await Tr(n,_s),await Dr(n.id,Wn),n.client_id&&ce){const e=wn.find(e=>e.id===Wn)??null,t=Ee.find(e=>e.id===n.client_id);"quote"===Re(Jn)?await Y(n,ce,t):await ee(n,ce,t,e)}await sr(n.company_id),t?(Dn(n),$s("")):fr()}catch(a){$s(a instanceof Error?a.message:"Les photos, la liaison ou la facture en projet nâont pas pu être enregistrées.")}ws(!1)}else ws(!1)},"data-field-step":Tn?.client_signature_url?void 0:Jt,"data-show-more":Zt?"true":void 0,className:ae("grid min-w-0 grid-cols-1 gap-5 sm:grid-cols-2",!Tn?.client_signature_url&&"mobile-report-flow"),children:[!Tn?.client_signature_url&&t.jsxs("div",{className:"min-w-0 sm:col-span-2",children:[t.jsx(un,{step:Jt,title:Tn?"Modifier le rapport":Lr.label,onBack:jr,onStepSelect:vr,onCh
1angeReport:Tn?void 0:()=>oa(!0)}),dn&&t.jsx("p",{role:"alert",className:"mt-3 rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:dn})]}),t.jsxs("div",{"data-report-section":"details",className:ae("space-y-2 border-l-4 pl-3",Fn.client_id?"border-primary":"border-warning"),children:[t.jsx(R,{children:"Client *"}),t.jsxs(z,{type:"button",variant:"outline",className:"h-12 w-full justify-start text-base",onClick:()=>ja(!0),children:[t.jsx(ge,{className:"h-4 w-4"}),Ee.find(e=>e.id===Fn.client_id)?.name??"Choisir un clientâ¦"]}),!Fn.client_id&&t.jsx("p",{className:"text-xs text-warning-foreground",children:"Sans client, aucune facture en projet ne sera créée à lâenregistrement du rapport."})]}),t.jsxs("div",{"data-report-section":"details",className:"min-w-0 space-y-2 rounded-md border border-border bg-secondary/30 p-3 sm:hidden",children:[t.jsx("p",{className:"text-sm font-semibold",children:Fn.service_type||Lr.label}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:[K(Fn.intervention_date),Fn.duration_minutes?` · ${Fn.duration_minutes} min`:""]}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:[[Fn.address_line1,[Fn.postal_code,Fn.city].filter(Boolean).join(" ")].filter(Boolean).join(", ")||"Adresse du client",Fn.occupant_name?` · chez ${Fn.occupant_name}`:""]}),t.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-9 px-0 text-primary",onClick:()=>en(e=>!e),children:Zt?"Masquer les détails":"Modifier date, adresse, TVA ou devis"})]}),t.jsx("div",{"data-report-section":"details-more",children:t.jsx(gn,{label:"Type dâintervention",value:Fn.service_type,onChange:e=>On({...Fn,service_type:e}),placeholder:"Dépannage chaudière, débouchageâ¦"})}),t.jsx("div",{"data-report-section":"details-more",children:t.jsx(gn,{label:"Date",type:"date",value:Fn.intervention_date,onChange:e=>On({...Fn,intervention_date:e})})}),t.jsx("div",{"data-report-section":"details-more",children:t.jsx(gn,{label:"Durée (minutes)",type:"number",value:Fn.duration_minutes,onChange:e=>On({...Fn,duration_minutes:e})})}),(()=>{const e=Ee.find(e=>e.id===Fn.client_id)??null,n=Fn.client_id?Da[Fn.client_id]??[]:[];return t.jsxs("div",{"data-report-section":"details-more",className:"space-y-3 sm:col-span-2 border border-border bg-secondary/30 p-4",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-accent",children:"Lieu de lâintervention"}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"Le client ci-dessus est celui qui paie (ex. le propriétaire). Si lâintervention a lieu chez un locataire, indiquez ici son adresse et ses coordonnées : elles apparaîtront sur le rapport, la facture restant au nom du payeur."}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(R,{htmlFor:"interventionspage-adresse-a-utiliser-1x",children:"Adresse à utiliser"}),t.jsxs("select",{id:"interventionspage-adresse-a-utiliser-1x",value:Fn.site_id||(Fn.occupant_name||Fn.occupant_phone?"new":"client"),onChange:t=>(t=>{if(Ma(""),"client"===t)return Fa(null!=e?.latitude&&null!=e?.longitude?{lat:Number(e.latitude),lon:Number(e.longitude)}:null),void On(t=>({...t,site_id:"",occupant_name:"",occupant_phone:"",address_line1:e?.address_line1??"",postal_code:e?.postal_code??"",city:e?.city??""}));if("new"===t)return Fa(null),void On(e=>({...e,site_id:"",occupant_name:"",occupant_phone:"",address_line1:"",postal_code:"",city:""}));const a=n.find(e=>e.id===t);a&&(Fa(null!=a.latitude&&null!=a.longitude?{lat:Number(a.latitude),lon:Number(a.longitude)}:null),On(e=>({...e,site_id:a.id,occupant_name:a.occupant_name??"",occupant_phone:a.occupant_phone??"",address_line1:a.address_line1??"",postal_code:a.postal_code??"",city:a.city??""})))})(t.target.value),className:"flex h-12 w-full border border-input bg-background px-3 text-base",children:[t.jsxs("option",{value:"client",children:["Adresse du client",e?` â ${[e.address_line1,e.postal_code,e.city].filter(Boolean).join(", ")||"non renseignée"}`:""]}),n.map(e=>t.jsxs("option",{value:e.id,children:[e.label,e.occupant_name?` â ${e.occupant_name}`:"",m(e)?` â ${m(e)}`:""]},e.id)),t.jsx("option",{value:"new",children:"Autre adresse (locataire, second bienâ¦)"})]})]}),t.jsx(pt,{label:"Adresse dâintervention",value:[Fn.address_line1,[Fn.postal_code,Fn.city].filter(
1Boolean).join(" ")].filter(Boolean).join(", "),located:null!==Ia,onPick:e=>{Fa({lat:e.lat,lon:e.lon}),On(t=>({...t,address_line1:e.address_line1,postal_code:e.postal_code,city:e.city}))},onClear:e=>{Fa(null),On(t=>({...t,address_line1:e}))}}),t.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[t.jsx(gn,{label:"Code postal",value:Fn.postal_code,onChange:e=>On({...Fn,postal_code:e})}),t.jsx(gn,{label:"Ville",value:Fn.city,onChange:e=>On({...Fn,city:e})}),t.jsx(gn,{label:"Occupant sur place (locataire)",value:Fn.occupant_name,onChange:e=>On({...Fn,occupant_name:e}),placeholder:"Nom du locataire"}),t.jsx(gn,{label:"Téléphone de lâoccupant",value:Fn.occupant_phone,onChange:e=>On({...Fn,occupant_phone:e}),placeholder:"0470 00 00 00"})]}),Fn.client_id&&(Fn.occupant_name.trim()||Fn.address_line1.trim())&&t.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[t.jsx(z,{type:"button",variant:"outline",className:"h-11",disabled:Ba,onClick:async()=>{if(se&&Fn.client_id){Ea(!0),Ma("");try{const e=await u({company_id:se,client_id:Fn.client_id,label:Fn.occupant_name.trim()?"Locataire":"Autre adresse",occupant_name:Fn.occupant_name,occupant_phone:Fn.occupant_phone,address_line1:Fn.address_line1,postal_code:Fn.postal_code,city:Fn.city,latitude:Ia?.lat??null,longitude:Ia?.lon??null},Fn.site_id||void 0);On(t=>({...t,site_id:e.id})),La(await x(se)),Ma("Lieu enregistré sur la fiche client.")}catch(e){$s(e instanceof Error?e.message:"Le lieu nâa pas pu être enregistré.")}Ea(!1)}},children:Ba?"Enregistrementâ¦":Fn.site_id?"Mettre à jour ce lieu":"Mémoriser ce lieu sur la fiche client"}),Oa&&t.jsx("span",{className:"text-xs text-emerald-700",children:Oa})]})]})})(),Mn&&!Un&&t.jsxs("div",{"data-report-section":"technical",className:"min-w-0 space-y-2 rounded-md border border-border bg-secondary/35 p-3 sm:col-span-2",children:[t.jsxs("p",{className:"text-sm font-semibold",children:["Dernier passage : ",new Date(`${Mn.date}T12:00:00`).toLocaleDateString("fr-BE"),Mn.service?` · ${Mn.service}`:""]}),Mn.work_done&&t.jsx("p",{className:"line-clamp-2 text-xs text-muted-foreground",children:Mn.work_done}),t.jsx(z,{type:"button",variant:"outline",className:"h-11 w-full",onClick:()=>{On(e=>({...e,findings:e.findings||Mn.findings||"",work_done:e.work_done||Mn.work_done||"",parts_used:e.parts_used||Mn.parts_used||"",recommendations:e.recommendations||Mn.recommendations||""})),Kn(!0)},children:"Reprendre le rapport précédent"}),t.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Tout reste modifiable avant la signature."})]}),t.jsx(Vt,{open:ia,onOpenChange:oa,currentTemplateId:Lr.id,planned:cr.map(e=>e.key),otherTemplates:lr.filter(e=>!Fe(e.id)).map(e=>({id:e.id,label:e.label})),onChoose:e=>{const t=Ve(e.templateId,Sa),n=Fe(e.templateId)?e.subServices:[],a=n.length?{[Oe]:ut(n),...dt(n)?{quote_follow_up:ct}:{}}:{};Hn(t.id),ta({...Ft(Me(t.fields,a)),...a}),On(e=>({...e,service_type:t.serviceType,findings:t.defaults?.findings??"",work_done:t.defaults?.work_done??"",recommendations:t.defaults?.recommendations??""})),aa(jn(t,sa,n)),oa(!1),fn(""),Ht("details")}}),t.jsx(nn,{enabled:Fe(Lr.id),title:"Prestations",summary:it(ea[Oe]).map(e=>st(e)?.label??e).join(", ")||"à choisir",open:Boolean(dn)||"prestations"===xa,onOpen:()=>ha("prestations"===xa?"":"prestations"),onNext:()=>ha("controles"),children:Fe(Lr.id)&&t.jsx("div",{"data-report-section":"technical",className:"min-w-0 sm:col-span-2",children:t.jsx(Mt,{reportId:Lr.id,selected:it(ea[Oe]),invalid:Boolean(dn)&&!it(ea[Oe]).length,onToggle:e=>{const t=it(ea[Oe]),n=t.includes(e)?t.filter(t=>t!==e):[...t,e],a={...ea,[Oe]:ut(n)};!t.includes(e)&&st(e)?.onQuote&&(a.quote_follow_up=ct),ta({...Ft(Me(Lr.fields,a)),...a}),t.length||!n.length||na.some(e=>String(e.description??"").trim())||aa(jn(Lr,sa,n))},planned:Tn?[]:cr.map(e=>e.key),onReset:()=>ta(e=>({...e,[Oe]:ut(cr.map(e=>e.key))}))})})}),t.jsx(nn,{enabled:Fe(Lr.id),title:"Appareil et contrôles",summary:[[ea.appliance_brand,ea.appliance_model,ea.appliance_capacity,ea.appliance_orientation,ea.appliance_kind].filter(e=>String(e??"").trim()).join(" · "),(()=>{const e=Qe(ea[Oe],ea[Je]);return e.length?`${e.filter(e=>"OK"===ea[`chk_${e}`]).length}/${e.length} OK`:""}
1)()].filter(Boolean).join(" â "),open:Boolean(dn)||"controles"===xa,onOpen:()=>ha("controles"===xa?"":"controles"),onNext:()=>ha("pieces"),children:Fr.length>0&&t.jsxs("div",{"data-report-section":"technical",className:"min-w-0 space-y-3 rounded-2xl sm:col-span-2 border border-border bg-secondary/30 p-4",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-accent",children:"Contrôles"}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx(z,{type:"button",size:"sm",variant:"outline",onClick:()=>ta({...ea,...Ft(Fr)}),children:"Tout conforme"}),Br&&t.jsx(z,{type:"button",size:"sm",variant:"outline",onClick:()=>ta({...Br,...Object.fromEntries(Object.entries(ea).filter(([,e])=>String(e??"").trim()))}),children:"Reprendre lâappareil du dernier rapport"})]}),Fe(Lr.id)&&Ke(ea[Oe])&&(()=>{const e=We[Ke(ea[Oe])];return t.jsxs("div",{className:"min-w-0 space-y-2","data-report-field":"appliance_brand",children:[t.jsxs("p",{className:"text-sm font-semibold",children:["Appareil · ",e.label]}),t.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[t.jsx(A,{"aria-label":"Marque",placeholder:"Marque",value:ea.appliance_brand??"",onChange:e=>ta({...ea,appliance_brand:e.target.value}),className:"h-12"}),t.jsx(A,{"aria-label":"Modèle",placeholder:"Modèle",value:ea.appliance_model??"",onChange:e=>ta({...ea,appliance_model:e.target.value}),className:"h-12"})]}),!String(ea.appliance_brand??"").trim()&&t.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.brands.map(e=>t.jsx("button",{type:"button",onClick:()=>ta({...ea,appliance_brand:e}),className:"min-h-9 rounded-full border border-border bg-background px-3 text-xs hover:border-accent/60",children:e},e))}),e.extra.map(e=>t.jsxs("div",{className:"space-y-1","data-report-field":e.key,children:[t.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:e.label}),t.jsx("div",{className:"flex flex-wrap gap-1.5",role:"radiogroup","aria-label":e.label,children:e.options.map(n=>{const a=ea[e.key]===n;return t.jsx("button",{type:"button",role:"radio","aria-checked":a,onClick:()=>ta({...ea,[e.key]:a?"":n}),className:ae("min-h-10 rounded-full border px-3 text-sm",a?"border-accent bg-accent text-accent-foreground":"border-border bg-background hover:border-accent/60"),children:n},n)})})]},e.key))]})})(),Fe(Lr.id)&&Qe(ea[Oe],ea[Je]).length>0&&t.jsx(sn,{checks:Qe(ea[Oe],ea[Je]),values:ea,invalidKeys:dn?new Set(Fr.filter(e=>e.key.startsWith("chk_")&&!String(ea[e.key]??"").trim()).map(e=>e.key)):void 0,onChange:(e,t)=>
1ta({...ea,[e]:t}),onAdd:e=>ta({...ea,[Je]:[...String(ea[Je]??"").split("|").filter(Boolean),e].join("|"),[`chk_${e}`]:"OK"})}),t.jsx("div",{className:"grid min-w-0 gap-4 sm:grid-cols-2",children:[...Fr].filter(e=>!Fe(Lr.id)||!(e.key.startsWith("chk_")||e.key.startsWith("appliance_"))).filter(e=>pa||e.required||"error_code"===e.key||!Fe(Lr.id)).sort((e,t)=>Number(mn.includes(e.key))-Number(mn.includes(t.key))).map(e=>{const n=Boolean(dn)&&Boolean(e.required)&&!String(ea[e.key]??"").trim();return t.jsxs("div",{className:ae("min-w-0 space-y-2",e.required&&"border-l-4 pl-3",e.required&&(n?"border-destructive":"border-accent/50")),children:["select"!==e.type&&t.jsxs(R,{htmlFor:`report-field-${e.key}`,className:ae(n&&"text-destructive"),children:[e.label,e.required?" *":""]}),"select"===e.type?t.jsx(Ot,{id:`report-field-${e.key}`,label:e.label,required:e.required,invalid:n,options:e.options??[],value:ea[e.key]??"",onChange:t=>ta({...ea,[e.key]:t})}):"checkbox"===e.type?t.jsxs("label",{className:"flex h-11 items-center gap-2 text-sm sm:h-10",children:[t.jsx("input",{id:`report-field-${e.key}`,type:"checkbox",checked:"oui"===ea[e.key],onChange:t=>ta({...ea,[e.key]:t.target.checked?"oui":""})}),"Oui"]}):"textarea"===e.type?t.jsx($,{id:`report-field-${e.key}`,rows:3,value:ea[e.key]??"",onChange:t=>ta({...ea,[e.key]:t.target.value}),placeholder:e.placeholder}):t.jsx(A,{id:`report-field-${e.key}`,type:e.type??"text",value:ea[e.key]??"",onChange:t=>ta({...ea,[e.key]:t.target.value}),placeholder:e.placeholder})]},e.key)})}),Fe(Lr.id)&&Fr.some(e=>!e.required&&!e.key.startsWith("appliance_")&&"error_code"!==e.key)&&t.jsx(z,{type:"button",variant:"ghost",className:"h-11 px-0 text-primary",onClick:()=>ma(e=>!e),children:pa?"Masquer les détails facultatifs":`Plus de détails (${Fr.filter(e=>!e.required&&!e.key.startsWith("appliance_")&&"error_code"!==e.key).length})`})]})}),t.jsxs(nn,{enabled:Fe(Lr.id),title:"Pièces et recommandations",summary:Object.entries(Ge(ea[Ze])).map(([e,t])=>`${e} : ${"missing"===t?"à prévoir":"added"===t?"posée":"remplacée"}`).join(" · ")||"Aucune pièce",open:Boolean(dn)||"pieces"===xa,onOpen:()=>ha("pieces"===xa?"":"pieces"),onNext:()=>ha("textes"),children:[Fe(Lr.id)&&t.jsxs("div",{"data-report-section":"technical",className:"min-w-0 space-y-2 sm:col-span-2",children:[t.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Pièces · touchez pour indiquer remplacée, posée ou manquante"}),t.jsx(tn,{parts:Xe(ea[Oe]),status:Ge(ea[Ze]),onChange:e=>{const t=He(Ge(ea[Ze])),n=He(e),a=(e,t)=>e.split("\n").filter(e=>!t.includes(e.trim())).join("\n"),s=n.missing.length>0;ta({...ea,[Ze]:JSON.stringify(e),...s&&!ea.recommendation_urgency?.trim()||s&&"Aucune"===ea.recommendation_urgency?{recommendation_urgency:"à prévoir"}:{}}),s&&ua(!0),On(e=>({...e,parts_used:n.parts.reduce((e,t)=>Yt(e,t),a(e.parts_used,t.parts)),recommendations:n.missing.reduce((e,t)=>Yt(e,t),a(e.recommendations,t.missing))}))}})]}),t.jsx("div",{"data-report-section":"technical",children:t.jsx(bn,{label:"Pièces / matériel",value:Fn.parts_used,onChange:e=>On({...Fn,parts_used:e})})}),t.jsx("div",{"data-report-section":"technical",children:da||Fn.recommendations.trim()?t.jsx(bn,{label:"Recommandations",value:Fn.recommendations,onChange:e=>On({...Fn,recommendations:e})}):t.jsxs(z,{type:"button",variant:"ghost",className:"h-11 px-0 text-primary",onClick:()=>ua(!0),children:[t.jsx(le,{className:"h-4 w-4"}),"Ajouter une recommandation"]})})]}),t.jsxs(nn,{enabled:Fe(Lr.id),title:"Constat et travaux réalisés",summary:Fn.work_done.split("\n")[0]||"à compléter",open:Boolean(dn)||"textes"===xa,onOpen:()=>ha("textes"===xa?"":"textes"),children:[t.jsxs("div",{"data-report-section":"technical",className:"min-w-0 space-y-2 sm:col-span-2",children:[t.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Saisie rapide · selon les sous-services cochés"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:Gt(ea[Oe]).map(e=>t.jsx(z,{type:"button",variant:"outline",size:"sm",className:"h-auto min-h-10 whitespace-normal rounded-full text-left",onClick:()=>On(t=>({...t,[e.target]:t[e.target]?`${t[e.target]}\n${e.text}`:e.text})),children:e.label},e.text))})]}),Xt(ea[Oe]).length>0&&t.jsxs("div",{"data-report-section":"technical",className:"min-w-0 space-y-2 sm:col-span-2",children:[t.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Panne constatée"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:Xt(ea[Oe]).map(e=>{const n=Fn.findings.includes(e.text);return t.jsx("button",{type:"button","aria-pressed":n,onClick:()=>{ca(!0),On(t=>({...t,findings:n?t.findings.split("\n").filter(t=>t.trim()!==e.text).join("\n"):Yt(t.findings,e.text)}))},className:ae("inline-flex min-h-10 items-center rounded-full border px-3 py-1.5 text-sm transition-colors",n?"border-accent bg-accent text-accent-foreground":"border-border bg-background hover:border-accent/60"),children:e.label},e.label)})})]}),t.jsx("div",{"data-report-section":"technical",children:la||Fn.findings.trim()?t.jsx(bn,{label:"Constat",value:Fn.findings,onChange:e=>{fa.current.findings=!0,On({...Fn,findings:e})}}):t.jsxs(z,{type:"button",variant:"ghost",className:"h-11 px-0 text-primary",onClick:()=>ca(!0),children:[t.jsx(le,{className:"h-4 w-4"}),"Ajouter un constat"]})}),t.jsx("div",{"data-report-section":"technical",children:t.jsx(bn,{label:"Travaux réalisés *",value:Fn.work_done,onChange:e=>{fa.current.work_done=!0,On({...Fn,work_done:e})},required:!0})})]}),t.jsx("div",{"data-report-section":"validation",className:ae("min-w-0 space-y-2 border-l-4 pl-3 sm:col-span-2",dn&&!rs?"border-destructive":"border-accent/50"),children:t.jsx(Ot,{id:"report-visit-done",label:"Le rendez-vous a-t-il été effectué ?",required:!0,invalid:Boolean(dn)&&!rs,options:["Oui, réalisée","Non, non réalisée"],value:"oui"===rs?"Oui, réalisée":"non"===rs?"Non, non réalisée":"",onChange:e=>is("Oui, réalisée"===e?"oui":"Non, non réalisée"===e?"non":"")}
1)}),Wn&&t.jsx(St,{quoteId:Wn,hasLines:na.length>0,onUseLines:aa}),Nr&&"quote"!==Re(Jn)&&t.jsxs("div",{"data-report-section":"details",className:"space-y-2 sm:col-span-2 border border-border bg-secondary/30 p-4",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-accent",children:"Facturation de ce rapport"}),t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ce client a déjà un rapport aujourdâhui",yr?.number?` (${yr.number})`:""," : une seule facture regroupe toute la visite. Aucune nouvelle facture ne sera créée."]}),t.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[t.jsxs(z,{type:"button",variant:Ka?"default":"outline",className:"h-auto min-h-14 whitespace-normal py-2 text-left","aria-pressed":Ka,onClick:()=>{Wa(!0),Ua(!1)},children:[Ka&&t.jsx(re,{}),"Prix déjà mis sur le premier rapport (rien à ajouter)"]}),t.jsxs(z,{type:"button",variant:Ka?"outline":"default",className:"h-auto min-h-14 whitespace-normal py-2 text-left","aria-pressed":!Ka,onClick:()=>Wa(!1),children:[!Ka&&t.jsx(re,{}),"Ajouter des prix à cette même facture"]})]})]}),!(Ka&&Nr)&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{"data-report-section":"details",className:"sm:col-span-2",children:[t.jsx(qt,{lines:na,onChange:aa,catalog:sa,defaultVatRate:$t(os)}),"quote"!==Re(Jn)&&t.jsxs("label",{className:"mt-3 flex min-h-12 items-center gap-3 border border-border bg-card px-3 py-2 text-sm font-medium",children:[t.jsx("input",{type:"checkbox",className:"h-5 w-5",checked:na.some(_n),onChange:e=>aa(na.map(t=>({...t,description:e.target.checked?_n(t)?t.description:`${t.description??""} (sous garantie)`.trim():String(t.description??"").replace(/\s*\(sous garantie\)/gi,"")}))),disabled:!na.length}),"Intervention sous garantie (seul cas autorisé à 0 â¬)"]})]}),t.jsxs("div",{"data-report-section":"validation",className:"space-y-3 sm:col-span-2 border border-border bg-secondary/30 p-4",children:[(()=>{const e=M(na).incl,n=Va?Math.min(Number(Za)>0?Math.round(100*Number(Za)):e,e):0,a=!Va||n<=0?"unpaid":n>=e&&e>0?"paid":"partial",s="paid"===a?"border-emerald-300 bg-emerald-50 text-emerald-800":"partial"===a?"border-amber-300 bg-amber-50 text-amber-800":"border-border bg-background text-muted-foreground";return t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-accent",children:"Paiement"}),t.jsx("span",{className:`border px-2 py-1 text-xs font-medium ${s}`,children:"paid"===a?"Payé":"partial"===a?`Partiellement payé · ${V(n)} / ${V(e)}`:"Non payé"})]})})(),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:[...Z,"Pas payé"].map(e=>{const n="Pas payé"===e?!Va:Va&&Qa===e;return t.jsxs(z,{type:"button",variant:n?"default":"outline",className:"h-14 text-base font-semibold","aria-pressed":n,onClick:()=>{"Pas payé"!==e?(Ua(!0),Ja(e)):Ua(!1)},children:[n&&t.jsx(re,{}),"Virement"===e?"Virement / QR code":e]},e)})}),Va?t.jsxs("details",{className:"text-sm",children:[t.jsx("summary",{className:"cursor-pointer py-2 text-primary",children:"Montant ou date différents ?"}),t.jsxs("div",{className:"grid gap-4 pt-2 sm:grid-cols-2",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(R,{htmlFor:"interventionspage-montant-recu-laisser-vide-total-4x",children:"Montant reçu (â¬, vide = total)"}),t.jsx(A,{id:"interventionspage-montant-recu-laisser-vide-total-4x",type:"number",inputMode:"decimal",step:"0.01",min:"0",value:Za,onChange:e=>Xa(e.target.value),placeholder:(M(na).incl/100).toFixed(2),className:"h-12 text-base sm:h-10 sm:text-sm"})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(R,{htmlFor:"interventionspage-date-du-paiement-3x",children:"Date du paiement"}),t.jsx(A,{id:"interventionspage-date-du-paiement-3x",type:"date",value:Ha,onChange:e=>Ga(e.target.value),className:"h-12 text-base sm:h-10 sm:text-sm"})]})]})]}):null,t.jsx("p",{className:"text-xs text-muted-foreground",children:Va?`Encaissement enregistré : la facture liée sera soldée à concurrence du montant reçu (total ${V(M(na).incl)}).`:"Paiement pas encore reçu : la facture liée restera à encaisser."})]})]}),t.jsxs("div",{"data-report-section":"details-more",className:"space-y-2 sm:col-span-2",children:[t.jsx(R,{children:"Devis lié (facultatif)"}),t.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[t.jsx(Ne,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),t.jsxs("select",{value:Wn,onChange:e=>Qn(e.target.value),className:"flex h-11 min-w-0 flex-1 border border-input bg-background px-3 text-sm",children:[t.jsx("option",{value:"",children:"Aucun devis"}),wn.filter(e=>!Fn.client_id||e.client_id===Fn.client_id).map(e=>t.jsxs("option",{value:e.id,children:[e.number??"Brouillon"," â ",e.title??"Devis"]},e.id))]})]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"Utilisé si aucun poste nâest saisi ci-dessus : les prix du rapport ont la priorité pour la facture brouillon."})]}),Gn.length>0&&t.jsxs("div",{"data-report-section":"technical",className:"space-y-2 sm:col-span-2",children:[t.jsx(R,{htmlFor:"interventionspage-equipement",children:"Appareil concerné"}),t.jsxs("select",{id:"interventionspage-equipement",value:Xn,onChange:e=>Yn(e.target.value),className:"flex h-12 w-full border border-input bg-background px-3 text-base",children:[t.jsx("option",{value:"",children:"Aucun appareil rattaché"}),Gn.map(e=>t.jsx("option",{value:e.id,children:vt(e)},e.id))]})]}),t.jsxs("div",{"data-report-section":"technical",className:"space-y-2 sm:col-span-2",children:[t.jsx(R,{htmlFor:"interventionspage-photos-du-rapport-1",children:"Photos du rapport"}),t.jsx(A,{id:"interventionspage-photos-du-rapport-1",type:"file",accept:"image/*",multiple:!0,onChange:e=>ys(t=>[...t,...Array.from(e.target.files??[]).map(e=>({id:crypto.randomUUID(),url:"",caption:null,phase:"after",file:e}))])}),t.jsx("div",{className:"flex flex-wrap gap-2",children:_s.map(e=>t.jsxs("div",{className:"flex items-center gap-2 border border-border px-2 py-1 text-xs",children:[e.file?.name??"Photo enregistrée",t.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>ys(t=>t.filter(t=>t.id!==e.id)),"aria-label":"Supprimer la photo",children:t.jsx(de,{})})]},e.id))})]}),t.jsxs("div",{"data-report-section":"details-more",className:"space-y-2 sm:col-span-2 border border-border bg-secondary/30 p-4",children:[t.jsxs("label",{className:"flex min-h-12 items-center gap-3 text-sm",children:[t.jsx("input",{type:"checkbox",className:"h-5 w-5 accent-emerald-600",checked:os,onChange:e=>ls(e.target.checked)}),t.jsx("span",{children:"Le logement du client est achevé depuis plus de 2 ans"})]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:os?"TVA réduite 6 % appliquée aux nouveaux postes du rapport.":"Logement de moins de 2 ans : TVA 21 % appliquée aux nouveaux postes."})]}),se&&Fn.client_id&&t.jsx("div",{"data-report-section":"validation",className:"border border-border bg-secondary/30 p-4 sm:col-span-2",children:t.jsx(qe,{companyId:se,clientId:Fn.client_id,online:navigator.onLine})}),!Tn?.client_signature_url&&t.jsxs("div",{"data-report-section":"signature",className:"space-y-4 sm:col-span-2",children:[t.jsxs("div",{className:"space-y-2 border-l-4 border-destructive pl-3",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-accent",children:"Signature du client sur place *"}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"Faites signer le client directement au doigt sur votre téléphone, puis validez."})]}),t.jsx(q,{value:Ya,onChange:es,onSignedAt:ss})]}),Tn?.client_signature_url&&t.jsxs("div",{className:"sm:col-span-2 border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800",children:["Signature enregistrée pour ",t.jsx("strong",{children:T
1n.signed_by})," le ",Tn.signed_at?K(Tn.signed_at.slice(0,10)):"â",". Le rapport est conservé comme preuve."]}),!Tn?.client_signature_url&&"signature"===Jt&&t.jsxs("section",{"data-report-section":"signature",className:"space-y-3 border border-border bg-card p-4 sm:col-span-2",children:[t.jsxs("div",{"data-address-confirm":!0,className:ae("space-y-2 rounded-xl border p-3",En===wr?"border-emerald-300 bg-emerald-50":"border-amber-300 bg-amber-50"),children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Intervention réalisée au"}),t.jsx("p",{className:"text-base font-bold text-foreground",children:[Fn.address_line1,[Fn.postal_code,Fn.city].filter(Boolean).join(" ")].filter(Boolean).join(", ")||"Adresse manquante"}),En===wr?t.jsxs("p",{className:"flex items-center gap-1.5 text-sm font-semibold text-emerald-700",children:[t.jsx(re,{className:"h-4 w-4"}),"Adresse confirmée â elle figurera sur l'attestation"]}):t.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[t.jsxs(z,{type:"button",className:"h-11",disabled:!Fn.address_line1.trim(),onClick:()=>{In(wr),fn("")},children:[t.jsx(re,{}),"Oui, c'est ici"]}),t.jsxs(z,{type:"button",variant:"outline",className:"h-11",onClick:()=>{fn(""),Ht("details")},children:[t.jsx(ve,{}),"Autre adresse"]})]})]}),t.jsx("h3",{className:"font-heading text-lg font-bold uppercase",children:"Récapitulatif"}),t.jsxs("dl",{className:"grid grid-cols-[1fr_auto] gap-x-4 gap-y-2 text-sm",children:[t.jsx("dt",{className:"text-muted-foreground",children:"Intervention"}),t.jsx("dd",{className:"text-right font-semibold",children:Fn.service_type||Lr.label}),t.jsx("dt",{className:"text-muted-foreground",children:"Client"}),t.jsx("dd",{className:"text-right font-semibold",children:Ee.find(e=>e.id===Fn.client_id)?.name??"â"}),t.jsx("dt",{className:"text-muted-foreground",children:"Total TVAC"}),t.jsx("dd",{className:"text-right font-semibold",children:V(M(na).incl)}),t.jsx("dt",{className:"text-muted-foreground",children:"Paiement"}),t.jsx("dd",{className:"text-right font-semibold",children:Va?`${Qa} · ${Za||V(M(na).incl)}`:"Non reçu"}),t.jsx("dt",{className:"text-muted-foreground",children:"Photos"}),t.jsx("dd",{className:"text-right font-semibold",children:_s.length})]}),t.jsx("p",{className:"whitespace-pre-wrap border-t border-border pt-3 text-sm text-muted-foreground",children:Fn.work_done})]}),Rs&&t.jsx("p",{role:"alert",className:"text-sm text-destructive sm:col-span-2",children:Rs}),Tn?.client_signature_url?t.jsx("div",{className:"sticky bottom-0 z-10 mt-2 flex min-w-0 flex-col gap-2 border-t border-border bg-background/95 py-3 backdrop-blur sm:static sm:col-span-2 sm:flex-row sm:justify-end sm:gap-3 sm:border-0 sm:bg-transparent sm:py-0",children:t.jsxs("div",{className:"flex min-w-0 gap-2 sm:gap-3",children:[t.jsx(z,{type:"button",variant:"outline",className:"h-11 min-w-0 flex-1 sm:h-10 sm:flex-none",onClick:fr,children:"Annuler"}),t.jsx(z,{type:"submit",variant:"outline",disabled:Ns,className:"h-11 min-w-0 flex-1 sm:h-10 sm:flex-none",children:Ns?"Enregistrementâ¦":"Enregistrer le brouillon"})]})}):t.jsxs("div",{className:"sticky bottom-0 z-10 mt-2 flex min-w-0 flex-col gap-2 border-t border-border bg-background/95 py-3 backdrop-blur sm:col-span-2",children:["signature"!==Jt?t.jsxs(z,{type:"button",className:"h-12 w-full",onClick:()=>{const e=Et(t=Jt,gr())||("technical"===t?Mr:"");var t;e?fn(e):vr(function(e){return Pt[Math.min(Lt(e)+1,Pt.length-1)]}(Jt))},children:[Bt(Jt),t.jsx(we,{})]}):t.jsxs(z,{type:"button",className:"h-12 w-full",onClick:()=>{if(Wt&&En!==wr)return fn("Confirmez d'abord l'adresse où l'intervention a eu lieu."),void document.querySelector("[data-address-confirm]")?.scrollIntoView({behavior:"smooth",block:"center"});const e=Ka?"":yn(na,"quote"===Re(Jn));if(e)return fn(e),Ht("details"),void document.querySelector('[data-report-section="details"]')?.scrollIntoView({behavior:"smooth",block:"center"});const t=(n=gr(),Pt.find(e=>""!==Et(e,n))??null);var n;if(t){const e=Et(t,gr());return fn(e),void Ht(t)}fn(""),$s(""),fs(!0),Pr()},disabled:Ns,children:[t.jsx(re,{}),Bt(Jt)]}),t.jsxs("div",{className:"flex min-w-0 gap-2",children:[t.jsx(z,{type:"button",variant:"outline",className:"h-11 min-w-0 flex-1",onClick:jr,children:"Retour"}),t.jsx(z,{type:"submit",variant:"outline",disabled:Ns,className:"h-11 min-w-0 flex-1",children:Ns?"Enregistrementâ¦":"Brouillon"})]})]})]})]})}),t.jsx(h,{open:hs,onOpenChange:fs,children:t.jsxs(f,{className:"max-w-md",children:[t.jsxs(g,{children:[t.jsx(b,{children:"Vérification avant validation"}),t.jsxs(v,{children:["Contrôlez la signature et lâhorodatage : le rapport signé sert de preuve légale et générera le PDF ainsi quâ","quote"===Re(Jn)?"un devis en projet":"une facture brouillon","."]})]}),t.jsxs("div",{className:"space-y-3 text-sm",children:[Ya&&t.jsx("img",{src:Ya,alt:"Signature du client à vérifier",className:"h-24 w-full border border-border bg-white object-contain"}),t.jsxs("ul",{className:"space-y-1 text-muted-foreground",children:[t.jsxs("li",{children:[t.jsx("span",{className:"text-foreground",children:"Date & heure :"})," ",(()=>{const e=as?new Date(as):new Date;return`${e.toLocaleDateString("fr-BE")} à ${e.toLocaleTimeString("fr-BE",{hour:"2-digit",minute:"2-digit"})}`})()]}),t.jsxs("li",{children:[t.jsx("span",{className:"text-foreground",children:"Rapport :"})," ",Fn.service_type||"Rapport dâintervention"]}),t.jsxs("li",{children:[t.jsx("span",{className:"text-foreground",children:"Photos jointes :"})," ",_s.length]}),t.jsxs("li",{children:[t.jsx("span",{className:"text-foreground",children:"quote"===Re(Jn)?"Montant TVAC proposé :":"Total TVAC facturé :"})," ",V(M(na).incl)]}),"quote"!==Re(Jn)&&String(ea.quote_follow_up??"").startsWith("Oui")&&t.jsxs("li",{children:[t.jsx("span",{className:"text-foreground",children:"Devis à suivre :"})," un devis en projet sera préparé pour le Bureau"]}),String(ea.installation_safety??"").startsWith("Dangereuse")&&t.jsx("li",{className:"text-destructive",children:"Installation dangereuse mise à lâarrêt : le client signe en ayant été informé."}),String(ea.client_refusal??"").startsWith("Refusés")&&t.jsx("li",{className:"text-destructive",children:"Le client refuse les travaux re
1commandés et en prend la responsabilité."}),t.jsxs("li",{children:[t.jsx("span",{className:"text-foreground",children:"Paiement :"})," ",Va?`Reçu â ${Qa} le ${K(Ha)}`:"Pas encore reçu"]})]}),Vr.length>0&&t.jsx("ul",{"aria-label":"Points à vérifier",className:"space-y-1 border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:Vr.map(e=>t.jsxs("li",{children:["à vérifier : ",e.message]},e.message))}),0===M(na).incl&&t.jsx("p",{className:"border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:"quote"===Re(Jn)?"Aucun montant nâest encore chiffré : le devis restera en projet pour être complété dans Bureau.":"Aucun montant nâest saisi : la facture brouillon sera créée à 0,00 â¬. Ajoutez vos prestations avant de valider si le chantier doit être facturé."}),Rs&&t.jsx("p",{role:"alert",className:"border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:Rs}),Ns&&ks&&t.jsxs("p",{role:"status","aria-live":"polite",className:"flex items-center gap-2 border border-primary/30 bg-primary/5 px-3 py-2 text-sm font-medium text-foreground",children:[t.jsx("span",{className:"h-3 w-3 animate-spin rounded-full border-2 border-primary border-t-transparent"}),ks]})]}),t.jsxs(j,{children:[t.jsx(z,{type:"button",variant:"outline",onClick:()=>fs(!1),disabled:Ns,children:"Corriger la signature"}),t.jsxs(z,{type:"button",onClick:()=>{Pr()},disabled:Ns,children:[t.jsx(re,{}),Ns?ks||"Validationâ¦":"Confirmer et valider"]})]})]})}),t.jsx(h,{open:Boolean(us),onOpenChange:e=>{e||(ps(""),xs(null))},children:t.jsxs(f,{className:"max-w-sm",children:[t.jsxs(g,{children:[t.jsxs(b,{className:"flex items-center gap-2",children:[t.jsx(re,{className:"h-5 w-5 text-emerald-600"}),"Rapport envoyé"]}),t.jsx(v,{children:us})]}),ms&&(()=>{const e=Ee.find(e=>e.id===ms.client_id),n=String(ce?.name??"VDK Chauffconfort SRL"),a=t.jsx(p,{intervention:ms,photos:qn[ms.id]??[],clientName:e?.name??"Client",company:ce??{},template:Ve(ms.report_type,Sa),options:za,headerInfo:Ra}),s=`rapport-signe-${ms.number??ms.id}.pdf`;return t.jsxs("div",{className:"space-y-2 border-t border-border pt-3",children:[t.jsxs("p",{className:"text-xs text-muted-foreground",children:["Rapport signé par ",ms.signed_by||e?.name||"le client"," : téléchargez le PDF ou envoyez-le directement."]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx(l,{document:a,fileName:s,children:t.jsxs(z,{variant:"outline",size:"sm",children:[t.jsx(_e,{}),"Exporter le PDF signé"]})}),t.jsx(y,{document:a,fileName:s,folder:`interventions/${ms.id}`,subject:`Rapport dâintervention ${ms.number??""} â ${n}`.trim(),message:Q({number:ms.number,companyName:n,clientName:e?.name??"Client",date:ms.intervention_date}),email:e?.email,label:"Envoyer au client",templateKind:"report",companyId:ce?.id,templateValues:{client:e?.name??"",numero:ms.number??"",entreprise:n,date:K(ms.intervention_date)},onSent:e=>{rr(ms,e)}})]})]})})(),t.jsx(j,{children:t.jsx(z,{type:"button",onClick:()=>{ps(""),xs(null)},children:"Fermer"})})]})}),t.jsx(h,{open:!!gs,onOpenChange:e=>{e||vs||$r()},children:t.jsxs(f,{className:"max-h-[90dvh] max-w-lg overflow-y-auto",children:[t.jsxs(g,{children:[t.jsx(b,{children:"Aperçu de lâe-mail â paiement reçu"}),t.jsx(v,{children:"Vérifiez ou modifiez lâobjet et le texte avant lâenvoi du rapport signé. Le modèle par défaut se règle dans Réglages â Modèles dâe-mail."})]}),t.jsxs("div",{className:"space-y-3 text-sm",children:[t.jsxs("p",{className:"text-muted-foreground",children:["Destinataire : ",t.jsx("span",{className:"text-foreground",children:gs?.to})," · PDF du rapport joint"]}),t.jsxs("div",{children:[t.jsx(R,{htmlFor:"email-subject",children:"Objet"}),t.jsx(A,{id:"email-subject",value:gs?.subject??"",onChange:e=>bs(t=>t&&{...t,subject:e.target.value}),className:"h-12 text-base sm:h-10 sm:text-sm"})]}),t.jsxs("div",{children:[t.jsx(R,{htmlFor:"email-body",children:"Message"}),t.jsx($,{id:"email-body",rows:9,value:gs?.body??"",onChange:e=>bs(t=>t&&{...t,body:e.target.value}),className:"text-base sm:text-sm"})]}),t.jsxs("div",{className:"border border-border bg-secondary/30 p-3",children:[t.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Aperçu"}),t.jsx("p",{className:"mt-1 font-medium",children:gs?.subject}),t.jsx("p",{className:"mt-2 whitespace-pre-wrap text-muted-foreground",children:gs?.body})]}),Rs&&t.jsx("p",{role:"alert",className:"border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:Rs})]}),t.jsxs(j,{children:[t.jsx(z,{type:"button",variant:"outline",onClick:$r,disabled:vs,children:"Ne pas envoyer"}),t.jsxs(z,{type:"button",onClick:()=>{(async()=>
1{if(gs){js(!0),$s("");try{const{data:e,error:t}=await ne.functions.invoke("send-document",{body:{to:gs.to,subject:gs.subject,message:gs.body,pdfUrl:gs.pdfUrl,companyId:gs.intervention.company_id,documentLabel:"rapport dâintervention",maintenanceType:/ramon/i.test(gs.intervention.service_type??"")?"ramonage":/entretien|chaudi/i.test(gs.intervention.service_type??"")?"entretien":void 0}});if(t||!e?.success){if(e?.skipped)throw new Error(e?.reason??"Les envois d'e-mails sont désactivés dans les réglages de l'entreprise.");throw new Error(t?.message??"Lâenvoi a échoué.")}await rr(gs.intervention,"e-mail"),$r()}catch(e){$s(e instanceof Error?e.message:"Lâe-mail nâa pas pu être envoyé.")}finally{js(!1)}}})()},disabled:vs||!gs?.subject.trim(),children:[t.jsx(be,{}),vs?"Envoiâ¦":"Envoyer le rapport"]})]})]})}),t.jsx(cn,{item:Ln,onClose:()=>Bn(null),onDone:()=>{se&&sr(se)}})]})}function gn({label:n,value:a,onChange:s,type:r="text",placeholder:i}){const o=e.useId();return t.jsxs("div",{className:"space-y-2",children:[t.jsx(R,{htmlFor:o,children:n}),t.jsx(A,{id:o,type:r,value:a,placeholder:i,onChange:e=>s(e.target.value)})]})}function bn({label:n,value:a,onChange:s,required:r=!1}){const i=e.useId();return t.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[t.jsx(R,{htmlFor:i,children:n}),t.jsx($,{id:i,required:r,value:a,onChange:e=>s(e.target.value),rows:4})]})}function vn(e,t){const n=($e[e]??[]).map(Pe);return t.filter(e=>n.includes(Pe(e.label))).sort((e,t)=>n.indexOf(Pe(e.label))-n.indexOf(Pe(t.label)))}function jn(e,t,n=[]){const a=n.flatMap(e=>st(e)?.catalogLabels.slice(0,1)??[]).map(Pe).map(e=>t.find(t=>Pe(t.label)===e)).find(Boolean)??vn(e.id,t)[0]??t.find(t=>Pe(t.label)===Pe(e.serviceType));return a?[{description:a.label,quantity:1,unit:a.unit,unit_price_cents:a.unit_price_cents,vat_rate:Number(a.vat_rate),discount_percent:0}]:[]}function _n(e){return/garantie/i.test(String(e.description??""))}function yn(e,t){if(t)return"";const n=e.filter(e=>String(e.description??"").trim());return n.length?n.reduce((e,t)=>e+Number(t.quantity||0)*Number(t.unit_price_cents||0),0)<=0&&!n.some(_n)?"Le total est à 0 â¬. Indiquez le prix de la prestation, ou cochez « Intervention sous garantie ».":"":"Ajoutez au moins une prestation avant de faire signer."}export{vn as catalogFor,fn as default,yn as reportPricingIssue};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.