@airporting/tech-app 0.0.153 → 0.0.155

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";(globalThis["chunk_tech_app"]=globalThis["chunk_tech_app"]||[]).push([["7915"],{3437:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{D:()=>CompanyLogo});var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(5893);var _mantine_core__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(207);const BASE_URL="https://s3.dualstack.eu-west-3.amazonaws.com/media.airporting/companies";function CompanyLogo({slug,updatedAt,size=20,...rest}){const base=`${BASE_URL}/${slug}.png`;const url=updatedAt?`${base}?v=${new Date(updatedAt).getTime()}`:base;return/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Image,{src:url,fallbackSrc:`${BASE_URL}/undefined.png`,alt:slug??"",w:size,h:size,fit:"contain",radius:"sm",style:{aspectRatio:1},...rest})}},1354:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{m:()=>PageHeader});var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(5893);var _mantine_core__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(207);var _tabler_icons_react__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(9632);var react__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(5850);function formatRelative(now,then){const seconds=Math.max(0,Math.floor((now-then)/1e3));if(seconds<5)return"\xe0 l’instant";if(seconds<60)return`il y a ${seconds}s`;const minutes=Math.floor(seconds/60);if(minutes<60)return`il y a ${minutes} min`;const hours=Math.floor(minutes/60);return`il y a ${hours} h`}function PageHeader({title,leading,badge,updatedAt,isFetching,isError,onRefresh,actions}){const[now,setNow]=(0,react__WEBPACK_IMPORTED_MODULE_3__.useState)(()=>Date.now());(0,react__WEBPACK_IMPORTED_MODULE_3__.useEffect)(()=>{if(!updatedAt)return;const id=window.setInterval(()=>setNow(Date.now()),1e3);return()=>window.clearInterval(id)},[updatedAt]);const relative=updatedAt?formatRelative(now,updatedAt):null;const color=isError?"orange":isFetching?"teal":"dimmed";return/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Group,{justify:"space-between",align:"center",mih:48,mb:"md",children:[/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Group,{gap:"sm",align:"center",children:[leading,/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Title,{order:2,children:title}),badge]}),/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Group,{gap:"sm",align:"center",children:[relative&&/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Text,{size:"xs",c:color,fw:isFetching?600:400,"data-testid":"page-header-freshness",children:isError?"\xe9chec maj":isFetching?"maj…":relative}),onRefresh&&/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Tooltip,{label:"Rafra\xeechir",children:/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.ActionIcon,{variant:"default",size:"md",onClick:onRefresh,loading:isFetching,"aria-label":"Refresh",children:/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_tabler_icons_react__WEBPACK_IMPORTED_MODULE_2__.IconRefresh,{size:16})})}),actions]})]})}},9781:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{h:()=>QuickBooksIcon});var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(5893);function QuickBooksIcon(props){const size=props.size??20;return/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("svg",{width:size,height:size,viewBox:"0 0 24 24",role:"img","aria-label":"QuickBooks",children:[/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)("title",{children:"QuickBooks"}),/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)("circle",{cx:"12",cy:"12",r:"12",fill:"#2CA01C"}),/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)("text",{x:"12",y:"16.5",textAnchor:"middle",fontSize:"12",fontWeight:"700",fill:"#ffffff",fontFamily:"Arial, Helvetica, sans-serif",children:"qb"})]})}},243:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{j:()=>logoDevUrl});const LOGO_DEV_TOKEN="pk_BVN4OQv0Qs-bnqjdIgTppg";function logoDevUrl(domain){return`https://img.logo.dev/${domain}?token=${LOGO_DEV_TOKEN}`}},7967:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,{default:()=>EtatSaisie});var jsx_runtime=__webpack_require__(5893);var consume_shared_module_default_react_strict_=__webpack_require__(5850);var providers=__webpack_require__(7034);var index_mjs_=__webpack_require__(207);var esm_index_mjs_=__webpack_require__(3863);var index_js_=__webpack_require__(6197);var useApi=__webpack_require__(4148);function useEtatSaisieLatest(){const api=(0,useApi.h)();return(0,index_js_.useQuery)({queryKey:["tech","etat-saisie","latest"],queryFn:async()=>(await api.etatSaisie.getLatestV1()).data,staleTime:6e5,refetchOnWindowFocus:false})}function useEtatSaisieRecompute(){const api=(0,useApi.h)();const qc=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async()=>(await api.etatSaisie.recomputeV1()).data,onSuccess:()=>qc.invalidateQueries({queryKey:["tech","etat-saisie","latest"]})})}var notifications_esm_index_mjs_=__webpack_require__(1455);class PartialMuteSaveError extends Error{saved;total;cause;constructor(saved,total,cause){super(`${saved}/${total} changements enregistr\xe9s avant l'\xe9chec`);this.name="PartialMuteSaveError";this.saved=saved;this.total=total;this.cause=cause}}function useSaveReconciliationMutes(){const api=(0,useApi.h)();const qc=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async changes=>{let saved=0;for(const change of changes){try{await api.etatSaisie.setReconciliationMuteV1({company_id:change.company_id,account_id:change.account_id,muted:change.muted})}catch(err){throw new PartialMuteSaveError(saved,changes.length,err)}saved+=1}return saved},onSuccess:async saved=>{notifications_esm_index_mjs_.notifications.show({title:"Suivi des rappros",message:saved>1?`${saved} changements enregistr\xe9s`:"Changement enregistr\xe9",color:"teal"});await Promise.all([qc.invalidateQueries({queryKey:["tech","etat-saisie","dossiers"]}),qc.invalidateQueries({queryKey:["tech","etat-saisie","latest"]})])},onError:async err=>{const partial=err instanceof PartialMuteSaveError?err:null;notifications_esm_index_mjs_.notifications.show({title:"Suivi des rappros",message:partial?`${partial.saved} changement(s) sur ${partial.total} enregistr\xe9(s), les suivants ont \xe9chou\xe9`:err?.error?.error??err?.message??"Les changements n'ont pas \xe9t\xe9 enregistr\xe9s",color:"red"});if(partial&&partial.saved>0)await Promise.all([qc.invalidateQueries({queryKey:["tech","etat-saisie","dossiers"]}),qc.invalidateQueries({queryKey:["tech","etat-saisie","latest"]})])}})}var tabler_icons_react_mjs_=__webpack_require__(9632);function DetailTableInner(props){const{columns,rows,onRowClick,rowKey,maxHeight}=props;const[sortKey,setSortKey]=(0,consume_shared_module_default_react_strict_.useState)(null);const[asc,setAsc]=(0,consume_shared_module_default_react_strict_.useState)(false);const sortColumn=sortKey?columns.find(c=>c.key===sortKey):void 0;const sorted=[...rows].sort((a,b)=>{if(!sortKey)return 0;const av=sortColumn?.sortValue?sortColumn.sortValue(a):a[sortKey];const bv=sortColumn?.sortValue?sortColumn.sortValue(b):b[sortKey];if("number"==typeof av&&"number"==typeof bv)return asc?av-bv:bv-av;return asc?String(av).localeCompare(String(bv)):String(bv).localeCompare(String(av))});const toggle=k=>{if(sortKey===k)setAsc(v=>!v);else{setSortKey(k);setAsc(false)}};const fmt=(v,numeric)=>{if(numeric&&"number"==typeof v)return v.toLocaleString("fr-FR",{minimumFractionDigits:0,maximumFractionDigits:0});if("boolean"==typeof v)return v?"✓":"";if(null==v)return"-";if("object"==typeof v)return"-";return String(v)};const table=/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{striped:true,highlightOnHover:true,withTableBorder:true,stickyHeader:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Thead,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tr,{children:columns.map(c=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{onClick:()=>toggle(c.key),style:{cursor:"pointer"},children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:4,wrap:"nowrap",component:"span",display:"inline-flex",children:[/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:c.label}),c.hint?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:c.hint,multiline:true,w:260,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)("span",{style:{display:"inline-flex",alignItems:"center"},onClick:e=>e.stopPropagation(),children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconInfoCircle,{size:13})})}):null,/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:sortKey===c.key?asc?" ▲":" ▼":""})]})},c.key))})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:0===sorted.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tr,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{colSpan:columns.length,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",ta:"center",children:"Aucune ligne"})})}):sorted.map((row,i)=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tr,{onClick:onRowClick?()=>onRowClick(row):void 0,style:onRowClick?{cursor:"pointer"}:void 0,children:columns.map(c=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{style:c.numeric?{textAlign:"right",fontVariantNumeric:"tabular-nums"}:void 0,children:c.render?c.render(row):fmt(row[c.key],c.numeric)},c.key))},rowKey?rowKey(row,i):i))})]});if(void 0===maxHeight)return table;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.ScrollContainer,{minWidth:0,mah:maxHeight,type:"native",children:table})}const DetailTable=/*#__PURE__*/(0,consume_shared_module_default_react_strict_.memo)(DetailTableInner);function useDossiers(){const api=(0,useApi.h)();return(0,index_js_.useQuery)({queryKey:["tech","etat-saisie","dossiers"],queryFn:async()=>(await api.etatSaisie.getDossiersV1()).data,refetchOnWindowFocus:true})}function useSaveDossierAssignments(){const api=(0,useApi.h)();const qc=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async changes=>{for(const change of changes){if(null!=change.managed)await api.etatSaisie.setManagedV1({id:change.id},{managed:change.managed});if(void 0!==change.notionUserId)await api.etatSaisie.setResponsableV1({id:change.id},{notion_user_id:change.notionUserId})}return changes.length},onSuccess:()=>{qc.invalidateQueries({queryKey:["tech","etat-saisie","dossiers"]});qc.invalidateQueries({queryKey:["tech","etat-saisie","latest"]})}})}var logoDev=__webpack_require__(243);var QuickBooksIcon=__webpack_require__(9781);const PROVIDER_DOMAIN={pennylane:"pennylane.com",zohobooks:"zoho.com",xero:"xero.com",odoo:"odoo.com"};function ProviderIcon(props){const{provider}=props;if(!provider)return null;if("quickbooks"===provider)return/*#__PURE__*/(0,jsx_runtime.jsx)(QuickBooksIcon.h,{size:20});const domain=PROVIDER_DOMAIN[provider];if(!domain)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{size:"sm",variant:"light",color:"gray",title:provider,children:provider.slice(0,2).toUpperCase()});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Image,{src:(0,logoDev.j)(domain),alt:provider,title:provider,w:20,h:20,fit:"contain",radius:"sm",style:{aspectRatio:1}})}function DossiersTab(){const isMobile=(0,esm_index_mjs_.useMediaQuery)("(max-width: 48em)",false);const dossiers=useDossiers();const save=useSaveDossierAssignments();const[filter,setFilter]=(0,consume_shared_module_default_react_strict_.useState)("");const[draft,setDraft]=(0,consume_shared_module_default_react_strict_.useState)({});(0,consume_shared_module_default_react_strict_.useEffect)(()=>{if(dossiers.data)setDraft({})},[dossiers.data]);const managedOf=dossier=>draft[dossier.airporting_id]?.managed??dossier.managed;const responsableIdOf=dossier=>{const pending=draft[dossier.airporting_id];if(pending&&"responsableId"in pending)return pending.responsableId??null;return dossier.responsable?dossier.responsable.id:null};const setManagedDraft=(dossier,managed)=>setDraft(current=>({...current,[dossier.airporting_id]:{...current[dossier.airporting_id],managed}}));const setResponsableDraft=(dossier,responsableId)=>setDraft(current=>({...current,[dossier.airporting_id]:{...current[dossier.airporting_id],responsableId}}));const options=dossiers.data?.responsable_options??[];const optionData=options.map(u=>({value:String(u.id),label:u.name}));const avatarOf=responsableId=>null==responsableId?void 0:options.find(u=>u.id===responsableId)?.avatar_url;const all=dossiers.data?.dossiers??[];const rows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const needle=filter.trim().toLowerCase();const filtered=needle?all.filter(dossier=>dossier.display_name.toLowerCase().includes(needle)||dossier.slug.toLowerCase().includes(needle)):all;return[...filtered].sort((a,b)=>a.display_name.localeCompare(b.display_name))},[all,filter]);const changes=all.flatMap(dossier=>{const change={id:dossier.airporting_id};const managed=managedOf(dossier);if(managed!==dossier.managed)change.managed=managed;const responsableId=responsableIdOf(dossier);const current=dossier.responsable?dossier.responsable.id:null;if(responsableId!==current)change.notionUserId=responsableId;return null!=change.managed||void 0!==change.notionUserId?[change]:[]});if(dossiers.isError)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"red",mt:"md",children:"Erreur de chargement des dossiers."});const saveButton=/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{size:"xs",loading:save.isPending,disabled:0===changes.length,onClick:()=>save.mutate(changes),children:changes.length>0?`Enregistrer (${changes.length})`:"Enregistrer"});return/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{mb:"md",justify:"space-between",wrap:"wrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{placeholder:"Filtrer par nom ou slug",value:filter,onChange:event=>setFilter(event.currentTarget.value),w:isMobile?"100%":320}),saveButton]}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:"sm",children:0===rows.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",ta:"center",py:"xl",children:"Aucun dossier"}):rows.map(dossier=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Card,{withBorder:true,p:"sm",radius:"md",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:dossier.provider}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:dossier.display_name}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:dossier.slug})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{checked:managedOf(dossier),onChange:event=>setManagedDraft(dossier,event.currentTarget.checked)})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{placeholder:"Responsable",data:optionData,value:null==responsableIdOf(dossier)?null:String(responsableIdOf(dossier)),onChange:v=>setResponsableDraft(dossier,v?Number(v):null),searchable:true,clearable:true,leftSection:avatarOf(responsableIdOf(dossier))?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:avatarOf(responsableIdOf(dossier)),size:20,radius:"xl"}):void 0})]})},`${dossier.airporting_id}:${dossier.provider}`))}):/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{striped:true,highlightOnHover:true,withTableBorder:true,stickyHeader:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Thead,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Source"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Dossier"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"G\xe9r\xe9"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Responsable"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:0===rows.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tr,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{colSpan:4,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",ta:"center",children:"Aucun dossier"})})}):rows.map(dossier=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:dossier.provider})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:dossier.display_name}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{checked:managedOf(dossier),onChange:event=>setManagedDraft(dossier,event.currentTarget.checked)})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{placeholder:"—",data:optionData,value:null==responsableIdOf(dossier)?null:String(responsableIdOf(dossier)),onChange:v=>setResponsableDraft(dossier,v?Number(v):null),searchable:true,clearable:true,w:220,leftSection:avatarOf(responsableIdOf(dossier))?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:avatarOf(responsableIdOf(dossier)),size:20,radius:"xl"}):void 0})})]},`${dossier.airporting_id}:${dossier.provider}`))})]})]})}const MAX_STARS=5;const REASON_BADGES={vide:{label:"Vide",color:"gray"},erreur_scan:{label:"Erreur de scan",color:"red"},couverture_connecteur:{label:"Non not\xe9",color:"gray"}};const VERDICT_STYLE={parfait:{color:"green",symbol:"✓"},vert:{color:"green",symbol:"✓"},orange:{color:"orange",symbol:"!"},rouge:{color:"red",symbol:"✕"},non_mesurable:{color:"gray",symbol:"\xb7"}};function starColor(score){if(score>=4)return"var(--mantine-color-green-6)";if(score>=3)return"var(--mantine-color-yellow-6)";if(score>=2)return"var(--mantine-color-orange-6)";return"var(--mantine-color-red-6)"}function Stars(props){const color=starColor(props.score);const items=[];for(let i=1;i<=MAX_STARS;i+=1)if(props.score>=i)items.push(/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconStarFilled,{size:13,color:color},i));else if(props.score>=i-.5)items.push(/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconStarHalfFilled,{size:13,color:color},i));else items.push(/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconStar,{size:13,color:"var(--mantine-color-dark-2)"},i));return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:1,wrap:"nowrap",children:items})}function ControlList(props){const controls=props.row.score_controls??[];if(0===controls.length)return null;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:4,children:controls.map(c=>{const style=VERDICT_STYLE[c.verdict]??VERDICT_STYLE.non_mesurable;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:style.color,fw:700,w:12,children:style.symbol}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",children:c.label}),c.detail?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:c.detail}):null]})]},c.key)})})}function ScoreStars(props){const{row}=props;if(null==row.score){const badge=row.score_reason?REASON_BADGES[row.score_reason]:void 0;const fallback=badge??{label:"Non not\xe9",color:"gray"};const controls=row.score_controls??[];const content=/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{size:"xs",color:fallback.color,variant:"light",children:fallback.label});if("couverture_connecteur"!==row.score_reason)return content;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard,{width:300,shadow:"md",openDelay:150,withinPortal:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Target,{children:/*#__PURE__*/(0,jsx_runtime.jsx)("span",{style:{cursor:"help"},children:content})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard.Dropdown,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",fw:600,mb:6,children:"Pas assez de contr\xf4les mesurables"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",c:"dimmed",mb:6,children:["Ce connecteur n’expose pas les comptes n\xe9cessaires. Une note fond\xe9e sur ",controls.filter(c=>"non_mesurable"!==c.verdict).length," ","contr\xf4le(s) sur ",MAX_STARS," ne voudrait rien dire."]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ControlList,{row:row})]})]})}const stale=null!=row.refreshed_at&&null!=row.reconciliation_refresh_date&&row.refreshed_at<row.reconciliation_refresh_date;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard,{width:320,shadow:"md",openDelay:150,withinPortal:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Target,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:6,wrap:"nowrap",style:{cursor:"help"},children:/*#__PURE__*/(0,jsx_runtime.jsx)(Stars,{score:row.score})})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard.Dropdown,{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",mb:6,wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(Stars,{score:row.score}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",fw:600,children:[row.score.toLocaleString("fr-FR")," / ",MAX_STARS,row.score_label?` \xb7 ${row.score_label}`:""]})]}),row.score_capped_reason?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"orange",mb:6,children:row.score_capped_reason}):null,stale?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"yellow",mb:6,children:"Chiffres repris d’un calcul ant\xe9rieur."}):null,/*#__PURE__*/(0,jsx_runtime.jsx)(ControlList,{row:row})]})]})}function scoreBucket(row){if(null==row.score)return"non_note";if(row.score>=4)return"bon";if(row.score>=3)return"moyen";return"faible"}function ManagedBadge(props){const{managed}=props;if(!managed)return null;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Image,{src:(0,logoDev.j)("airporting.com"),alt:"G\xe9r\xe9 par Airporting",title:"G\xe9r\xe9 par Airporting",w:18,h:18,fit:"contain",radius:"sm",style:{aspectRatio:1}})}const BANK_DOMAINS=[["bnp paribas","bnpparibas.com"],["societe generale","societegenerale.fr"],["qonto","qonto.com"],["revolut","revolut.com"],["stripe","stripe.com"],["wise","wise.com"],["transferwise","wise.com"],["ibanfirst","ibanfirst.com"],["credit agricole","credit-agricole.fr"],["credit mutuel","creditmutuel.fr"],["banque populaire","banquepopulaire.fr"],["caisse d","caisse-epargne.fr"],["american express","americanexpress.com"],["amex","americanexpress.com"],["paypal","paypal.com"],["hsbc","hsbc.com"],["pennylane","pennylane.com"],["mercury","mercury.com"],["lcl","lcl.fr"],["boursorama","boursorama.com"],["bpce","bpce.fr"]];function normalize(value){return value.toLowerCase().normalize("NFD").replace(/\p{Diacritic}/gu,"")}function BankLogo(props){const{label,size=20}=props;const normalized=label?normalize(label):"";const match=BANK_DOMAINS.find(([needle])=>normalized.includes(needle));if(!match)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,children:"\uD83C\uDFE6"});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Image,{src:(0,logoDev.j)(match[1]),alt:label??"",title:label??"",w:size,h:size,fit:"contain",radius:"sm",style:{aspectRatio:1}})}var CompanyLogo=__webpack_require__(3437);var PageHeader=__webpack_require__(1354);const recoAccountLabel=row=>{const account=(row.account_name??"").trim();const bank=(row.bank_label??"").trim();if(""!==account&&""!==bank&&account!==bank)return`${bank} : ${account}`;return""!==account?account:""!==bank?bank:"Banque"};const muteKey=(companyId,accountId)=>`${companyId}:${accountId}`;function drillCategoryLabel(category){if("471"===category)return"D\xe9tail 471";if("58"===category)return"D\xe9tail 58";if("supplier"===category)return"Fournisseurs d\xe9biteurs 401";if("customer"===category)return"Clients cr\xe9diteurs 411";if("factor"===category)return"Cr\xe9ances c\xe9d\xe9es au factor 4116";if("reconciliation"===category)return"Rappros bancaires";return null}function syncBadge(isoDate){if(!isoDate)return null;const days=Math.floor((Date.now()-new Date(isoDate).getTime())/864e5);let color="green";if(days>10)color="red";else if(days>4)color="orange";return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Badge,{ml:6,size:"xs",color:color,variant:"light",children:[days,"j"]})}function isStaleRefresh(refreshedAt,computedAt){if(!refreshedAt)return false;const refreshedDay=refreshedAt.slice(0,10);const referenceDay=(computedAt??new Date().toISOString()).slice(0,10);return refreshedDay<referenceDay}function refreshKoBadge(refreshedAt,computedAt){if(!isStaleRefresh(refreshedAt,computedAt))return null;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:`Chiffres du ${formatDate(refreshedAt?.slice(0,10))} \u{2014} refresh KO ce run`,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{ml:6,size:"xs",color:"yellow",variant:"light",children:"refresh KO"})})}function factorKeur(row){const v=row.total_factor_eur??0;return 0===v?"—":formatKeur(v,row.currency)}function withDossierFilter(rows,dossier){if(!dossier)return rows;return rows.filter(r=>r.dossier===dossier)}function withManagedFilter(rows,managedOnly){if(!managedOnly)return rows;return rows.filter(r=>true===r.managed)}const NO_RESPONSABLE="__none__";function withResponsableFilter(rows,responsable){if(!responsable)return rows;if(responsable===NO_RESPONSABLE)return rows.filter(r=>null==r.responsable);return rows.filter(r=>String(r.responsable?.id)===responsable)}function withScoreFilter(rows,bucket){if("all"===bucket)return rows;return rows.filter(r=>scoreBucket(r)===bucket)}function formatCurrency(value,currency){if(null==value)return"—";try{return value.toLocaleString("fr-FR",{style:"currency",currency:currency||"EUR",minimumFractionDigits:0,maximumFractionDigits:0})}catch{return`${Math.round(value).toLocaleString("fr-FR")} ${currency}`}}function formatNumber(value){if(null==value)return"—";return value.toLocaleString("fr-FR")}function formatDate(value){if(!value)return"—";return value.split("-").reverse().join("/")}function currencySymbol(code){const currency=code||"EUR";try{const parts=new Intl.NumberFormat("fr-FR",{style:"currency",currency}).formatToParts(0);return parts.find(part=>"currency"===part.type)?.value??currency}catch{return currency}}function formatKeur(value,currency){if(null==value)return"—";const keur=(Math.round(value/1e3)||0).toLocaleString("fr-FR");return`${keur} k${currencySymbol(currency)}`}function sumBy(rows,pick){return rows.reduce((acc,row)=>acc+(pick(row)??0),0)}function DrillSectionTitle(props){const isSample=null!=props.total&&props.count>0&&Math.abs(props.visibleSum-props.total)>.5;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Title,{order:5,mb:6,children:[props.label," (",props.count,isSample?" affich\xe9s":"",")",null!=props.total?` \xb7 total ${formatCurrency(props.total,props.currency)}`:""]})}function ClickableMetricValue(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,style:{cursor:"pointer",display:"block",width:"100%"},onClick:e=>{e.stopPropagation();props.onClick()},children:props.value})}function updateDateParts(row){return[{label:"Derni\xe8re \xe9criture",iso:row.last_entry_date},{label:"Dernier import GLA",iso:row.gla_last_sync_date?.slice(0,10)??null},{label:"Rappros / factures",iso:row.reconciliation_refresh_date?.slice(0,10)??null}]}function oldestUpdateDate(parts){const present=parts.map(p=>p.iso).filter(v=>null!=v);if(0===present.length)return null;return present.reduce((a,b)=>a<b?a:b)}function UpdateDateCell(props){const parts=updateDateParts(props.row);const oldest=oldestUpdateDate(parts);if(null==oldest)return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"});return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard,{withArrow:true,shadow:"md",openDelay:120,position:"bottom-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Target,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{span:true,style:{cursor:"default"},children:[formatDate(oldest),syncBadge(oldest),refreshKoBadge(props.row.refreshed_at,props.computedAt),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"dimmed",children:" ▾"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Dropdown,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:4,children:parts.map(p=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",gap:"lg",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:p.label}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",children:p.iso?formatDate(p.iso):"—"})]},p.label))})})]})}function clickableCardStyle(clickable){return clickable?{cursor:"pointer"}:void 0}function MobileMetricGrid({metrics}){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SimpleGrid,{cols:2,spacing:"xs",children:metrics.map(metric=>/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:metric.label}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",fw:700,c:metric.color,lineClamp:2,children:metric.value})]},metric.label))})}function MobileAccountingList(props){const{rows,emptyLabel="Aucune ligne",getKey,renderHeader,getMetrics,onRowClick}=props;if(0===rows.length)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",ta:"center",py:"xl",children:emptyLabel});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:"sm",children:rows.map((row,index)=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Card,{withBorder:true,p:"sm",radius:"md",onClick:onRowClick?()=>onRowClick(row):void 0,style:clickableCardStyle(!!onRowClick),children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[renderHeader(row),/*#__PURE__*/(0,jsx_runtime.jsx)(MobileMetricGrid,{metrics:getMetrics(row)})]})},getKey(row,index)))})}function MobileDossierLineList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:row=>props.onDrill(row),getKey:row=>`${row.source}:${row.dossier}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",align:"center",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsx)(CompanyLogo.D,{slug:row.slug,updatedAt:row.logo_updated_at,size:24}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:row.dossier}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:6,wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.responsable?.name??"Sans responsable"})]})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ScoreStars,{row:row})]}),getMetrics:row=>[{label:"471",value:/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(row.solde_attente_eur,row.currency),onClick:()=>props.onDrill(row,"471")})},{label:"58",value:/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(row.solde_virements_eur,row.currency),onClick:()=>props.onDrill(row,"58")})},{label:"401",value:/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(row.total_fournisseurs_eur,row.currency),onClick:()=>props.onDrill(row,"supplier")})},{label:"411",value:/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(row.total_clients_eur,row.currency),onClick:()=>props.onDrill(row,"customer")})},{label:"Cr\xe9ances c\xe9d\xe9es",value:/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:factorKeur(row),onClick:()=>props.onDrill(row,"factor")})},{label:"Date mise \xe0 jour",value:(()=>{const oldest=oldestUpdateDate(updateDateParts(row));if(null==oldest)return"—";return/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[formatDate(oldest),syncBadge(oldest),refreshKoBadge(row.refreshed_at,props.computedAt)]})})()},{label:"Rappro",value:(()=>{const text="pennylane"!==row.source?"—":row.last_reconciliation_date?formatDate(row.last_reconciliation_date):props.dossiersWithActiveReco.has(row.dossier)?"jamais":"—";if("—"===text)return text;return/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:text,onClick:()=>props.onDrill(row,"reconciliation")})})(),color:"pennylane"===row.source&&null==row.last_reconciliation_date&&props.dossiersWithActiveReco.has(row.dossier)?"red":void 0},{label:"Factures fournisseurs \xe0 traiter (compta)",value:"pennylane"===row.source?formatNumber(row.pending_supplier_invoices):"—"},{label:"Factures fournisseurs \xe0 traiter (gestion)",value:"pennylane"===row.source?formatNumber(row.management_supplier_invoices_inbox):"—"}]})}function MobileSuspenseList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:(row,index)=>`${row.dossier}:${row.date}:${row.numero_piece??index}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:row.dossier}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:2,children:row.libelle_ecriture??row.libelle_compte??"Sans libell\xe9"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Solde net",value:formatCurrency(row.solde_net)},{label:"Date",value:formatDate(row.date)},{label:"Compte",value:row.numero_compte??"—"},{label:"Pi\xe8ce",value:row.numero_piece??"—"}]})}function MobileSupplierList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:(row,index)=>`${row.dossier}:${row.fournisseur}:${index}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:row.fournisseur}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.dossier})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Solde d\xe9biteur",value:formatCurrency(row.solde_debiteur_eur)},{label:"\xc9critures",value:formatNumber(row.nb_ecritures)},{label:"Devise",value:row.devise||"—"}]})}function MobileCustomerList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:(row,index)=>`${row.dossier}:${row.client}:${index}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:row.client}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.dossier})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Solde cr\xe9diteur",value:formatCurrency(row.solde_crediteur_eur)},{label:"\xc9critures",value:formatNumber(row.nb_ecritures)},{label:"Devise",value:row.devise||"—"}]})}function MobileReconciliationList({rows,onToggleMute}){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:rows,getKey:row=>`${row.airporting_company_id}:${row.account_id}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"center",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(BankLogo,{label:row.bank_label,size:24}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,c:row.muted?"dimmed":void 0,children:recoAccountLabel(row)})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{size:"sm",checked:!row.muted,label:row.muted?"non suivi":"suivi",onLabel:"suivi",onChange:e=>onToggleMute({company_id:row.airporting_company_id,account_id:row.account_id,muted:!e.currentTarget.checked})})]}),getMetrics:row=>[{label:"Dernier rappro",value:row.muted?"non suivi":row.last_reconciled_period_end?formatDate(row.last_reconciled_period_end):"jamais",color:row.muted?"dimmed":row.last_reconciled_period_end?void 0:"red"}]})}function MobileTopSuspenseList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:row=>`471:${row.rank}:${row.dossier}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:["#",row.rank," ",row.dossier]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.top_libelle??"Sans libell\xe9"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Solde 471",value:formatCurrency(row.solde_eur)},{label:"\xc9critures",value:formatNumber(row.nb_ecritures)},{label:"Top montant",value:formatCurrency(row.top_montant)}]})}function MobileTopSupplierList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:row=>`401:${row.rank}:${row.dossier}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:["#",row.rank," ",row.dossier]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.top_nom??"Sans fournisseur"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Total d\xe9biteur",value:formatCurrency(row.total_eur)},{label:"Fournisseurs",value:formatNumber(row.nb_fournisseurs)},{label:"Top montant",value:formatCurrency(row.top_montant)}]})}function MobileTopCustomerList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:row=>`411:${row.rank}:${row.dossier}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:["#",row.rank," ",row.dossier]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.top_nom??"Sans client"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Total cr\xe9diteur",value:formatCurrency(row.total_eur)},{label:"Clients",value:formatNumber(row.nb_clients)},{label:"Top montant",value:formatCurrency(row.top_montant)}]})}function EtatSaisieApp(){const isMobile=(0,esm_index_mjs_.useMediaQuery)("(max-width: 48em)",false);const latest=useEtatSaisieLatest();const recompute=useEtatSaisieRecompute();const saveReconciliationMutes=useSaveReconciliationMutes();const[muteDraft,setMuteDraft]=(0,consume_shared_module_default_react_strict_.useState)(new Map);const[tab,setTab]=(0,consume_shared_module_default_react_strict_.useState)("resume");const[selectedDossier,setSelectedDossier]=(0,consume_shared_module_default_react_strict_.useState)(null);const[managedOnly,setManagedOnly]=(0,consume_shared_module_default_react_strict_.useState)(true);const[statusFilter,setStatusFilter]=(0,consume_shared_module_default_react_strict_.useState)("all");const[selectedResponsable,setSelectedResponsable]=(0,consume_shared_module_default_react_strict_.useState)(null);const[drillDossier,setDrillDossier]=(0,consume_shared_module_default_react_strict_.useState)(null);const[drillProvider,setDrillProvider]=(0,consume_shared_module_default_react_strict_.useState)(null);const[drillCategory,setDrillCategory]=(0,consume_shared_module_default_react_strict_.useState)(null);const d=latest.data;const allDossiers=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{if(!d?.available)return[];const set=new Set;for(const r of d.suspense_rows??[])set.add(r.dossier);for(const r of d.supplier_rows??[])set.add(r.dossier);for(const r of d.customer_rows??[])set.add(r.dossier);for(const r of d.dossier_lines??[])set.add(r.dossier);for(const r of d.reconciliation_rows??[])set.add(r.dossier);for(const r of d.summary?.top_5_suspense??[])set.add(r.dossier);for(const r of d.summary?.top_5_supplier_debtors??[])set.add(r.dossier);for(const r of d.summary?.top_5_customer_creditors??[])set.add(r.dossier);return[...set].sort()},[d]);const responsableOptions=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const byId=new Map;let hasNone=false;for(const line of d?.dossier_lines??[])if(line.responsable)byId.set(line.responsable.id,line.responsable.name);else hasNone=true;const options=[...byId.entries()].map(([id,name])=>({value:String(id),label:name})).sort((a,b)=>a.label.localeCompare(b.label));if(hasNone)options.push({value:NO_RESPONSABLE,label:"Sans responsable"});return options},[d]);const dossiersWithActiveReco=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const set=new Set;for(const r of d?.reconciliation_rows??[])if(!r.muted)set.add(r.dossier);return set},[d]);const openDrill=(0,consume_shared_module_default_react_strict_.useCallback)((row,category=null)=>{setDrillDossier(row.dossier);setDrillProvider(row.source);setDrillCategory(category)},[]);const closeDrill=(0,consume_shared_module_default_react_strict_.useCallback)(()=>{setDrillDossier(null);setDrillProvider(null);setDrillCategory(null);setMuteDraft(new Map)},[]);const unifiedCols=(0,consume_shared_module_default_react_strict_.useMemo)(()=>buildUnifiedCols(d?.computed_at,openDrill,dossiersWithActiveReco),[d?.computed_at,openDrill,dossiersWithActiveReco]);const drillData=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{if(!drillDossier||!d?.available)return null;const scoped=rows=>(rows??[]).filter(r=>r.dossier===drillDossier&&r.source===drillProvider);const reconciliation=scoped(d.reconciliation_rows).sort((a,b)=>{const av=a.last_reconciled_period_end??"0000-00-00";const bv=b.last_reconciled_period_end??"0000-00-00";return av.localeCompare(bv)});const lines=(d.dossier_lines??[]).filter(l=>l.dossier===drillDossier&&l.source===drillProvider);const sumLines=pick=>lines.reduce((acc,l)=>acc+(pick(l)??0),0);return{reconciliation,suspense:scoped(d.suspense_rows),internalTransfers:scoped(d.internal_transfer_rows),supplier:scoped(d.supplier_rows),customer:scoped(d.customer_rows),factor:scoped(d.factor_rows??[]),currency:lines[0]?.currency??null,totals:{suspense:sumLines(l=>l.solde_attente_eur),internalTransfers:sumLines(l=>l.solde_virements_eur),supplier:sumLines(l=>l.total_fournisseurs_eur),customer:sumLines(l=>l.total_clients_eur),factor:sumLines(l=>l.total_factor_eur??0)}}},[drillDossier,drillProvider,d]);const reconciliationRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const rows=drillData?.reconciliation??[];if(0===muteDraft.size)return rows;return rows.map(row=>{const draft=muteDraft.get(muteKey(row.airporting_company_id,row.account_id));return void 0===draft?row:{...row,muted:draft}})},[drillData,muteDraft]);const onToggleMute=(0,consume_shared_module_default_react_strict_.useCallback)(({company_id,account_id,muted})=>{setMuteDraft(current=>{const next=new Map(current);const key=muteKey(company_id,account_id);const server=(drillData?.reconciliation??[]).find(row=>row.airporting_company_id===company_id&&row.account_id===account_id);if(server&&server.muted===muted)next.delete(key);else next.set(key,muted);return next})},[drillData]);const drillRecoCols=(0,consume_shared_module_default_react_strict_.useMemo)(()=>buildDrillRecoCols(onToggleMute),[onToggleMute]);const pendingMutes=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const changes=[];for(const[key,muted]of muteDraft){const[companyId,accountId]=key.split(":");changes.push({company_id:Number(companyId),account_id:Number(accountId),muted})}return changes},[muteDraft]);const summaryRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withScoreFilter(withResponsableFilter(withManagedFilter(withDossierFilter(d?.dossier_lines??[],selectedDossier),managedOnly),selectedResponsable),statusFilter),[d,selectedDossier,managedOnly,selectedResponsable,statusFilter]);const scoreTiles=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const base=withResponsableFilter(withManagedFilter(withDossierFilter(d?.dossier_lines??[],selectedDossier),managedOnly),selectedResponsable);const count=bucket=>base.filter(r=>scoreBucket(r)===bucket).length;return[{key:"all",label:"Dossiers",value:base.length,color:void 0},{key:"bon",label:"4 \xe0 5 \xe9toiles",value:count("bon"),color:"green"},{key:"moyen",label:"3 \xe9toiles",value:count("moyen"),color:"yellow"},{key:"faible",label:"1 \xe0 2 \xe9toiles",value:count("faible"),color:"red"},{key:"non_note",label:"Non not\xe9s",value:count("non_note"),color:"gray"}]},[d,selectedDossier,managedOnly,selectedResponsable]);const topSuspenseRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withDossierFilter(d?.summary?.top_5_suspense??[],selectedDossier),[d,selectedDossier]);const topSupplierRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withDossierFilter(d?.summary?.top_5_supplier_debtors??[],selectedDossier),[d,selectedDossier]);const topCustomerRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withDossierFilter(d?.summary?.top_5_customer_creditors??[],selectedDossier),[d,selectedDossier]);const suspenseRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withManagedFilter(withDossierFilter(d?.suspense_rows??[],selectedDossier),managedOnly),[d,selectedDossier,managedOnly]);const internalTransferRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withManagedFilter(withDossierFilter(d?.internal_transfer_rows??[],selectedDossier),managedOnly),[d,selectedDossier,managedOnly]);const supplierRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withManagedFilter(withDossierFilter(d?.supplier_rows??[],selectedDossier),managedOnly),[d,selectedDossier,managedOnly]);const customerRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withManagedFilter(withDossierFilter(d?.customer_rows??[],selectedDossier),managedOnly),[d,selectedDossier,managedOnly]);return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Container,{fluid:true,my:isMobile?0:"md",px:isMobile?12:void 0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(PageHeader.m,{title:"Accounting",updatedAt:d?.computed_at?new Date(d.computed_at).getTime():latest.dataUpdatedAt,isFetching:latest.isFetching,isError:latest.isError,onRefresh:()=>latest.refetch(),actions:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{loading:recompute.isPending,onClick:()=>recompute.mutate(),variant:"light",size:isMobile?"xs":"sm",children:"Recalculer"})}),d&&!d.available?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",children:"Aucun snapshot disponible — lancez \xab Recalculer \xbb ou attendez le run nocturne."}):/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{mb:"md",align:"end",gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"Focus dossier",placeholder:"Tous les dossiers",data:allDossiers.map(dos=>({value:dos,label:dos})),value:selectedDossier,onChange:setSelectedDossier,searchable:true,clearable:true,w:isMobile?"100%":320}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"Responsable",placeholder:"Tous les responsables",data:responsableOptions,value:selectedResponsable,onChange:setSelectedResponsable,searchable:true,clearable:true,w:isMobile?"100%":240}),(selectedDossier||selectedResponsable)&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",onClick:()=>{setSelectedDossier(null);setSelectedResponsable(null)},w:isMobile?"100%":void 0,children:"R\xe9initialiser"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SegmentedControl,{value:managedOnly?"managed":"all",onChange:v=>setManagedOnly("managed"===v),data:[{label:"G\xe9r\xe9s",value:"managed"},{label:"Tous",value:"all"}],w:isMobile?"100%":void 0})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Tabs,{value:tab,onChange:setTab,children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Tabs.List,{style:isMobile?{flexWrap:"nowrap",overflowX:"auto",overflowY:"hidden"}:void 0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Tab,{value:"resume",children:"R\xe9sum\xe9"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Tab,{value:"dossiers",children:"Dossiers"})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Tabs.Panel,{value:"resume",pt:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SimpleGrid,{cols:isMobile?2:5,mb:"md",spacing:"sm",children:scoreTiles.map(tile=>{const active=statusFilter===tile.key;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Card,{withBorder:active,style:{cursor:"pointer",borderColor:active?"var(--mantine-color-blue-5)":void 0},onClick:()=>setStatusFilter(tile.key),children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:tile.label}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"xl",c:tile.color,children:tile.value})]},tile.key)})}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileDossierLineList,{rows:summaryRows,onDrill:openDrill,computedAt:d?.computed_at,dossiersWithActiveReco:dossiersWithActiveReco}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{maxHeight:"calc(100vh - 320px)",columns:unifiedCols,rows:summaryRows,onRowClick:openDrill,rowKey:r=>`${r.source}:${r.dossier}`})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"top5",pt:"md",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"lg",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:4,mb:"sm",children:"Top 5 comptes d'attente (471)"}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileTopSuspenseList,{rows:topSuspenseRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:TOP_SUSPENSE_COLS,rows:topSuspenseRows,onRowClick:openDrill})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:4,mb:"sm",children:"Top 5 fournisseurs d\xe9biteurs (401)"}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileTopSupplierList,{rows:topSupplierRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:TOP_SUPPLIER_COLS,rows:topSupplierRows,onRowClick:openDrill})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:4,mb:"sm",children:"Top 5 clients cr\xe9diteurs (411)"}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileTopCustomerList,{rows:topCustomerRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:TOP_CUSTOMER_COLS,rows:topCustomerRows,onRowClick:openDrill})]})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"s471",pt:"md",children:isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSuspenseList,{rows:suspenseRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:SUSPENSE_COLS,rows:suspenseRows,onRowClick:openDrill})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"s58",pt:"md",children:isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSuspenseList,{rows:internalTransferRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:SUSPENSE_COLS,rows:internalTransferRows,onRowClick:openDrill})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"s401",pt:"md",children:isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSupplierList,{rows:supplierRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:SUPPLIER_COLS,rows:supplierRows,onRowClick:openDrill})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"s411",pt:"md",children:isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileCustomerList,{rows:customerRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:CUSTOMER_COLS,rows:customerRows,onRowClick:openDrill})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"dossiers",pt:"md",children:/*#__PURE__*/(0,jsx_runtime.jsx)(DossiersTab,{})})]})]}),latest.isError?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"red",mt:"md",children:"Erreur de chargement."}):null,/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Drawer,{opened:!!drillDossier,onClose:closeDrill,position:isMobile?"bottom":"right",size:isMobile?"calc(100dvh - 88px)":"xl",title:drillDossier?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",align:"center",wrap:isMobile?"wrap":"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:isMobile?5:4,children:drillCategoryLabel(drillCategory)?`${drillCategoryLabel(drillCategory)} : ${drillDossier}`:`Dossier ${drillDossier}`}),drillProvider&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:4,wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:drillProvider}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:drillProvider})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{size:"xs",variant:"light",onClick:()=>{setSelectedDossier(drillDossier);closeDrill()},children:"Focus sur ce dossier"})]}):null,styles:isMobile?{body:{padding:12,paddingBottom:24}}:void 0,children:drillData&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[(null===drillCategory||"reconciliation"===drillCategory)&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"center",mb:6,children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Title,{order:5,children:["Rappros bancaires (",drillData.reconciliation.length,")"]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{size:"xs",variant:pendingMutes.length>0?"filled":"light",disabled:0===pendingMutes.length,loading:saveReconciliationMutes.isPending,onClick:()=>saveReconciliationMutes.mutate(pendingMutes,{onSuccess:()=>setMuteDraft(new Map)}),children:pendingMutes.length>1?`Enregistrer (${pendingMutes.length})`:"Enregistrer"})]}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileReconciliationList,{rows:reconciliationRows,onToggleMute:onToggleMute}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:drillRecoCols,rows:reconciliationRows})]}),(null===drillCategory||"471"===drillCategory)&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(DrillSectionTitle,{label:"Comptes d'attente 471",count:drillData.suspense.length,visibleSum:sumBy(drillData.suspense,r=>r.solde_net),total:drillData.totals.suspense,currency:drillData.currency}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSuspenseList,{rows:drillData.suspense}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:DRILL_SUSPENSE_COLS,rows:drillData.suspense})]}),(null===drillCategory||"58"===drillCategory)&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(DrillSectionTitle,{label:"Virements internes 58",count:drillData.internalTransfers.length,visibleSum:sumBy(drillData.internalTransfers,r=>r.solde_net),total:drillData.totals.internalTransfers,currency:drillData.currency}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSuspenseList,{rows:drillData.internalTransfers}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:DRILL_SUSPENSE_COLS,rows:drillData.internalTransfers})]}),(null===drillCategory||"supplier"===drillCategory)&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(DrillSectionTitle,{label:"Fournisseurs d\xe9biteurs 401",count:drillData.supplier.length,visibleSum:sumBy(drillData.supplier,r=>r.solde_debiteur_eur),total:drillData.totals.supplier,currency:drillData.currency}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSupplierList,{rows:drillData.supplier}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:DRILL_SUPPLIER_COLS,rows:drillData.supplier})]}),(null===drillCategory||"customer"===drillCategory)&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(DrillSectionTitle,{label:"Clients cr\xe9diteurs 411",count:drillData.customer.length,visibleSum:sumBy(drillData.customer,r=>r.solde_crediteur_eur),total:drillData.totals.customer,currency:drillData.currency}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileCustomerList,{rows:drillData.customer}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:DRILL_CUSTOMER_COLS,rows:drillData.customer})]}),(null===drillCategory||"factor"===drillCategory)&&drillData.factor.length>0&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(DrillSectionTitle,{label:"Cr\xe9ances c\xe9d\xe9es au factor 4116",count:drillData.factor.length,visibleSum:sumBy(drillData.factor,r=>r.solde_eur),total:drillData.totals.factor}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileCustomerList,{rows:drillData.factor.map(factorRowAsCustomerRow)}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:DRILL_FACTOR_COLS,rows:drillData.factor})]})]})})]})}const TOP_SUSPENSE_COLS=[{key:"rank",label:"#",numeric:true},{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"G\xe9r\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"solde_eur",label:"Solde 471 (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr.",numeric:true},{key:"top_libelle",label:"Top \xe9criture"},{key:"top_montant",label:"Montant",numeric:true}];const TOP_SUPPLIER_COLS=[{key:"rank",label:"#",numeric:true},{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"total_eur",label:"Total d\xe9biteur (€)",numeric:true},{key:"nb_fournisseurs",label:"Nb fourn.",numeric:true},{key:"top_nom",label:"Top fournisseur"},{key:"top_montant",label:"Montant",numeric:true}];const TOP_CUSTOMER_COLS=[{key:"rank",label:"#",numeric:true},{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"total_eur",label:"Total cr\xe9diteur (€)",numeric:true},{key:"nb_clients",label:"Nb clients",numeric:true},{key:"top_nom",label:"Top client"},{key:"top_montant",label:"Montant",numeric:true}];function buildUnifiedCols(computedAt,openDrill,dossiersWithActiveReco){return[{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"score",label:"Tenue",hint:"Note de tenue comptable sur 5 : un point par contr\xf4le pass\xe9 (factures fournisseurs en attente, banques rapproch\xe9es, compte d’attente, virements internes, comptes tiers). Survolez pour le d\xe9tail.",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ScoreStars,{row:r})},{key:"dossier",label:"Dossier",render:r=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(CompanyLogo.D,{slug:r.slug,updatedAt:r.logo_updated_at,size:20}),/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:r.dossier})]})},{key:"responsable",label:"Responsable",sortValue:r=>r.responsable?.name??"",render:r=>r.responsable?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:r.responsable.avatar_url,size:20,radius:"xl"}),/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:r.responsable.name})]}):/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"})},{key:"fiscal_year_end",label:"Cl\xf4ture",render:r=>r.fiscal_year_end?/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:r.fiscal_year_end.split("-").reverse().join("/")}):/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"})},{key:"solde_attente_eur",label:"Solde 471",numeric:true,render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(r.solde_attente_eur,r.currency),onClick:()=>openDrill(r,"471")})},{key:"solde_virements_eur",label:"Solde 58",numeric:true,render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(r.solde_virements_eur,r.currency),onClick:()=>openDrill(r,"58")})},{key:"total_fournisseurs_eur",label:"Fourn. d\xe9biteurs",numeric:true,render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(r.total_fournisseurs_eur,r.currency),onClick:()=>openDrill(r,"supplier")})},{key:"total_clients_eur",label:"Clients cr\xe9diteurs",numeric:true,render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(r.total_clients_eur,r.currency),onClick:()=>openDrill(r,"customer")})},{key:"total_factor_eur",label:"Cr\xe9ances c\xe9d\xe9es",hint:"Cr\xe9ances c\xe9d\xe9es au factor (comptes 4116) : solde cr\xe9diteur par construction, il vaut moins l’encours c\xe9d\xe9 au portail du factor. Ce n’est pas une anomalie clients.",numeric:true,render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:factorKeur(r),onClick:()=>openDrill(r,"factor")})},{key:"last_entry_date",label:"Date mise \xe0 jour",hint:"La plus ancienne des 3 dates de fra\xeecheur : derni\xe8re \xe9criture comptable, dernier import GLA, dernier passage du scrapper rappros/factures. Survolez pour le d\xe9tail des 3 dates.",render:row=>/*#__PURE__*/(0,jsx_runtime.jsx)(UpdateDateCell,{row:row,computedAt:computedAt})},{key:"last_reconciliation_date",label:"Rappro le + en retard",render:r=>{if("pennylane"!==r.source)return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"});if(null==r.last_reconciliation_date){if(!dossiersWithActiveReco.has(r.dossier))return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"dimmed",children:"—"});return/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"red",fw:700,children:"jamais"}),onClick:()=>openDrill(r,"reconciliation")})}return/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:r.last_reconciliation_date.split("-").reverse().join("/"),onClick:()=>openDrill(r,"reconciliation")})}},{key:"pending_supplier_invoices",label:"Factures fournisseurs \xe0 traiter (compta)",hint:"Factures fournisseurs \xe0 traiter c\xf4t\xe9 Comptabilit\xe9 sur l’ann\xe9e civile courante.",numeric:true,render:r=>{if("pennylane"!==r.source||null==r.pending_supplier_invoices)return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"});return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:formatNumber(r.pending_supplier_invoices)})}},{key:"management_supplier_invoices_inbox",label:"Factures fournisseurs \xe0 traiter (gestion)",hint:"Nombre affich\xe9 dans la Bo\xeete de r\xe9ception des factures fournisseurs c\xf4t\xe9 Gestion, toutes dates confondues.",numeric:true,render:r=>{if("pennylane"!==r.source||null==r.management_supplier_invoices_inbox)return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"});return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:formatNumber(r.management_supplier_invoices_inbox)})}}]}const SUSPENSE_COLS=[{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"date",label:"Date"},{key:"numero_compte",label:"N\xb0 Compte"},{key:"libelle_compte",label:"Libell\xe9 compte"},{key:"libelle_ecriture",label:"Libell\xe9 \xe9criture"},{key:"journal",label:"Journal"},{key:"numero_piece",label:"N\xb0 Pi\xe8ce"},{key:"debit",label:"D\xe9bit",numeric:true},{key:"credit",label:"Cr\xe9dit",numeric:true},{key:"solde_net",label:"Solde net",numeric:true},{key:"lettre",label:"Lettr\xe9"},{key:"devise",label:"Devise"}];const SUPPLIER_COLS=[{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"fournisseur",label:"Fournisseur"},{key:"solde_debiteur_eur",label:"Solde d\xe9biteur (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr. non lettr\xe9es",numeric:true},{key:"devise",label:"Devise"}];const CUSTOMER_COLS=[{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"client",label:"Client"},{key:"solde_crediteur_eur",label:"Solde cr\xe9diteur (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr. non lettr\xe9es",numeric:true},{key:"devise",label:"Devise"}];function buildDrillRecoCols(onToggleMute){return[{key:"bank_label",label:"Compte",render:r=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(BankLogo,{label:r.bank_label,size:20}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:r.muted?"dimmed":void 0,children:recoAccountLabel(r)})]})},{key:"last_reconciled_period_end",label:"Dernier rappro",render:r=>{if(r.muted)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"dimmed",children:"non suivi"});if(null==r.last_reconciled_period_end)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"red",fw:700,children:"jamais"});return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:r.last_reconciled_period_end.split("-").reverse().join("/")})}},{key:"muted",label:"Suivi",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{size:"sm",checked:!r.muted,label:r.muted?"non suivi":"suivi",onLabel:"suivi",onChange:e=>onToggleMute({company_id:r.airporting_company_id,account_id:r.account_id,muted:!e.currentTarget.checked})})}]}const DRILL_SUSPENSE_COLS=[{key:"date",label:"Date"},{key:"numero_compte",label:"N\xb0 Compte"},{key:"libelle_ecriture",label:"Libell\xe9"},{key:"debit",label:"D\xe9bit",numeric:true},{key:"credit",label:"Cr\xe9dit",numeric:true},{key:"solde_net",label:"Solde net",numeric:true},{key:"lettre",label:"Lettr\xe9"}];const DRILL_SUPPLIER_COLS=[{key:"fournisseur",label:"Fournisseur"},{key:"solde_debiteur_eur",label:"Solde d\xe9biteur (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr.",numeric:true},{key:"devise",label:"Devise"}];const DRILL_FACTOR_COLS=[{key:"compte",label:"Compte"},{key:"solde_eur",label:"Solde (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr.",numeric:true},{key:"devise",label:"Devise"}];function factorRowAsCustomerRow(r){return{source:r.source,dossier:r.dossier,managed:r.managed,client:r.compte,solde_crediteur_eur:r.solde_eur,nb_ecritures:r.nb_ecritures,devise:r.devise}}const DRILL_CUSTOMER_COLS=[{key:"client",label:"Client"},{key:"solde_crediteur_eur",label:"Solde cr\xe9diteur (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr.",numeric:true},{key:"devise",label:"Devise"}];function EtatSaisie(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(consume_shared_module_default_react_strict_.StrictMode,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(providers.C,{...props,children:/*#__PURE__*/(0,jsx_runtime.jsx)(EtatSaisieApp,{})})})}}}]);
1
+ "use strict";(globalThis["chunk_tech_app"]=globalThis["chunk_tech_app"]||[]).push([["7915"],{3437:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{D:()=>CompanyLogo});var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(5893);var _mantine_core__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(207);const BASE_URL="https://s3.dualstack.eu-west-3.amazonaws.com/media.airporting/companies";function CompanyLogo({slug,updatedAt,size=20,...rest}){const base=`${BASE_URL}/${slug}.png`;const url=updatedAt?`${base}?v=${new Date(updatedAt).getTime()}`:base;return/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Image,{src:url,fallbackSrc:`${BASE_URL}/undefined.png`,alt:slug??"",w:size,h:size,fit:"contain",radius:"sm",style:{aspectRatio:1},...rest})}},1354:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{m:()=>PageHeader});var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(5893);var _mantine_core__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(207);var _tabler_icons_react__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(9632);var react__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(5850);function formatRelative(now,then){const seconds=Math.max(0,Math.floor((now-then)/1e3));if(seconds<5)return"\xe0 l’instant";if(seconds<60)return`il y a ${seconds}s`;const minutes=Math.floor(seconds/60);if(minutes<60)return`il y a ${minutes} min`;const hours=Math.floor(minutes/60);return`il y a ${hours} h`}function PageHeader({title,leading,badge,updatedAt,isFetching,isError,onRefresh,actions}){const[now,setNow]=(0,react__WEBPACK_IMPORTED_MODULE_3__.useState)(()=>Date.now());(0,react__WEBPACK_IMPORTED_MODULE_3__.useEffect)(()=>{if(!updatedAt)return;const id=window.setInterval(()=>setNow(Date.now()),1e3);return()=>window.clearInterval(id)},[updatedAt]);const relative=updatedAt?formatRelative(now,updatedAt):null;const color=isError?"orange":isFetching?"teal":"dimmed";return/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Group,{justify:"space-between",align:"center",mih:48,mb:"md",children:[/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Group,{gap:"sm",align:"center",children:[leading,/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Title,{order:2,children:title}),badge]}),/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Group,{gap:"sm",align:"center",children:[relative&&/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Text,{size:"xs",c:color,fw:isFetching?600:400,"data-testid":"page-header-freshness",children:isError?"\xe9chec maj":isFetching?"maj…":relative}),onRefresh&&/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Tooltip,{label:"Rafra\xeechir",children:/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.ActionIcon,{variant:"default",size:"md",onClick:onRefresh,loading:isFetching,"aria-label":"Refresh",children:/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_tabler_icons_react__WEBPACK_IMPORTED_MODULE_2__.IconRefresh,{size:16})})}),actions]})]})}},9781:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{h:()=>QuickBooksIcon});var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(5893);function QuickBooksIcon(props){const size=props.size??20;return/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("svg",{width:size,height:size,viewBox:"0 0 24 24",role:"img","aria-label":"QuickBooks",children:[/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)("title",{children:"QuickBooks"}),/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)("circle",{cx:"12",cy:"12",r:"12",fill:"#2CA01C"}),/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)("text",{x:"12",y:"16.5",textAnchor:"middle",fontSize:"12",fontWeight:"700",fill:"#ffffff",fontFamily:"Arial, Helvetica, sans-serif",children:"qb"})]})}},243:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{j:()=>logoDevUrl});const LOGO_DEV_TOKEN="pk_BVN4OQv0Qs-bnqjdIgTppg";function logoDevUrl(domain){return`https://img.logo.dev/${domain}?token=${LOGO_DEV_TOKEN}`}},7967:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,{default:()=>EtatSaisie});var jsx_runtime=__webpack_require__(5893);var consume_shared_module_default_react_strict_=__webpack_require__(5850);var providers=__webpack_require__(7034);var index_mjs_=__webpack_require__(207);var esm_index_mjs_=__webpack_require__(3863);var index_js_=__webpack_require__(6197);var useApi=__webpack_require__(4148);function useEtatSaisieLatest(){const api=(0,useApi.h)();return(0,index_js_.useQuery)({queryKey:["tech","etat-saisie","latest"],queryFn:async()=>(await api.etatSaisie.getLatestV1()).data,staleTime:6e5,refetchOnWindowFocus:false})}function useEtatSaisieRecompute(){const api=(0,useApi.h)();const qc=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async()=>(await api.etatSaisie.recomputeV1()).data,onSuccess:()=>qc.invalidateQueries({queryKey:["tech","etat-saisie","latest"]})})}var notifications_esm_index_mjs_=__webpack_require__(1455);class PartialMuteSaveError extends Error{saved;total;cause;constructor(saved,total,cause){super(`${saved}/${total} changements enregistr\xe9s avant l'\xe9chec`);this.name="PartialMuteSaveError";this.saved=saved;this.total=total;this.cause=cause}}function useSaveReconciliationMutes(){const api=(0,useApi.h)();const qc=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async changes=>{let saved=0;for(const change of changes){try{await api.etatSaisie.setReconciliationMuteV1({company_id:change.company_id,account_id:change.account_id,muted:change.muted})}catch(err){throw new PartialMuteSaveError(saved,changes.length,err)}saved+=1}return saved},onSuccess:async saved=>{notifications_esm_index_mjs_.notifications.show({title:"Suivi des rappros",message:saved>1?`${saved} changements enregistr\xe9s`:"Changement enregistr\xe9",color:"teal"});await Promise.all([qc.invalidateQueries({queryKey:["tech","etat-saisie","dossiers"]}),qc.invalidateQueries({queryKey:["tech","etat-saisie","latest"]})])},onError:async err=>{const partial=err instanceof PartialMuteSaveError?err:null;notifications_esm_index_mjs_.notifications.show({title:"Suivi des rappros",message:partial?`${partial.saved} changement(s) sur ${partial.total} enregistr\xe9(s), les suivants ont \xe9chou\xe9`:err?.error?.error??err?.message??"Les changements n'ont pas \xe9t\xe9 enregistr\xe9s",color:"red"});if(partial&&partial.saved>0)await Promise.all([qc.invalidateQueries({queryKey:["tech","etat-saisie","dossiers"]}),qc.invalidateQueries({queryKey:["tech","etat-saisie","latest"]})])}})}var tabler_icons_react_mjs_=__webpack_require__(9632);function DetailTableInner(props){const{columns,rows,onRowClick,rowKey,maxHeight}=props;const[sortKey,setSortKey]=(0,consume_shared_module_default_react_strict_.useState)(null);const[asc,setAsc]=(0,consume_shared_module_default_react_strict_.useState)(false);const sortColumn=sortKey?columns.find(c=>c.key===sortKey):void 0;const sorted=[...rows].sort((a,b)=>{if(!sortKey)return 0;const av=sortColumn?.sortValue?sortColumn.sortValue(a):a[sortKey];const bv=sortColumn?.sortValue?sortColumn.sortValue(b):b[sortKey];if("number"==typeof av&&"number"==typeof bv)return asc?av-bv:bv-av;return asc?String(av).localeCompare(String(bv)):String(bv).localeCompare(String(av))});const toggle=k=>{if(sortKey===k)setAsc(v=>!v);else{setSortKey(k);setAsc(false)}};const fmt=(v,numeric)=>{if(numeric&&"number"==typeof v)return v.toLocaleString("fr-FR",{minimumFractionDigits:0,maximumFractionDigits:0});if("boolean"==typeof v)return v?"✓":"";if(null==v)return"-";if("object"==typeof v)return"-";return String(v)};const table=/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{striped:true,highlightOnHover:true,withTableBorder:true,stickyHeader:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Thead,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tr,{children:columns.map(c=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{onClick:()=>toggle(c.key),style:{cursor:"pointer"},children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:4,wrap:"nowrap",component:"span",display:"inline-flex",children:[/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:c.label}),c.hint?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:c.hint,multiline:true,w:260,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)("span",{style:{display:"inline-flex",alignItems:"center"},onClick:e=>e.stopPropagation(),children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconInfoCircle,{size:13})})}):null,/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:sortKey===c.key?asc?" ▲":" ▼":""})]})},c.key))})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:0===sorted.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tr,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{colSpan:columns.length,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",ta:"center",children:"Aucune ligne"})})}):sorted.map((row,i)=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tr,{onClick:onRowClick?()=>onRowClick(row):void 0,style:onRowClick?{cursor:"pointer"}:void 0,children:columns.map(c=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{style:c.numeric?{textAlign:"right",fontVariantNumeric:"tabular-nums"}:void 0,children:c.render?c.render(row):fmt(row[c.key],c.numeric)},c.key))},rowKey?rowKey(row,i):i))})]});if(void 0===maxHeight)return table;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.ScrollContainer,{minWidth:0,mah:maxHeight,type:"native",children:table})}const DetailTable=/*#__PURE__*/(0,consume_shared_module_default_react_strict_.memo)(DetailTableInner);function useDossiers(){const api=(0,useApi.h)();return(0,index_js_.useQuery)({queryKey:["tech","etat-saisie","dossiers"],queryFn:async()=>(await api.etatSaisie.getDossiersV1()).data,refetchOnWindowFocus:true})}function useSaveDossierAssignments(){const api=(0,useApi.h)();const qc=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async changes=>{for(const change of changes){if(null!=change.managed)await api.etatSaisie.setManagedV1({id:change.id},{managed:change.managed});if(void 0!==change.notionUserId)await api.etatSaisie.setResponsableV1({id:change.id},{notion_user_id:change.notionUserId})}return changes.length},onSuccess:()=>{qc.invalidateQueries({queryKey:["tech","etat-saisie","dossiers"]});qc.invalidateQueries({queryKey:["tech","etat-saisie","latest"]})}})}var logoDev=__webpack_require__(243);var QuickBooksIcon=__webpack_require__(9781);const PROVIDER_DOMAIN={pennylane:"pennylane.com",zohobooks:"zoho.com",xero:"xero.com",odoo:"odoo.com"};function ProviderIcon(props){const{provider}=props;if(!provider)return null;if("quickbooks"===provider)return/*#__PURE__*/(0,jsx_runtime.jsx)(QuickBooksIcon.h,{size:20});const domain=PROVIDER_DOMAIN[provider];if(!domain)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{size:"sm",variant:"light",color:"gray",title:provider,children:provider.slice(0,2).toUpperCase()});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Image,{src:(0,logoDev.j)(domain),alt:provider,title:provider,w:20,h:20,fit:"contain",radius:"sm",style:{aspectRatio:1}})}function DossiersTab(){const isMobile=(0,esm_index_mjs_.useMediaQuery)("(max-width: 48em)",false);const dossiers=useDossiers();const save=useSaveDossierAssignments();const[filter,setFilter]=(0,consume_shared_module_default_react_strict_.useState)("");const[draft,setDraft]=(0,consume_shared_module_default_react_strict_.useState)({});(0,consume_shared_module_default_react_strict_.useEffect)(()=>{if(dossiers.data)setDraft({})},[dossiers.data]);const managedOf=dossier=>draft[dossier.airporting_id]?.managed??dossier.managed;const responsableIdOf=dossier=>{const pending=draft[dossier.airporting_id];if(pending&&"responsableId"in pending)return pending.responsableId??null;return dossier.responsable?dossier.responsable.id:null};const setManagedDraft=(dossier,managed)=>setDraft(current=>({...current,[dossier.airporting_id]:{...current[dossier.airporting_id],managed}}));const setResponsableDraft=(dossier,responsableId)=>setDraft(current=>({...current,[dossier.airporting_id]:{...current[dossier.airporting_id],responsableId}}));const options=dossiers.data?.responsable_options??[];const optionData=options.map(u=>({value:String(u.id),label:u.name}));const avatarOf=responsableId=>null==responsableId?void 0:options.find(u=>u.id===responsableId)?.avatar_url;const all=dossiers.data?.dossiers??[];const rows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const needle=filter.trim().toLowerCase();const filtered=needle?all.filter(dossier=>dossier.display_name.toLowerCase().includes(needle)||dossier.slug.toLowerCase().includes(needle)):all;return[...filtered].sort((a,b)=>a.display_name.localeCompare(b.display_name))},[all,filter]);const changes=all.flatMap(dossier=>{const change={id:dossier.airporting_id};const managed=managedOf(dossier);if(managed!==dossier.managed)change.managed=managed;const responsableId=responsableIdOf(dossier);const current=dossier.responsable?dossier.responsable.id:null;if(responsableId!==current)change.notionUserId=responsableId;return null!=change.managed||void 0!==change.notionUserId?[change]:[]});if(dossiers.isError)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"red",mt:"md",children:"Erreur de chargement des dossiers."});const saveButton=/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{size:"xs",loading:save.isPending,disabled:0===changes.length,onClick:()=>save.mutate(changes),children:changes.length>0?`Enregistrer (${changes.length})`:"Enregistrer"});return/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{mb:"md",justify:"space-between",wrap:"wrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{placeholder:"Filtrer par nom ou slug",value:filter,onChange:event=>setFilter(event.currentTarget.value),w:isMobile?"100%":320}),saveButton]}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:"sm",children:0===rows.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",ta:"center",py:"xl",children:"Aucun dossier"}):rows.map(dossier=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Card,{withBorder:true,p:"sm",radius:"md",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:dossier.provider}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:dossier.display_name}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:dossier.slug})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{checked:managedOf(dossier),onChange:event=>setManagedDraft(dossier,event.currentTarget.checked)})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{placeholder:"Responsable",data:optionData,value:null==responsableIdOf(dossier)?null:String(responsableIdOf(dossier)),onChange:v=>setResponsableDraft(dossier,v?Number(v):null),searchable:true,clearable:true,leftSection:avatarOf(responsableIdOf(dossier))?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:avatarOf(responsableIdOf(dossier)),size:20,radius:"xl"}):void 0})]})},`${dossier.airporting_id}:${dossier.provider}`))}):/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{striped:true,highlightOnHover:true,withTableBorder:true,stickyHeader:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Thead,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Source"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Dossier"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"G\xe9r\xe9"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Responsable"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:0===rows.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tr,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{colSpan:4,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",ta:"center",children:"Aucun dossier"})})}):rows.map(dossier=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:dossier.provider})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:dossier.display_name}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{checked:managedOf(dossier),onChange:event=>setManagedDraft(dossier,event.currentTarget.checked)})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{placeholder:"—",data:optionData,value:null==responsableIdOf(dossier)?null:String(responsableIdOf(dossier)),onChange:v=>setResponsableDraft(dossier,v?Number(v):null),searchable:true,clearable:true,w:220,leftSection:avatarOf(responsableIdOf(dossier))?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:avatarOf(responsableIdOf(dossier)),size:20,radius:"xl"}):void 0})})]},`${dossier.airporting_id}:${dossier.provider}`))})]})]})}const MAX_STARS=5;const REASON_BADGES={vide:{label:"Vide",color:"gray"},erreur_scan:{label:"Erreur de scan",color:"red"},couverture_connecteur:{label:"Non not\xe9",color:"gray"}};const VERDICT_STYLE={parfait:{color:"green",symbol:"✓"},vert:{color:"green",symbol:"✓"},orange:{color:"orange",symbol:"!"},rouge:{color:"red",symbol:"✕"},non_mesurable:{color:"gray",symbol:"\xb7"}};function starColor(score){if(score>=4)return"var(--mantine-color-green-6)";if(score>=3)return"var(--mantine-color-yellow-6)";if(score>=2)return"var(--mantine-color-orange-6)";return"var(--mantine-color-red-6)"}function Stars(props){const color=starColor(props.score);const items=[];for(let i=1;i<=MAX_STARS;i+=1)if(props.score>=i)items.push(/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconStarFilled,{size:13,color:color},i));else if(props.score>=i-.5)items.push(/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconStarHalfFilled,{size:13,color:color},i));else items.push(/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconStar,{size:13,color:"var(--mantine-color-dark-2)"},i));return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:1,wrap:"nowrap",children:items})}function ControlList(props){const controls=props.row.score_controls??[];if(0===controls.length)return null;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:4,children:controls.map(c=>{const style=VERDICT_STYLE[c.verdict]??VERDICT_STYLE.non_mesurable;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:style.color,fw:700,w:12,children:style.symbol}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",children:c.label}),c.detail?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:c.detail}):null]})]},c.key)})})}function ScoreStars(props){const{row}=props;if(null==row.score){const badge=row.score_reason?REASON_BADGES[row.score_reason]:void 0;const fallback=badge??{label:"Non not\xe9",color:"gray"};const controls=row.score_controls??[];const content=/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{size:"xs",color:fallback.color,variant:"light",children:fallback.label});if("couverture_connecteur"!==row.score_reason)return content;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard,{width:300,shadow:"md",openDelay:150,withinPortal:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Target,{children:/*#__PURE__*/(0,jsx_runtime.jsx)("span",{style:{cursor:"help"},children:content})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard.Dropdown,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",fw:600,mb:6,children:"Pas assez de contr\xf4les mesurables"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",c:"dimmed",mb:6,children:["Ce connecteur n’expose pas les comptes n\xe9cessaires. Une note fond\xe9e sur ",controls.filter(c=>"non_mesurable"!==c.verdict).length," ","contr\xf4le(s) sur ",MAX_STARS," ne voudrait rien dire."]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ControlList,{row:row})]})]})}const stale=null!=row.refreshed_at&&null!=row.reconciliation_refresh_date&&row.refreshed_at<row.reconciliation_refresh_date;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard,{width:320,shadow:"md",openDelay:150,withinPortal:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Target,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:6,wrap:"nowrap",style:{cursor:"help"},children:/*#__PURE__*/(0,jsx_runtime.jsx)(Stars,{score:row.score})})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard.Dropdown,{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",mb:6,wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(Stars,{score:row.score}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",fw:600,children:[row.score.toLocaleString("fr-FR")," / ",MAX_STARS,row.score_label?` \xb7 ${row.score_label}`:""]})]}),row.score_capped_reason?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"orange",mb:6,children:row.score_capped_reason}):null,stale?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"yellow",mb:6,children:"Chiffres repris d’un calcul ant\xe9rieur."}):null,/*#__PURE__*/(0,jsx_runtime.jsx)(ControlList,{row:row})]})]})}function scoreBucket(row){if(null==row.score)return"non_note";if(row.score>=4)return"bon";if(row.score>=3)return"moyen";return"faible"}function ManagedBadge(props){const{managed}=props;if(!managed)return null;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Image,{src:(0,logoDev.j)("airporting.com"),alt:"G\xe9r\xe9 par Airporting",title:"G\xe9r\xe9 par Airporting",w:18,h:18,fit:"contain",radius:"sm",style:{aspectRatio:1}})}const BANK_DOMAINS=[["bnp paribas","bnpparibas.com"],["societe generale","societegenerale.fr"],["qonto","qonto.com"],["revolut","revolut.com"],["stripe","stripe.com"],["wise","wise.com"],["transferwise","wise.com"],["ibanfirst","ibanfirst.com"],["credit agricole","credit-agricole.fr"],["credit mutuel","creditmutuel.fr"],["banque populaire","banquepopulaire.fr"],["caisse d","caisse-epargne.fr"],["american express","americanexpress.com"],["amex","americanexpress.com"],["paypal","paypal.com"],["hsbc","hsbc.com"],["pennylane","pennylane.com"],["mercury","mercury.com"],["lcl","lcl.fr"],["boursorama","boursorama.com"],["bpce","bpce.fr"]];function normalize(value){return value.toLowerCase().normalize("NFD").replace(/\p{Diacritic}/gu,"")}function BankLogo(props){const{label,size=20}=props;const normalized=label?normalize(label):"";const match=BANK_DOMAINS.find(([needle])=>normalized.includes(needle));if(!match)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,children:"\uD83C\uDFE6"});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Image,{src:(0,logoDev.j)(match[1]),alt:label??"",title:label??"",w:size,h:size,fit:"contain",radius:"sm",style:{aspectRatio:1}})}var CompanyLogo=__webpack_require__(3437);var PageHeader=__webpack_require__(1354);const recoAccountLabel=row=>{const account=(row.account_name??"").trim();const bank=(row.bank_label??"").trim();if(""!==account&&""!==bank&&account!==bank)return`${bank} : ${account}`;return""!==account?account:""!==bank?bank:"Banque"};const muteKey=(companyId,accountId)=>`${companyId}:${accountId}`;function drillCategoryLabel(category){if("471"===category)return"D\xe9tail 471";if("58"===category)return"D\xe9tail 58";if("supplier"===category)return"Fournisseurs d\xe9biteurs 401";if("customer"===category)return"Clients cr\xe9diteurs 411";if("factor"===category)return"Cr\xe9ances c\xe9d\xe9es au factor 4116";if("reconciliation"===category)return"Rappros bancaires";return null}function syncBadge(isoDate){if(!isoDate)return null;const days=Math.floor((Date.now()-new Date(isoDate).getTime())/864e5);let color="green";if(days>10)color="red";else if(days>4)color="orange";return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Badge,{ml:6,size:"xs",color:color,variant:"light",children:[days,"j"]})}function isStaleRefresh(refreshedAt,computedAt){if(!refreshedAt)return false;const refreshedDay=refreshedAt.slice(0,10);const referenceDay=(computedAt??new Date().toISOString()).slice(0,10);return refreshedDay<referenceDay}function refreshKoBadge(refreshedAt,computedAt){if(!isStaleRefresh(refreshedAt,computedAt))return null;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:`Chiffres du ${formatDate(refreshedAt?.slice(0,10))} \u{2014} refresh KO ce run`,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{ml:6,size:"xs",color:"yellow",variant:"light",children:"refresh KO"})})}function factorKeur(row){const v=row.total_factor_eur??0;return 0===v?"—":formatKeur(v,row.currency)}function withDossierFilter(rows,dossier){if(!dossier)return rows;return rows.filter(r=>r.dossier===dossier)}function withManagedFilter(rows,managedOnly){if(!managedOnly)return rows;return rows.filter(r=>true===r.managed)}const NO_RESPONSABLE="__none__";function withResponsableFilter(rows,responsable){if(!responsable)return rows;if(responsable===NO_RESPONSABLE)return rows.filter(r=>null==r.responsable);return rows.filter(r=>String(r.responsable?.id)===responsable)}function withScoreFilter(rows,bucket){if("all"===bucket)return rows;return rows.filter(r=>scoreBucket(r)===bucket)}function formatCurrency(value,currency){if(null==value)return"—";try{return value.toLocaleString("fr-FR",{style:"currency",currency:currency||"EUR",minimumFractionDigits:0,maximumFractionDigits:0})}catch{return`${Math.round(value).toLocaleString("fr-FR")} ${currency}`}}function formatNumber(value){if(null==value)return"—";return value.toLocaleString("fr-FR")}function formatDate(value){if(!value)return"—";return value.split("-").reverse().join("/")}function currencySymbol(code){const currency=code||"EUR";try{const parts=new Intl.NumberFormat("fr-FR",{style:"currency",currency}).formatToParts(0);return parts.find(part=>"currency"===part.type)?.value??currency}catch{return currency}}function formatKeur(value,currency){if(null==value)return"—";const keur=(Math.round(value/1e3)||0).toLocaleString("fr-FR");return`${keur} k${currencySymbol(currency)}`}function sumBy(rows,pick){return rows.reduce((acc,row)=>acc+(pick(row)??0),0)}function DrillSectionTitle(props){const isSample=null!=props.total&&props.count>0&&Math.abs(props.visibleSum-props.total)>.5;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Title,{order:5,mb:6,children:[props.label," (",props.count,isSample?" affich\xe9s":"",")",null!=props.total?` \xb7 total ${formatCurrency(props.total,props.currency)}`:""]})}function ClickableMetricValue(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,style:{cursor:"pointer",display:"block",width:"100%"},onClick:e=>{e.stopPropagation();props.onClick()},children:props.value})}function updateDateParts(row){return[{label:"Derni\xe8re \xe9criture",iso:row.last_entry_date},{label:"Dernier import GLA",iso:row.gla_last_sync_date?.slice(0,10)??null},{label:"Rappros / factures",iso:row.reconciliation_refresh_date?.slice(0,10)??null}]}function oldestUpdateDate(parts){const present=parts.map(p=>p.iso).filter(v=>null!=v);if(0===present.length)return null;return present.reduce((a,b)=>a<b?a:b)}function UpdateDateCell(props){const parts=updateDateParts(props.row);const oldest=oldestUpdateDate(parts);if(null==oldest)return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"});return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard,{withArrow:true,shadow:"md",openDelay:120,position:"bottom-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Target,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{span:true,style:{cursor:"default"},children:[formatDate(oldest),syncBadge(oldest),refreshKoBadge(props.row.refreshed_at,props.computedAt),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"dimmed",children:" ▾"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Dropdown,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:4,children:parts.map(p=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",gap:"lg",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:p.label}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",children:p.iso?formatDate(p.iso):"—"})]},p.label))})})]})}function clickableCardStyle(clickable){return clickable?{cursor:"pointer"}:void 0}function MobileMetricGrid({metrics}){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SimpleGrid,{cols:2,spacing:"xs",children:metrics.map(metric=>/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:metric.label}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",fw:700,c:metric.color,lineClamp:2,children:metric.value})]},metric.label))})}function MobileAccountingList(props){const{rows,emptyLabel="Aucune ligne",getKey,renderHeader,getMetrics,onRowClick}=props;if(0===rows.length)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",ta:"center",py:"xl",children:emptyLabel});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:"sm",children:rows.map((row,index)=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Card,{withBorder:true,p:"sm",radius:"md",onClick:onRowClick?()=>onRowClick(row):void 0,style:clickableCardStyle(!!onRowClick),children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[renderHeader(row),/*#__PURE__*/(0,jsx_runtime.jsx)(MobileMetricGrid,{metrics:getMetrics(row)})]})},getKey(row,index)))})}function MobileDossierLineList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:row=>props.onDrill(row),getKey:row=>`${row.source}:${row.dossier}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",align:"center",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsx)(CompanyLogo.D,{slug:row.slug,updatedAt:row.logo_updated_at,size:24}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:row.dossier}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:6,wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.responsable?.name??"Sans responsable"})]})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ScoreStars,{row:row})]}),getMetrics:row=>[{label:"471",value:/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(row.solde_attente_eur,row.currency),onClick:()=>props.onDrill(row,"471")})},{label:"58",value:/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(row.solde_virements_eur,row.currency),onClick:()=>props.onDrill(row,"58")})},{label:"401",value:/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(row.total_fournisseurs_eur,row.currency),onClick:()=>props.onDrill(row,"supplier")})},{label:"411",value:/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(row.total_clients_eur,row.currency),onClick:()=>props.onDrill(row,"customer")})},{label:"Cr\xe9ances c\xe9d\xe9es",value:/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:factorKeur(row),onClick:()=>props.onDrill(row,"factor")})},{label:"Date mise \xe0 jour",value:(()=>{const oldest=oldestUpdateDate(updateDateParts(row));if(null==oldest)return"—";return/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[formatDate(oldest),syncBadge(oldest),refreshKoBadge(row.refreshed_at,props.computedAt)]})})()},{label:"Rappro",value:(()=>{const text="pennylane"!==row.source?"—":row.last_reconciliation_date?formatDate(row.last_reconciliation_date):props.dossiersWithActiveReco.has(row.dossier)?"jamais":"—";if("—"===text)return text;return/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:text,onClick:()=>props.onDrill(row,"reconciliation")})})(),color:"pennylane"===row.source&&null==row.last_reconciliation_date&&props.dossiersWithActiveReco.has(row.dossier)?"red":void 0},{label:"Factures fournisseurs \xe0 traiter (compta)",value:"pennylane"===row.source?formatNumber(row.pending_supplier_invoices):"—"},{label:"Factures fournisseurs \xe0 traiter (gestion)",value:"pennylane"===row.source?formatNumber(row.management_supplier_invoices_inbox):"—"}]})}function MobileSuspenseList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:(row,index)=>`${row.dossier}:${row.date}:${row.numero_piece??index}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:row.dossier}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:2,children:row.libelle_ecriture??row.libelle_compte??"Sans libell\xe9"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Solde net",value:formatCurrency(row.solde_net)},{label:"Date",value:formatDate(row.date)},{label:"Compte",value:row.numero_compte??"—"},{label:"Pi\xe8ce",value:row.numero_piece??"—"}]})}function MobileSupplierList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:(row,index)=>`${row.dossier}:${row.fournisseur}:${index}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:row.fournisseur}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.dossier})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Solde d\xe9biteur",value:formatCurrency(row.solde_debiteur_eur)},{label:"\xc9critures",value:formatNumber(row.nb_ecritures)},{label:"Devise",value:row.devise||"—"}]})}function MobileCustomerList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:(row,index)=>`${row.dossier}:${row.client}:${index}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:row.client}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.dossier})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Solde cr\xe9diteur",value:formatCurrency(row.solde_crediteur_eur)},{label:"\xc9critures",value:formatNumber(row.nb_ecritures)},{label:"Devise",value:row.devise||"—"}]})}function MobileReconciliationList({rows,onToggleMute}){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:rows,getKey:row=>`${row.airporting_company_id}:${row.account_id}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"center",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(BankLogo,{label:row.bank_label,size:24}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,c:row.muted?"dimmed":void 0,children:recoAccountLabel(row)})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{size:"sm",checked:!row.muted,label:row.muted?"non suivi":"suivi",onLabel:"suivi",onChange:e=>onToggleMute({company_id:row.airporting_company_id,account_id:row.account_id,muted:!e.currentTarget.checked})})]}),getMetrics:row=>[{label:"Dernier rappro",value:row.muted?"non suivi":row.last_reconciled_period_end?formatDate(row.last_reconciled_period_end):"jamais",color:row.muted?"dimmed":row.last_reconciled_period_end?void 0:"red"},{label:"Derni\xe8re op\xe9ration",value:row.last_movement_date?formatDate(row.last_movement_date):"—"},{label:"\xc0 rapprocher depuis",value:row.muted?"non suivi":row.unreconciled_since?formatDate(row.unreconciled_since):row.last_movement_date?"rien \xe0 rapprocher":"—",color:!row.muted&&null==row.unreconciled_since&&row.last_movement_date?"teal":void 0}]})}function MobileTopSuspenseList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:row=>`471:${row.rank}:${row.dossier}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:["#",row.rank," ",row.dossier]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.top_libelle??"Sans libell\xe9"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Solde 471",value:formatCurrency(row.solde_eur)},{label:"\xc9critures",value:formatNumber(row.nb_ecritures)},{label:"Top montant",value:formatCurrency(row.top_montant)}]})}function MobileTopSupplierList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:row=>`401:${row.rank}:${row.dossier}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:["#",row.rank," ",row.dossier]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.top_nom??"Sans fournisseur"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Total d\xe9biteur",value:formatCurrency(row.total_eur)},{label:"Fournisseurs",value:formatNumber(row.nb_fournisseurs)},{label:"Top montant",value:formatCurrency(row.top_montant)}]})}function MobileTopCustomerList(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(MobileAccountingList,{rows:props.rows,onRowClick:props.onRowClick,getKey:row=>`411:${row.rank}:${row.dossier}`,renderHeader:row=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",gap:"sm",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",miw:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:row.source}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{fw:700,size:"sm",lineClamp:1,children:["#",row.rank," ",row.dossier]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:row.top_nom??"Sans client"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:row.managed})]}),getMetrics:row=>[{label:"Total cr\xe9diteur",value:formatCurrency(row.total_eur)},{label:"Clients",value:formatNumber(row.nb_clients)},{label:"Top montant",value:formatCurrency(row.top_montant)}]})}function EtatSaisieApp(){const isMobile=(0,esm_index_mjs_.useMediaQuery)("(max-width: 48em)",false);const latest=useEtatSaisieLatest();const recompute=useEtatSaisieRecompute();const saveReconciliationMutes=useSaveReconciliationMutes();const[muteDraft,setMuteDraft]=(0,consume_shared_module_default_react_strict_.useState)(new Map);const[tab,setTab]=(0,consume_shared_module_default_react_strict_.useState)("resume");const[selectedDossier,setSelectedDossier]=(0,consume_shared_module_default_react_strict_.useState)(null);const[managedOnly,setManagedOnly]=(0,consume_shared_module_default_react_strict_.useState)(true);const[statusFilter,setStatusFilter]=(0,consume_shared_module_default_react_strict_.useState)("all");const[selectedResponsable,setSelectedResponsable]=(0,consume_shared_module_default_react_strict_.useState)(null);const[drillDossier,setDrillDossier]=(0,consume_shared_module_default_react_strict_.useState)(null);const[drillProvider,setDrillProvider]=(0,consume_shared_module_default_react_strict_.useState)(null);const[drillCategory,setDrillCategory]=(0,consume_shared_module_default_react_strict_.useState)(null);const d=latest.data;const allDossiers=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{if(!d?.available)return[];const set=new Set;for(const r of d.suspense_rows??[])set.add(r.dossier);for(const r of d.supplier_rows??[])set.add(r.dossier);for(const r of d.customer_rows??[])set.add(r.dossier);for(const r of d.dossier_lines??[])set.add(r.dossier);for(const r of d.reconciliation_rows??[])set.add(r.dossier);for(const r of d.summary?.top_5_suspense??[])set.add(r.dossier);for(const r of d.summary?.top_5_supplier_debtors??[])set.add(r.dossier);for(const r of d.summary?.top_5_customer_creditors??[])set.add(r.dossier);return[...set].sort()},[d]);const responsableOptions=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const byId=new Map;let hasNone=false;for(const line of d?.dossier_lines??[])if(line.responsable)byId.set(line.responsable.id,line.responsable.name);else hasNone=true;const options=[...byId.entries()].map(([id,name])=>({value:String(id),label:name})).sort((a,b)=>a.label.localeCompare(b.label));if(hasNone)options.push({value:NO_RESPONSABLE,label:"Sans responsable"});return options},[d]);const dossiersWithActiveReco=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const set=new Set;for(const r of d?.reconciliation_rows??[])if(!r.muted)set.add(r.dossier);return set},[d]);const openDrill=(0,consume_shared_module_default_react_strict_.useCallback)((row,category=null)=>{setDrillDossier(row.dossier);setDrillProvider(row.source);setDrillCategory(category)},[]);const closeDrill=(0,consume_shared_module_default_react_strict_.useCallback)(()=>{setDrillDossier(null);setDrillProvider(null);setDrillCategory(null);setMuteDraft(new Map)},[]);const unifiedCols=(0,consume_shared_module_default_react_strict_.useMemo)(()=>buildUnifiedCols(d?.computed_at,openDrill,dossiersWithActiveReco),[d?.computed_at,openDrill,dossiersWithActiveReco]);const drillData=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{if(!drillDossier||!d?.available)return null;const scoped=rows=>(rows??[]).filter(r=>r.dossier===drillDossier&&r.source===drillProvider);const reconciliation=scoped(d.reconciliation_rows).sort((a,b)=>{const av=a.last_reconciled_period_end??"0000-00-00";const bv=b.last_reconciled_period_end??"0000-00-00";return av.localeCompare(bv)});const lines=(d.dossier_lines??[]).filter(l=>l.dossier===drillDossier&&l.source===drillProvider);const sumLines=pick=>lines.reduce((acc,l)=>acc+(pick(l)??0),0);return{reconciliation,suspense:scoped(d.suspense_rows),internalTransfers:scoped(d.internal_transfer_rows),supplier:scoped(d.supplier_rows),customer:scoped(d.customer_rows),factor:scoped(d.factor_rows??[]),currency:lines[0]?.currency??null,totals:{suspense:sumLines(l=>l.solde_attente_eur),internalTransfers:sumLines(l=>l.solde_virements_eur),supplier:sumLines(l=>l.total_fournisseurs_eur),customer:sumLines(l=>l.total_clients_eur),factor:sumLines(l=>l.total_factor_eur??0)}}},[drillDossier,drillProvider,d]);const reconciliationRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const rows=drillData?.reconciliation??[];if(0===muteDraft.size)return rows;return rows.map(row=>{const draft=muteDraft.get(muteKey(row.airporting_company_id,row.account_id));return void 0===draft?row:{...row,muted:draft}})},[drillData,muteDraft]);const onToggleMute=(0,consume_shared_module_default_react_strict_.useCallback)(({company_id,account_id,muted})=>{setMuteDraft(current=>{const next=new Map(current);const key=muteKey(company_id,account_id);const server=(drillData?.reconciliation??[]).find(row=>row.airporting_company_id===company_id&&row.account_id===account_id);if(server&&server.muted===muted)next.delete(key);else next.set(key,muted);return next})},[drillData]);const drillRecoCols=(0,consume_shared_module_default_react_strict_.useMemo)(()=>buildDrillRecoCols(onToggleMute),[onToggleMute]);const pendingMutes=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const changes=[];for(const[key,muted]of muteDraft){const[companyId,accountId]=key.split(":");changes.push({company_id:Number(companyId),account_id:Number(accountId),muted})}return changes},[muteDraft]);const summaryRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withScoreFilter(withResponsableFilter(withManagedFilter(withDossierFilter(d?.dossier_lines??[],selectedDossier),managedOnly),selectedResponsable),statusFilter),[d,selectedDossier,managedOnly,selectedResponsable,statusFilter]);const scoreTiles=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{const base=withResponsableFilter(withManagedFilter(withDossierFilter(d?.dossier_lines??[],selectedDossier),managedOnly),selectedResponsable);const count=bucket=>base.filter(r=>scoreBucket(r)===bucket).length;return[{key:"all",label:"Dossiers",value:base.length,color:void 0},{key:"bon",label:"4 \xe0 5 \xe9toiles",value:count("bon"),color:"green"},{key:"moyen",label:"3 \xe9toiles",value:count("moyen"),color:"yellow"},{key:"faible",label:"1 \xe0 2 \xe9toiles",value:count("faible"),color:"red"},{key:"non_note",label:"Non not\xe9s",value:count("non_note"),color:"gray"}]},[d,selectedDossier,managedOnly,selectedResponsable]);const topSuspenseRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withDossierFilter(d?.summary?.top_5_suspense??[],selectedDossier),[d,selectedDossier]);const topSupplierRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withDossierFilter(d?.summary?.top_5_supplier_debtors??[],selectedDossier),[d,selectedDossier]);const topCustomerRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withDossierFilter(d?.summary?.top_5_customer_creditors??[],selectedDossier),[d,selectedDossier]);const suspenseRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withManagedFilter(withDossierFilter(d?.suspense_rows??[],selectedDossier),managedOnly),[d,selectedDossier,managedOnly]);const internalTransferRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withManagedFilter(withDossierFilter(d?.internal_transfer_rows??[],selectedDossier),managedOnly),[d,selectedDossier,managedOnly]);const supplierRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withManagedFilter(withDossierFilter(d?.supplier_rows??[],selectedDossier),managedOnly),[d,selectedDossier,managedOnly]);const customerRows=(0,consume_shared_module_default_react_strict_.useMemo)(()=>withManagedFilter(withDossierFilter(d?.customer_rows??[],selectedDossier),managedOnly),[d,selectedDossier,managedOnly]);return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Container,{fluid:true,my:isMobile?0:"md",px:isMobile?12:void 0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(PageHeader.m,{title:"Accounting",updatedAt:d?.computed_at?new Date(d.computed_at).getTime():latest.dataUpdatedAt,isFetching:latest.isFetching,isError:latest.isError,onRefresh:()=>latest.refetch(),actions:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{loading:recompute.isPending,onClick:()=>recompute.mutate(),variant:"light",size:isMobile?"xs":"sm",children:"Recalculer"})}),d&&!d.available?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",children:"Aucun snapshot disponible — lancez \xab Recalculer \xbb ou attendez le run nocturne."}):/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{mb:"md",align:"end",gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"Focus dossier",placeholder:"Tous les dossiers",data:allDossiers.map(dos=>({value:dos,label:dos})),value:selectedDossier,onChange:setSelectedDossier,searchable:true,clearable:true,w:isMobile?"100%":320}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"Responsable",placeholder:"Tous les responsables",data:responsableOptions,value:selectedResponsable,onChange:setSelectedResponsable,searchable:true,clearable:true,w:isMobile?"100%":240}),(selectedDossier||selectedResponsable)&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",onClick:()=>{setSelectedDossier(null);setSelectedResponsable(null)},w:isMobile?"100%":void 0,children:"R\xe9initialiser"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SegmentedControl,{value:managedOnly?"managed":"all",onChange:v=>setManagedOnly("managed"===v),data:[{label:"G\xe9r\xe9s",value:"managed"},{label:"Tous",value:"all"}],w:isMobile?"100%":void 0})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Tabs,{value:tab,onChange:setTab,children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Tabs.List,{style:isMobile?{flexWrap:"nowrap",overflowX:"auto",overflowY:"hidden"}:void 0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Tab,{value:"resume",children:"R\xe9sum\xe9"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Tab,{value:"dossiers",children:"Dossiers"})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Tabs.Panel,{value:"resume",pt:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SimpleGrid,{cols:isMobile?2:5,mb:"md",spacing:"sm",children:scoreTiles.map(tile=>{const active=statusFilter===tile.key;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Card,{withBorder:active,style:{cursor:"pointer",borderColor:active?"var(--mantine-color-blue-5)":void 0},onClick:()=>setStatusFilter(tile.key),children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:tile.label}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:700,size:"xl",c:tile.color,children:tile.value})]},tile.key)})}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileDossierLineList,{rows:summaryRows,onDrill:openDrill,computedAt:d?.computed_at,dossiersWithActiveReco:dossiersWithActiveReco}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{maxHeight:"calc(100vh - 320px)",columns:unifiedCols,rows:summaryRows,onRowClick:openDrill,rowKey:r=>`${r.source}:${r.dossier}`})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"top5",pt:"md",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"lg",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:4,mb:"sm",children:"Top 5 comptes d'attente (471)"}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileTopSuspenseList,{rows:topSuspenseRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:TOP_SUSPENSE_COLS,rows:topSuspenseRows,onRowClick:openDrill})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:4,mb:"sm",children:"Top 5 fournisseurs d\xe9biteurs (401)"}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileTopSupplierList,{rows:topSupplierRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:TOP_SUPPLIER_COLS,rows:topSupplierRows,onRowClick:openDrill})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:4,mb:"sm",children:"Top 5 clients cr\xe9diteurs (411)"}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileTopCustomerList,{rows:topCustomerRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:TOP_CUSTOMER_COLS,rows:topCustomerRows,onRowClick:openDrill})]})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"s471",pt:"md",children:isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSuspenseList,{rows:suspenseRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:SUSPENSE_COLS,rows:suspenseRows,onRowClick:openDrill})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"s58",pt:"md",children:isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSuspenseList,{rows:internalTransferRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:SUSPENSE_COLS,rows:internalTransferRows,onRowClick:openDrill})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"s401",pt:"md",children:isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSupplierList,{rows:supplierRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:SUPPLIER_COLS,rows:supplierRows,onRowClick:openDrill})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"s411",pt:"md",children:isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileCustomerList,{rows:customerRows,onRowClick:openDrill}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:CUSTOMER_COLS,rows:customerRows,onRowClick:openDrill})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tabs.Panel,{value:"dossiers",pt:"md",children:/*#__PURE__*/(0,jsx_runtime.jsx)(DossiersTab,{})})]})]}),latest.isError?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"red",mt:"md",children:"Erreur de chargement."}):null,/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Drawer,{opened:!!drillDossier,onClose:closeDrill,position:isMobile?"bottom":"right",size:isMobile?"calc(100dvh - 88px)":"xl",title:drillDossier?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",align:"center",wrap:isMobile?"wrap":"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:isMobile?5:4,children:drillCategoryLabel(drillCategory)?`${drillCategoryLabel(drillCategory)} : ${drillDossier}`:`Dossier ${drillDossier}`}),drillProvider&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:4,wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:drillProvider}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:drillProvider})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{size:"xs",variant:"light",onClick:()=>{setSelectedDossier(drillDossier);closeDrill()},children:"Focus sur ce dossier"})]}):null,styles:isMobile?{body:{padding:12,paddingBottom:24}}:void 0,children:drillData&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[(null===drillCategory||"reconciliation"===drillCategory)&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"center",mb:6,children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Title,{order:5,children:["Rappros bancaires (",drillData.reconciliation.length,")"]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{size:"xs",variant:pendingMutes.length>0?"filled":"light",disabled:0===pendingMutes.length,loading:saveReconciliationMutes.isPending,onClick:()=>saveReconciliationMutes.mutate(pendingMutes,{onSuccess:()=>setMuteDraft(new Map)}),children:pendingMutes.length>1?`Enregistrer (${pendingMutes.length})`:"Enregistrer"})]}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileReconciliationList,{rows:reconciliationRows,onToggleMute:onToggleMute}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:drillRecoCols,rows:reconciliationRows})]}),(null===drillCategory||"471"===drillCategory)&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(DrillSectionTitle,{label:"Comptes d'attente 471",count:drillData.suspense.length,visibleSum:sumBy(drillData.suspense,r=>r.solde_net),total:drillData.totals.suspense,currency:drillData.currency}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSuspenseList,{rows:drillData.suspense}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:DRILL_SUSPENSE_COLS,rows:drillData.suspense})]}),(null===drillCategory||"58"===drillCategory)&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(DrillSectionTitle,{label:"Virements internes 58",count:drillData.internalTransfers.length,visibleSum:sumBy(drillData.internalTransfers,r=>r.solde_net),total:drillData.totals.internalTransfers,currency:drillData.currency}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSuspenseList,{rows:drillData.internalTransfers}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:DRILL_SUSPENSE_COLS,rows:drillData.internalTransfers})]}),(null===drillCategory||"supplier"===drillCategory)&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(DrillSectionTitle,{label:"Fournisseurs d\xe9biteurs 401",count:drillData.supplier.length,visibleSum:sumBy(drillData.supplier,r=>r.solde_debiteur_eur),total:drillData.totals.supplier,currency:drillData.currency}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileSupplierList,{rows:drillData.supplier}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:DRILL_SUPPLIER_COLS,rows:drillData.supplier})]}),(null===drillCategory||"customer"===drillCategory)&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(DrillSectionTitle,{label:"Clients cr\xe9diteurs 411",count:drillData.customer.length,visibleSum:sumBy(drillData.customer,r=>r.solde_crediteur_eur),total:drillData.totals.customer,currency:drillData.currency}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileCustomerList,{rows:drillData.customer}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:DRILL_CUSTOMER_COLS,rows:drillData.customer})]}),(null===drillCategory||"factor"===drillCategory)&&drillData.factor.length>0&&/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(DrillSectionTitle,{label:"Cr\xe9ances c\xe9d\xe9es au factor 4116",count:drillData.factor.length,visibleSum:sumBy(drillData.factor,r=>r.solde_eur),total:drillData.totals.factor}),isMobile?/*#__PURE__*/(0,jsx_runtime.jsx)(MobileCustomerList,{rows:drillData.factor.map(factorRowAsCustomerRow)}):/*#__PURE__*/(0,jsx_runtime.jsx)(DetailTable,{columns:DRILL_FACTOR_COLS,rows:drillData.factor})]})]})})]})}const TOP_SUSPENSE_COLS=[{key:"rank",label:"#",numeric:true},{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"G\xe9r\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"solde_eur",label:"Solde 471 (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr.",numeric:true},{key:"top_libelle",label:"Top \xe9criture"},{key:"top_montant",label:"Montant",numeric:true}];const TOP_SUPPLIER_COLS=[{key:"rank",label:"#",numeric:true},{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"total_eur",label:"Total d\xe9biteur (€)",numeric:true},{key:"nb_fournisseurs",label:"Nb fourn.",numeric:true},{key:"top_nom",label:"Top fournisseur"},{key:"top_montant",label:"Montant",numeric:true}];const TOP_CUSTOMER_COLS=[{key:"rank",label:"#",numeric:true},{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"total_eur",label:"Total cr\xe9diteur (€)",numeric:true},{key:"nb_clients",label:"Nb clients",numeric:true},{key:"top_nom",label:"Top client"},{key:"top_montant",label:"Montant",numeric:true}];function buildUnifiedCols(computedAt,openDrill,dossiersWithActiveReco){return[{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"score",label:"Tenue",hint:"Note de tenue comptable sur 5 : un point par contr\xf4le pass\xe9 (factures fournisseurs en attente, banques rapproch\xe9es, compte d’attente, virements internes, comptes tiers). Survolez pour le d\xe9tail.",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ScoreStars,{row:r})},{key:"dossier",label:"Dossier",render:r=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(CompanyLogo.D,{slug:r.slug,updatedAt:r.logo_updated_at,size:20}),/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:r.dossier})]})},{key:"responsable",label:"Responsable",sortValue:r=>r.responsable?.name??"",render:r=>r.responsable?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:r.responsable.avatar_url,size:20,radius:"xl"}),/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:r.responsable.name})]}):/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"})},{key:"fiscal_year_end",label:"Cl\xf4ture",render:r=>r.fiscal_year_end?/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:r.fiscal_year_end.split("-").reverse().join("/")}):/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"})},{key:"solde_attente_eur",label:"Solde 471",numeric:true,render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(r.solde_attente_eur,r.currency),onClick:()=>openDrill(r,"471")})},{key:"solde_virements_eur",label:"Solde 58",numeric:true,render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(r.solde_virements_eur,r.currency),onClick:()=>openDrill(r,"58")})},{key:"total_fournisseurs_eur",label:"Fourn. d\xe9biteurs",numeric:true,render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(r.total_fournisseurs_eur,r.currency),onClick:()=>openDrill(r,"supplier")})},{key:"total_clients_eur",label:"Clients cr\xe9diteurs",numeric:true,render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:formatKeur(r.total_clients_eur,r.currency),onClick:()=>openDrill(r,"customer")})},{key:"total_factor_eur",label:"Cr\xe9ances c\xe9d\xe9es",hint:"Cr\xe9ances c\xe9d\xe9es au factor (comptes 4116) : solde cr\xe9diteur par construction, il vaut moins l’encours c\xe9d\xe9 au portail du factor. Ce n’est pas une anomalie clients.",numeric:true,render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:factorKeur(r),onClick:()=>openDrill(r,"factor")})},{key:"last_entry_date",label:"Date mise \xe0 jour",hint:"La plus ancienne des 3 dates de fra\xeecheur : derni\xe8re \xe9criture comptable, dernier import GLA, dernier passage du scrapper rappros/factures. Survolez pour le d\xe9tail des 3 dates.",render:row=>/*#__PURE__*/(0,jsx_runtime.jsx)(UpdateDateCell,{row:row,computedAt:computedAt})},{key:"last_reconciliation_date",label:"Rappro le + en retard",render:r=>{if("pennylane"!==r.source)return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"});if(null==r.last_reconciliation_date){if(!dossiersWithActiveReco.has(r.dossier))return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"dimmed",children:"—"});return/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"red",fw:700,children:"jamais"}),onClick:()=>openDrill(r,"reconciliation")})}return/*#__PURE__*/(0,jsx_runtime.jsx)(ClickableMetricValue,{value:r.last_reconciliation_date.split("-").reverse().join("/"),onClick:()=>openDrill(r,"reconciliation")})}},{key:"pending_supplier_invoices",label:"Factures fournisseurs \xe0 traiter (compta)",hint:"Factures fournisseurs \xe0 traiter c\xf4t\xe9 Comptabilit\xe9 sur l’ann\xe9e civile courante.",numeric:true,render:r=>{if("pennylane"!==r.source||null==r.pending_supplier_invoices)return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"});return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:formatNumber(r.pending_supplier_invoices)})}},{key:"management_supplier_invoices_inbox",label:"Factures fournisseurs \xe0 traiter (gestion)",hint:"Nombre affich\xe9 dans la Bo\xeete de r\xe9ception des factures fournisseurs c\xf4t\xe9 Gestion, toutes dates confondues.",numeric:true,render:r=>{if("pennylane"!==r.source||null==r.management_supplier_invoices_inbox)return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"—"});return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:formatNumber(r.management_supplier_invoices_inbox)})}}]}const SUSPENSE_COLS=[{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"date",label:"Date"},{key:"numero_compte",label:"N\xb0 Compte"},{key:"libelle_compte",label:"Libell\xe9 compte"},{key:"libelle_ecriture",label:"Libell\xe9 \xe9criture"},{key:"journal",label:"Journal"},{key:"numero_piece",label:"N\xb0 Pi\xe8ce"},{key:"debit",label:"D\xe9bit",numeric:true},{key:"credit",label:"Cr\xe9dit",numeric:true},{key:"solde_net",label:"Solde net",numeric:true},{key:"lettre",label:"Lettr\xe9"},{key:"devise",label:"Devise"}];const SUPPLIER_COLS=[{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"fournisseur",label:"Fournisseur"},{key:"solde_debiteur_eur",label:"Solde d\xe9biteur (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr. non lettr\xe9es",numeric:true},{key:"devise",label:"Devise"}];const CUSTOMER_COLS=[{key:"source",label:"Source",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ProviderIcon,{provider:r.source})},{key:"managed",label:"Manag\xe9",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(ManagedBadge,{managed:r.managed})},{key:"dossier",label:"Dossier"},{key:"client",label:"Client"},{key:"solde_crediteur_eur",label:"Solde cr\xe9diteur (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr. non lettr\xe9es",numeric:true},{key:"devise",label:"Devise"}];function buildDrillRecoCols(onToggleMute){return[{key:"bank_label",label:"Compte",render:r=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(BankLogo,{label:r.bank_label,size:20}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:r.muted?"dimmed":void 0,children:recoAccountLabel(r)})]})},{key:"last_reconciled_period_end",label:"Dernier rappro",render:r=>{if(r.muted)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"dimmed",children:"non suivi"});if(null==r.last_reconciled_period_end)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"red",fw:700,children:"jamais"});return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:r.last_reconciled_period_end.split("-").reverse().join("/")})}},{key:"last_movement_date",label:"Derni\xe8re op\xe9ration",hint:"Date de la derni\xe8re \xe9criture r\xe9elle du compte au grand livre. Un compte sans op\xe9ration depuis son dernier rappro n’a rien \xe0 rapprocher.",render:r=>{if(null==r.last_movement_date)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"dimmed",children:"—"});return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:formatDate(r.last_movement_date)})}},{key:"unreconciled_since",label:"\xc0 rapprocher depuis",hint:"Premi\xe8re \xe9criture post\xe9rieure au dernier rappro. C’est de l\xe0 que date le retard r\xe9el, et non du dernier rappro : un compte rapproch\xe9 en avril puis rest\xe9 sans mouvement jusqu’en septembre n’accuse pas cinq mois de retard.",render:r=>{if(r.muted)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"dimmed",children:"non suivi"});if(null!=r.unreconciled_since)return/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:formatDate(r.unreconciled_since)});if(null==r.last_movement_date)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"dimmed",children:"—"});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{span:true,c:"teal",children:"rien \xe0 rapprocher"})}},{key:"muted",label:"Suivi",render:r=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{size:"sm",checked:!r.muted,label:r.muted?"non suivi":"suivi",onLabel:"suivi",onChange:e=>onToggleMute({company_id:r.airporting_company_id,account_id:r.account_id,muted:!e.currentTarget.checked})})}]}const DRILL_SUSPENSE_COLS=[{key:"date",label:"Date"},{key:"numero_compte",label:"N\xb0 Compte"},{key:"libelle_ecriture",label:"Libell\xe9"},{key:"debit",label:"D\xe9bit",numeric:true},{key:"credit",label:"Cr\xe9dit",numeric:true},{key:"solde_net",label:"Solde net",numeric:true},{key:"lettre",label:"Lettr\xe9"}];const DRILL_SUPPLIER_COLS=[{key:"fournisseur",label:"Fournisseur"},{key:"solde_debiteur_eur",label:"Solde d\xe9biteur (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr.",numeric:true},{key:"devise",label:"Devise"}];const DRILL_FACTOR_COLS=[{key:"compte",label:"Compte"},{key:"solde_eur",label:"Solde (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr.",numeric:true},{key:"devise",label:"Devise"}];function factorRowAsCustomerRow(r){return{source:r.source,dossier:r.dossier,managed:r.managed,client:r.compte,solde_crediteur_eur:r.solde_eur,nb_ecritures:r.nb_ecritures,devise:r.devise}}const DRILL_CUSTOMER_COLS=[{key:"client",label:"Client"},{key:"solde_crediteur_eur",label:"Solde cr\xe9diteur (€)",numeric:true},{key:"nb_ecritures",label:"Nb \xe9cr.",numeric:true},{key:"devise",label:"Devise"}];function EtatSaisie(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(consume_shared_module_default_react_strict_.StrictMode,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(providers.C,{...props,children:/*#__PURE__*/(0,jsx_runtime.jsx)(EtatSaisieApp,{})})})}}}]);
@@ -1 +1 @@
1
- "use strict";(globalThis["chunk_tech_app"]=globalThis["chunk_tech_app"]||[]).push([["2149"],{1334:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{m:()=>useSalesLeads});var _tanstack_react_query__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(6197);var _useApi_ts__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(4148);function useSalesLeads(status){const api=(0,_useApi_ts__WEBPACK_IMPORTED_MODULE_1__.h)();return(0,_tanstack_react_query__WEBPACK_IMPORTED_MODULE_0__.useQuery)({queryKey:["tech","sales","leads",status],queryFn:async()=>(await api.sales.listLeadsV1({status})).data,refetchOnWindowFocus:true})}},9328:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{A:()=>NewLeadModal});var jsx_runtime=__webpack_require__(5893);var index_mjs_=__webpack_require__(207);var esm_index_mjs_=__webpack_require__(9038);var form_esm_index_mjs_=__webpack_require__(5021);var notifications_esm_index_mjs_=__webpack_require__(1455);var index_js_=__webpack_require__(6197);var useApi=__webpack_require__(4148);function useCreateLead(){const api=(0,useApi.h)();const queryClient=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async payload=>(await api.sales.createLeadV1(payload)).data,onSuccess:data=>{notifications_esm_index_mjs_.notifications.show({title:"Lead",message:data?.attached?"Coordonn\xe9e d\xe9j\xe0 connue — rattach\xe9 au lead existant":"Lead cr\xe9\xe9",color:"green"});queryClient.invalidateQueries({queryKey:["tech","sales"]})},onError:err=>{notifications_esm_index_mjs_.notifications.show({title:"Lead",message:err?.error?.error??err?.message??"\xc9chec de la cr\xe9ation",color:"red"})}})}function NewLeadModal({opened,onClose,onCreated}){const create=useCreateLead();const form=(0,form_esm_index_mjs_.useForm)({initialValues:{first_name:"",last_name:"",company:"",email:"",phone:"",linkedin_url:"",note:"",next_action_due_at:null,request_reconstruction:true}});function submit(values){const hasAny=Boolean(values.first_name)||Boolean(values.last_name)||Boolean(values.company)||Boolean(values.email)||Boolean(values.phone)||Boolean(values.linkedin_url);if(!hasAny)return void notifications_esm_index_mjs_.notifications.show({title:"Lead",message:"Renseignez au moins un nom, une entreprise ou une coordonn\xe9e",color:"orange"});create.mutate({first_name:values.first_name||null,last_name:values.last_name||null,company:values.company||null,emails:values.email?[values.email]:[],phones:values.phone?[values.phone]:[],linkedin_url:values.linkedin_url||null,note:values.note||null,next_action_due_at:values.next_action_due_at?new Date(values.next_action_due_at).toISOString():null,request_reconstruction:values.request_reconstruction},{onSuccess:data=>{onCreated?.({id:data.id,first_name:values.first_name||null,last_name:values.last_name||null,company:values.company||null});form.reset();onClose()}})}return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:opened,onClose:onClose,title:"Nouveau lead",children:/*#__PURE__*/(0,jsx_runtime.jsx)("form",{onSubmit:form.onSubmit(submit),children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{grow:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Pr\xe9nom",...form.getInputProps("first_name")}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Nom",...form.getInputProps("last_name")})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Entreprise",...form.getInputProps("company")}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"URL LinkedIn",placeholder:"https://www.linkedin.com/in/...",...form.getInputProps("linkedin_url")}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{grow:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Email",...form.getInputProps("email")}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"T\xe9l\xe9phone",...form.getInputProps("phone")})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Textarea,{label:"Note / prochaine action",...form.getInputProps("note")}),/*#__PURE__*/(0,jsx_runtime.jsx)(esm_index_mjs_.DateInput,{label:"Relancer le",placeholder:"Pas de date fix\xe9e",clearable:true,valueFormat:"DD/MM/YYYY",...form.getInputProps("next_action_due_at")}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Checkbox,{label:"Reconstruire l'historique (recherche multi-sources)",...form.getInputProps("request_reconstruction",{type:"checkbox"})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"default",onClick:onClose,children:"Annuler"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{type:"submit",loading:create.isPending,children:"Cr\xe9er"})]})]})})})}},479:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{P:()=>TEMPERATURE_META,o:()=>TEMPERATURE_ORDER});const TEMPERATURE_META={burning:{emoji:"\uD83D\uDD25\uD83D\uDD25",label:"Br\xfblant",order:5},hot:{emoji:"\uD83D\uDD25",label:"Chaud",order:4},warm:{emoji:"\uD83C\uDF21️",label:"Ti\xe8de",order:3},cold:{emoji:"❄️",label:"Froid",order:2},frozen:{emoji:"\uD83E\uDDCA",label:"Gel\xe9",order:1}};const TEMPERATURE_ORDER=["burning","hot","warm","cold","frozen"]},3697:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,{default:()=>Pipeline});var jsx_runtime=__webpack_require__(5893);var consume_shared_module_default_react_strict_=__webpack_require__(5850);var providers=__webpack_require__(7034);var index_mjs_=__webpack_require__(207);var esm_index_mjs_=__webpack_require__(3863);var tabler_icons_react_mjs_=__webpack_require__(9632);var index_js_=__webpack_require__(6197);var useApi=__webpack_require__(4148);function useSalesDeals(pipeline,status){const api=(0,useApi.h)();return(0,index_js_.useQuery)({queryKey:["tech","sales","deals",pipeline,status],queryFn:async()=>(await api.sales.listDealsV1({pipeline,status})).data,refetchOnWindowFocus:true})}var notifications_esm_index_mjs_=__webpack_require__(1455);function useExportDeals(){const api=(0,useApi.h)();return(0,index_js_.useMutation)({mutationFn:async()=>(await api.sales.exportDealsV1()).data,onSuccess:data=>{notifications_esm_index_mjs_.notifications.show({title:"Export",message:`Export lanc\xe9 : ${data?.rows??0} deal(s) seront \xe9crits dans l'onglet ${data?.worksheet??"de reporting"} dans quelques minutes`,color:"green"})},onError:err=>{notifications_esm_index_mjs_.notifications.show({title:"Export",message:err?.error?.error??err?.message??"\xc9chec de l'export",color:"red"})}})}var dates_esm_index_mjs_=__webpack_require__(9038);function useDeleteDeal(){const api=(0,useApi.h)();const queryClient=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async id=>(await api.sales.deleteDealV1({id})).data,onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:"Deal supprim\xe9",color:"green"});queryClient.invalidateQueries({queryKey:["tech","sales"]})},onError:err=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:err?.error?.error??err?.message??"\xc9chec de la suppression",color:"red"})}})}function useUpdateDeal(id){const api=(0,useApi.h)();const queryClient=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async payload=>(await api.sales.updateDealV1({id},payload)).data,onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:"Modifications enregistr\xe9es",color:"green"});queryClient.invalidateQueries({queryKey:["tech","sales"]})},onError:err=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:err?.error?.error??err?.message??"\xc9chec de la mise \xe0 jour",color:"red"})}})}const eurFormatter=new Intl.NumberFormat("fr-FR",{style:"currency",currency:"EUR",maximumFractionDigits:0});const dayFormatter=new Intl.DateTimeFormat("fr-FR",{timeZone:"Europe/Paris",day:"2-digit",month:"2-digit",year:"numeric"});function formatEur(value){if(Number.isNaN(value))return eurFormatter.format(0);return eurFormatter.format(value)}function formatAmount(value,currency){if("EUR"===currency||""===currency)return formatEur(value);return new Intl.NumberFormat("fr-FR",{style:"currency",currency,maximumFractionDigits:0}).format(value)}function formatDay(iso){if(null===iso)return"";const date=new Date(iso);if(Number.isNaN(date.getTime()))return"";return dayFormatter.format(date)}var temperature=__webpack_require__(479);const STATUS_META={open:{label:"Ouvert",color:"blue"},won:{label:"Gagn\xe9",color:"green"},lost:{label:"Perdu",color:"red"}};function personLabel(deal){const parts=[deal.lead.first_name,deal.lead.last_name].filter(Boolean);return parts.join(" ")}function DealDetailForm({deal,stages,onClose}){const update=useUpdateDeal(deal.id);const remove=useDeleteDeal();const[title,setTitle]=(0,consume_shared_module_default_react_strict_.useState)(deal.title);const[value,setValue]=(0,consume_shared_module_default_react_strict_.useState)(deal.value);const[probability,setProbability]=(0,consume_shared_module_default_react_strict_.useState)(null===deal.probability?"":deal.probability);const[expectedCloseDate,setExpectedCloseDate]=(0,consume_shared_module_default_react_strict_.useState)(deal.expected_close_date??"");const[stageId,setStageId]=(0,consume_shared_module_default_react_strict_.useState)(String(deal.stage_id));const[lostReason,setLostReason]=(0,consume_shared_module_default_react_strict_.useState)(deal.lost_reason??"");const statusMeta=STATUS_META[deal.status];function save(){update.mutate({title,value:""===value?0:Number(value),probability:""===probability?null:Number(probability),expected_close_date:""===expectedCloseDate?null:expectedCloseDate,stage_id:null===stageId?void 0:Number(stageId)})}function markWon(){update.mutate({status:"won"},{onSuccess:onClose})}function markLost(){update.mutate({status:"lost",lost_reason:""===lostReason?null:lostReason},{onSuccess:onClose})}function reopen(){update.mutate({status:"open"},{onSuccess:onClose})}function handleDelete(){remove.mutate(deal.id,{onSuccess:onClose})}return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",children:[statusMeta?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:statusMeta.color,children:statusMeta.label}):null,"won"===deal.status&&null!==deal.won_at?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:`Gagn\xe9 le ${formatDay(deal.won_at)}`}):null,"lost"===deal.status&&null!==deal.lost_at?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:`Perdu le ${formatDay(deal.lost_at)}`}):null]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:2,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:`${temperature.P[deal.lead.temperature]?.emoji??""} ${personLabel(deal)}`.trim()}),deal.lead.company?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:deal.lead.company}):null,/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Anchor,{href:"/console/sales",size:"sm",children:"Voir le lead"})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Divider,{}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Titre",value:title,onChange:e=>setTitle(e.currentTarget.value)}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{grow:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:"Montant",value:value,onChange:setValue,min:0,thousandSeparator:" ",decimalSeparator:",",suffix:` ${deal.currency}`}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:"Probabilit\xe9 (%)",value:probability,onChange:setProbability,min:0,max:100})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(dates_esm_index_mjs_.DateInput,{label:"\xc9ch\xe9ance",placeholder:"Pas de date fix\xe9e",clearable:true,valueFormat:"DD/MM/YYYY",value:expectedCloseDate?new Date(expectedCloseDate):null,onChange:v=>setExpectedCloseDate(v?new Date(v).toISOString():"")}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"\xc9tape",data:stages.map(s=>({value:String(s.id),label:s.name})),value:stageId,onChange:setStageId}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{color:"red",variant:"light",onClick:handleDelete,children:"Supprimer"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{loading:update.isPending,onClick:save,children:"Enregistrer"})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Divider,{mt:"md"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:5,children:"Statut"}),"open"===deal.status?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Raison de la perte (optionnelle)",value:lostReason,onChange:e=>setLostReason(e.currentTarget.value)}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{color:"red",variant:"light",loading:update.isPending,onClick:markLost,children:"Perdu"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{color:"green",loading:update.isPending,onClick:markWon,children:"Gagn\xe9"})]})]}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{justify:"flex-end",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"light",loading:update.isPending,onClick:reopen,children:"Rouvrir"})})]})}function DealDetailDrawer({deal,stages,onClose}){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Drawer,{opened:null!==deal,onClose:onClose,position:"right",size:"lg",title:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:4,children:"Deal"}),children:deal?/*#__PURE__*/(0,jsx_runtime.jsx)(DealDetailForm,{deal:deal,stages:stages,onClose:onClose},deal.id):null})}function stageName(stages,stageId){const stage=stages.find(s=>s.id===stageId);if(!stage)return"";return stage.name}function DealsTable({deals,stages,status,onRowClick}){const isLost="lost"===status;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{highlightOnHover:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Thead,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Titre"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Entreprise"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Montant"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:isLost?"Perdu le":"Gagn\xe9 le"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"\xc9tape"}),isLost?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Raison"}):null]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:deals.map(deal=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{style:{cursor:"pointer"},onClick:()=>onRowClick(deal.id),children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:deal.title}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:deal.lead.company??""}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:formatAmount(deal.value,deal.currency)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:formatDay(isLost?deal.lost_at:deal.won_at)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:stageName(stages,deal.stage_id)}),isLost?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:deal.lost_reason?void 0:"dimmed",children:deal.lost_reason??"Non renseign\xe9e"})}):null]},deal.id))})]})}function moveDealToStage(current,dealId,stageId){const deal=current.deals.find(d=>d.id===dealId);if(void 0===deal||deal.stage_id===stageId)return current;const fromStageId=deal.stage_id;return{stages:current.stages.map(stage=>{if(stage.id===fromStageId)return{...stage,deal_count:Math.max(0,stage.deal_count-1),total_value:stage.total_value-deal.value};if(stage.id===stageId)return{...stage,deal_count:stage.deal_count+1,total_value:stage.total_value+deal.value};return stage}),deals:current.deals.map(d=>d.id===dealId?{...d,stage_id:stageId}:d)}}function useMoveDealStage(pipeline,status){const api=(0,useApi.h)();const queryClient=(0,index_js_.useQueryClient)();const queryKey=["tech","sales","deals",pipeline,status];return(0,index_js_.useMutation)({mutationFn:async payload=>(await api.sales.updateDealV1({id:payload.id},{stage_id:payload.stage_id})).data,onMutate:async payload=>{await queryClient.cancelQueries({queryKey});const previous=queryClient.getQueryData(queryKey);if(void 0!==previous)queryClient.setQueryData(queryKey,moveDealToStage(previous,payload.id,payload.stage_id));return{previous}},onError:(err,_payload,context)=>{if(context?.previous!==void 0)queryClient.setQueryData(queryKey,context.previous);notifications_esm_index_mjs_.notifications.show({title:"Deal",message:err?.error?.error??err?.message??"\xc9chec du changement d'\xe9tape",color:"red"})},onSettled:()=>{queryClient.invalidateQueries({queryKey:["tech","sales"]})}})}function DealCard_personLabel(deal){const parts=[deal.lead.first_name,deal.lead.last_name].filter(Boolean);return parts.join(" ")}function DealCard({deal,stages,isDragging,onOpen,onDragStart,onDragEnd}){const update=useUpdateDeal(deal.id);const index=stages.findIndex(s=>s.id===deal.stage_id);const previous=index>0?stages[index-1]:null;const next=index>=0&&index<stages.length-1?stages[index+1]:null;function move(target){if(null===target)return;update.mutate({stage_id:target.id})}return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Card,{withBorder:true,padding:"sm",radius:"md",draggable:true,style:{cursor:isDragging?"grabbing":"grab",opacity:isDragging?.4:1,transition:"opacity 120ms ease"},onClick:()=>onOpen(deal.id),onDragStart:e=>{e.dataTransfer.effectAllowed="move";e.dataTransfer.setData("text/plain",String(deal.id));onDragStart(deal.id)},onDragEnd:onDragEnd,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:6,children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:4,wrap:"nowrap",align:"flex-start",style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconGripVertical,{size:16,"aria-hidden":true,style:{flexShrink:0,marginTop:2,color:"var(--mantine-color-dimmed)"}}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:500,size:"sm",lineClamp:2,children:deal.title})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:"blue",children:formatAmount(deal.value,deal.currency)})]}),deal.lead.company?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:deal.lead.company}):null,/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:`${temperature.P[deal.lead.temperature]?.emoji??""} ${DealCard_personLabel(deal)}`.trim()}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",children:[null!==deal.probability?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:"gray",size:"sm",children:`${deal.probability} %`}):null,null!==deal.expected_close_date?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:"gray",size:"sm",children:`\xc9ch\xe9ance : ${formatDay(deal.expected_close_date)}`}):null]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{variant:"subtle",size:"sm","aria-label":"\xc9tape pr\xe9c\xe9dente",disabled:null===previous||update.isPending,onClick:e=>{e.stopPropagation();move(previous)},children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconChevronLeft,{size:16})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{variant:"subtle",size:"sm","aria-label":"\xc9tape suivante",disabled:null===next||update.isPending,onClick:e=>{e.stopPropagation();move(next)},children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconChevronRight,{size:16})})]})]})})}function KanbanBoard({pipeline,status,stages,deals,onOpen}){const move=useMoveDealStage(pipeline,status);const[draggedId,setDraggedId]=(0,consume_shared_module_default_react_strict_.useState)(null);const[hoveredStageId,setHoveredStageId]=(0,consume_shared_module_default_react_strict_.useState)(null);const draggedDeal=null===draggedId?null:deals.find(d=>d.id===draggedId)??null;function resetDrag(){setDraggedId(null);setHoveredStageId(null)}function handleDrop(e,stage){e.preventDefault();const raw=Number(e.dataTransfer.getData("text/plain"));const dealId=Number.isFinite(raw)&&raw>0?raw:draggedId;resetDrag();if(null===dealId)return;const deal=deals.find(d=>d.id===dealId);if(void 0===deal||deal.stage_id===stage.id)return;move.mutate({id:deal.id,stage_id:stage.id})}if(0===stages.length)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:"Aucune \xe9tape configur\xe9e pour ce pipeline"});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{style:{display:"flex",gap:"var(--mantine-spacing-md)",alignItems:"flex-start",overflowX:"auto",paddingBottom:"var(--mantine-spacing-sm)"},children:stages.map(stage=>{const stageDeals=deals.filter(d=>d.stage_id===stage.id);const isDropTarget=hoveredStageId===stage.id&&null!==draggedDeal&&draggedDeal.stage_id!==stage.id;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Paper,{withBorder:true,radius:"md",p:"sm",style:{flex:"0 0 300px",width:300,backgroundColor:isDropTarget?"var(--mantine-color-blue-light)":void 0,outline:isDropTarget?"2px solid var(--mantine-color-blue-filled)":void 0,outlineOffset:2,transition:"background-color 120ms ease"},onDragOver:e=>{if(null===draggedId)return;e.preventDefault();e.dataTransfer.dropEffect="move";if(hoveredStageId!==stage.id)setHoveredStageId(stage.id)},onDragLeave:e=>{if(e.currentTarget.contains(e.relatedTarget))return;if(hoveredStageId===stage.id)setHoveredStageId(null)},onDrop:e=>handleDrop(e,stage),children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",mih:140,children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:2,children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:600,size:"sm",children:stage.name}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:"gray",children:stage.deal_count})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:formatEur(stage.total_value)})]}),0===stageDeals.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:isDropTarget?"D\xe9poser ici":"Aucun deal"}):null,stageDeals.map(deal=>/*#__PURE__*/(0,jsx_runtime.jsx)(DealCard,{deal:deal,stages:stages,isDragging:draggedId===deal.id,onOpen:onOpen,onDragStart:setDraggedId,onDragEnd:resetDrag},deal.id))]})},stage.id)})})}function useCreateDeal(){const api=(0,useApi.h)();const queryClient=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async payload=>(await api.sales.createDealV1(payload)).data,onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:"Deal cr\xe9\xe9",color:"green"});queryClient.invalidateQueries({queryKey:["tech","sales"]})},onError:err=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:err?.error?.error??err?.message??"\xc9chec de la cr\xe9ation",color:"red"})}})}var leadsQuery=__webpack_require__(1334);var NewLeadModal=__webpack_require__(9328);function leadLabel(lead){const name=[lead.first_name,lead.last_name].filter(Boolean).join(" ");if(lead.company&&name)return`${name} (${lead.company})`;if(lead.company)return lead.company;if(name)return name;return`Lead ${lead.id}`}function NewDealForm({onClose,stages}){const leads=(0,leadsQuery.m)("active");const create=useCreateDeal();const[leadId,setLeadId]=(0,consume_shared_module_default_react_strict_.useState)(null);const[newLeadOpened,setNewLeadOpened]=(0,consume_shared_module_default_react_strict_.useState)(false);const[createdLead,setCreatedLead]=(0,consume_shared_module_default_react_strict_.useState)(null);const[title,setTitle]=(0,consume_shared_module_default_react_strict_.useState)("");const[value,setValue]=(0,consume_shared_module_default_react_strict_.useState)("");const[stageId,setStageId]=(0,consume_shared_module_default_react_strict_.useState)(stages.length>0?String(stages[0].id):null);const leadOptions=(leads.data?.leads??[]).map(lead=>({value:String(lead.id),label:leadLabel(lead)}));if(createdLead&&!leadOptions.some(option=>option.value===String(createdLead.id)))leadOptions.push({value:String(createdLead.id),label:leadLabel(createdLead)});function submit(){if(null===leadId||null===stageId||""===title.trim())return void notifications_esm_index_mjs_.notifications.show({title:"Deal",message:"Renseignez un lead, un titre et une \xe9tape",color:"orange"});create.mutate({lead_id:Number(leadId),stage_id:Number(stageId),title:title.trim(),value:""===value?0:Number(value),currency:"EUR"},{onSuccess:onClose})}return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"Lead",placeholder:"Rechercher un lead",searchable:true,nothingFoundMessage:"Aucun lead",data:leadOptions,value:leadId,onChange:setLeadId}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",size:"compact-sm",style:{alignSelf:"flex-start"},onClick:()=>setNewLeadOpened(true),children:"+ Cr\xe9er un nouveau lead"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Titre",value:title,onChange:e=>setTitle(e.currentTarget.value)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:"Montant (EUR)",value:value,onChange:setValue,min:0,thousandSeparator:" ",decimalSeparator:","}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"\xc9tape",data:stages.map(s=>({value:String(s.id),label:s.name})),value:stageId,onChange:setStageId}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"default",onClick:onClose,children:"Annuler"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{loading:create.isPending,onClick:submit,children:"Cr\xe9er"})]}),newLeadOpened?/*#__PURE__*/(0,jsx_runtime.jsx)(NewLeadModal.A,{opened:true,onClose:()=>setNewLeadOpened(false),onCreated:lead=>{setCreatedLead(lead);setLeadId(String(lead.id))}}):null]})}function NewDealModal({opened,onClose,stages}){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:opened,onClose:onClose,title:"Nouveau deal",children:opened?/*#__PURE__*/(0,jsx_runtime.jsx)(NewDealForm,{onClose:onClose,stages:stages}):null})}function PipelineApp(){const[pipeline,setPipeline]=(0,consume_shared_module_default_react_strict_.useState)("new_business");const[status,setStatus]=(0,consume_shared_module_default_react_strict_.useState)("open");const[selectedId,setSelectedId]=(0,consume_shared_module_default_react_strict_.useState)(null);const[newDealOpened,newDeal]=(0,esm_index_mjs_.useDisclosure)(false);const deals=useSalesDeals(pipeline,status);const exportDeals=useExportDeals();const stages=deals.data?.stages??[];const rows=deals.data?.deals??[];const selected=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{if(null===selectedId)return null;return rows.find(d=>d.id===selectedId)??null},[rows,selectedId]);const total=rows.reduce((acc,d)=>acc+d.value,0);return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Container,{fluid:true,my:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",mb:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:2,children:"Pipeline"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:"blue",children:`${rows.length} deal(s) : ${formatEur(total)}`}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{onClick:newDeal.open,disabled:0===stages.length,children:"+ Nouveau deal"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"light",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTableExport,{size:16}),loading:exportDeals.isPending,disabled:exportDeals.isPending,onClick:()=>exportDeals.mutate(),children:"Exporter vers le reporting"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",mb:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SegmentedControl,{value:pipeline,onChange:setPipeline,data:[{label:"New Business",value:"new_business"},{label:"Upsell / Cross-sell",value:"upsell"}]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SegmentedControl,{value:status,onChange:setStatus,data:[{label:"Ouverts",value:"open"},{label:"Gagn\xe9s",value:"won"},{label:"Perdus",value:"lost"}]})]}),deals.isLoading?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Loader,{}):null,deals.data&&"open"===status?/*#__PURE__*/(0,jsx_runtime.jsx)(KanbanBoard,{pipeline:pipeline,status:status,stages:stages,deals:rows,onOpen:setSelectedId}):null,deals.data&&"open"!==status?/*#__PURE__*/(0,jsx_runtime.jsx)(jsx_runtime.Fragment,{children:0===rows.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:"Aucun deal"}):/*#__PURE__*/(0,jsx_runtime.jsx)(DealsTable,{deals:rows,stages:stages,status:status,onRowClick:setSelectedId})}):null,/*#__PURE__*/(0,jsx_runtime.jsx)(NewDealModal,{opened:newDealOpened,onClose:newDeal.close,stages:stages}),/*#__PURE__*/(0,jsx_runtime.jsx)(DealDetailDrawer,{deal:selected,stages:stages,onClose:()=>setSelectedId(null)})]})}function Pipeline(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(consume_shared_module_default_react_strict_.StrictMode,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(providers.C,{...props,children:/*#__PURE__*/(0,jsx_runtime.jsx)(PipelineApp,{})})})}}}]);
1
+ "use strict";(globalThis["chunk_tech_app"]=globalThis["chunk_tech_app"]||[]).push([["2149"],{1334:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{m:()=>useSalesLeads});var _tanstack_react_query__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(6197);var _useApi_ts__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(4148);function useSalesLeads(status){const api=(0,_useApi_ts__WEBPACK_IMPORTED_MODULE_1__.h)();return(0,_tanstack_react_query__WEBPACK_IMPORTED_MODULE_0__.useQuery)({queryKey:["tech","sales","leads",status],queryFn:async()=>(await api.sales.listLeadsV1({status})).data,refetchOnWindowFocus:true})}},9328:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{A:()=>NewLeadModal});var jsx_runtime=__webpack_require__(5893);var index_mjs_=__webpack_require__(207);var esm_index_mjs_=__webpack_require__(9038);var form_esm_index_mjs_=__webpack_require__(5021);var notifications_esm_index_mjs_=__webpack_require__(1455);var index_js_=__webpack_require__(6197);var useApi=__webpack_require__(4148);function useCreateLead(){const api=(0,useApi.h)();const queryClient=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async payload=>(await api.sales.createLeadV1(payload)).data,onSuccess:data=>{notifications_esm_index_mjs_.notifications.show({title:"Lead",message:data?.attached?"Coordonn\xe9e d\xe9j\xe0 connue — rattach\xe9 au lead existant":"Lead cr\xe9\xe9",color:"green"});queryClient.invalidateQueries({queryKey:["tech","sales"]})},onError:err=>{notifications_esm_index_mjs_.notifications.show({title:"Lead",message:err?.error?.error??err?.message??"\xc9chec de la cr\xe9ation",color:"red"})}})}function NewLeadModal({opened,onClose,onCreated}){const create=useCreateLead();const form=(0,form_esm_index_mjs_.useForm)({initialValues:{first_name:"",last_name:"",company:"",email:"",phone:"",linkedin_url:"",note:"",next_action_due_at:null,request_reconstruction:true}});function submit(values){const hasAny=Boolean(values.first_name)||Boolean(values.last_name)||Boolean(values.company)||Boolean(values.email)||Boolean(values.phone)||Boolean(values.linkedin_url);if(!hasAny)return void notifications_esm_index_mjs_.notifications.show({title:"Lead",message:"Renseignez au moins un nom, une entreprise ou une coordonn\xe9e",color:"orange"});create.mutate({first_name:values.first_name||null,last_name:values.last_name||null,company:values.company||null,emails:values.email?[values.email]:[],phones:values.phone?[values.phone]:[],linkedin_url:values.linkedin_url||null,note:values.note||null,next_action_due_at:values.next_action_due_at?new Date(values.next_action_due_at).toISOString():null,request_reconstruction:values.request_reconstruction},{onSuccess:data=>{onCreated?.({id:data.id,first_name:values.first_name||null,last_name:values.last_name||null,company:values.company||null});form.reset();onClose()}})}return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:opened,onClose:onClose,title:"Nouveau lead",children:/*#__PURE__*/(0,jsx_runtime.jsx)("form",{onSubmit:form.onSubmit(submit),children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{grow:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Pr\xe9nom",...form.getInputProps("first_name")}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Nom",...form.getInputProps("last_name")})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Entreprise",...form.getInputProps("company")}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"URL LinkedIn",placeholder:"https://www.linkedin.com/in/...",...form.getInputProps("linkedin_url")}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{grow:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Email",...form.getInputProps("email")}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"T\xe9l\xe9phone",...form.getInputProps("phone")})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Textarea,{label:"Note / prochaine action",...form.getInputProps("note")}),/*#__PURE__*/(0,jsx_runtime.jsx)(esm_index_mjs_.DateInput,{label:"Relancer le",placeholder:"Pas de date fix\xe9e",clearable:true,valueFormat:"DD/MM/YYYY",...form.getInputProps("next_action_due_at")}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Checkbox,{label:"Reconstruire l'historique (recherche multi-sources)",...form.getInputProps("request_reconstruction",{type:"checkbox"})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"default",onClick:onClose,children:"Annuler"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{type:"submit",loading:create.isPending,children:"Cr\xe9er"})]})]})})})}},479:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{P:()=>TEMPERATURE_META,o:()=>TEMPERATURE_ORDER});const TEMPERATURE_META={burning:{emoji:"\uD83D\uDD25\uD83D\uDD25",label:"Br\xfblant",order:5},hot:{emoji:"\uD83D\uDD25",label:"Chaud",order:4},warm:{emoji:"\uD83C\uDF21️",label:"Ti\xe8de",order:3},cold:{emoji:"❄️",label:"Froid",order:2},frozen:{emoji:"\uD83E\uDDCA",label:"Gel\xe9",order:1}};const TEMPERATURE_ORDER=["burning","hot","warm","cold","frozen"]},1717:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,{default:()=>Pipeline});var jsx_runtime=__webpack_require__(5893);var consume_shared_module_default_react_strict_=__webpack_require__(5850);var providers=__webpack_require__(7034);var index_mjs_=__webpack_require__(207);var esm_index_mjs_=__webpack_require__(3863);var tabler_icons_react_mjs_=__webpack_require__(9632);var index_js_=__webpack_require__(6197);var useApi=__webpack_require__(4148);function useSalesDeals(pipeline,status){const api=(0,useApi.h)();return(0,index_js_.useQuery)({queryKey:["tech","sales","deals",pipeline,status],queryFn:async()=>(await api.sales.listDealsV1({pipeline,status})).data,refetchOnWindowFocus:true})}var notifications_esm_index_mjs_=__webpack_require__(1455);function useExportDeals(){const api=(0,useApi.h)();return(0,index_js_.useMutation)({mutationFn:async()=>(await api.sales.exportDealsV1()).data,onSuccess:data=>{notifications_esm_index_mjs_.notifications.show({title:"Export",message:`Export lanc\xe9 : ${data?.rows??0} deal(s) seront \xe9crits dans l'onglet ${data?.worksheet??"de reporting"} dans quelques minutes`,color:"green"})},onError:err=>{notifications_esm_index_mjs_.notifications.show({title:"Export",message:err?.error?.error??err?.message??"\xc9chec de l'export",color:"red"})}})}var dates_esm_index_mjs_=__webpack_require__(9038);function useSalesDealStages(){const api=(0,useApi.h)();return(0,index_js_.useQuery)({queryKey:["tech","sales","deal-stages"],queryFn:async()=>(await api.sales.listDealStagesV1()).data,staleTime:36e5,refetchOnWindowFocus:false})}function useDeleteDeal(){const api=(0,useApi.h)();const queryClient=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async id=>(await api.sales.deleteDealV1({id})).data,onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:"Deal supprim\xe9",color:"green"});queryClient.invalidateQueries({queryKey:["tech","sales"]})},onError:err=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:err?.error?.error??err?.message??"\xc9chec de la suppression",color:"red"})}})}function useUpdateDeal(id){const api=(0,useApi.h)();const queryClient=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async payload=>(await api.sales.updateDealV1({id},payload)).data,onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:"Modifications enregistr\xe9es",color:"green"});queryClient.invalidateQueries({queryKey:["tech","sales"]})},onError:err=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:err?.error?.error??err?.message??"\xc9chec de la mise \xe0 jour",color:"red"})}})}const eurFormatter=new Intl.NumberFormat("fr-FR",{style:"currency",currency:"EUR",maximumFractionDigits:0});const dayFormatter=new Intl.DateTimeFormat("fr-FR",{timeZone:"Europe/Paris",day:"2-digit",month:"2-digit",year:"numeric"});function formatEur(value){if(Number.isNaN(value))return eurFormatter.format(0);return eurFormatter.format(value)}function formatAmount(value,currency){if("EUR"===currency||""===currency)return formatEur(value);return new Intl.NumberFormat("fr-FR",{style:"currency",currency,maximumFractionDigits:0}).format(value)}function formatDay(iso){if(null===iso)return"";const date=new Date(iso);if(Number.isNaN(date.getTime()))return"";return dayFormatter.format(date)}var temperature=__webpack_require__(479);const STATUS_META={open:{label:"Ouvert",color:"blue"},won:{label:"Gagn\xe9",color:"green"},lost:{label:"Perdu",color:"red"}};const PIPELINE_LABEL={new_business:"New Business",upsell:"Upsell / Cross-sell"};const PIPELINE_OPTIONS=[{value:"new_business",label:PIPELINE_LABEL.new_business},{value:"upsell",label:PIPELINE_LABEL.upsell}];function personLabel(deal){const parts=[deal.lead.first_name,deal.lead.last_name].filter(Boolean);return parts.join(" ")}function stagesOfPipeline(allStages,pipeline){return allStages.filter(s=>s.pipeline===pipeline).sort((a,b)=>a.order_nr-b.order_nr)}function pipelineOfStage(allStages,stageId){const current=allStages.find(s=>s.id===stageId);if(void 0===current)return"new_business";return current.pipeline}function DealDetailForm({deal,stages,allStages,onClose}){const update=useUpdateDeal(deal.id);const remove=useDeleteDeal();const initialPipeline=(0,consume_shared_module_default_react_strict_.useMemo)(()=>pipelineOfStage(allStages,deal.stage_id),[allStages,deal.stage_id]);const[title,setTitle]=(0,consume_shared_module_default_react_strict_.useState)(deal.title);const[value,setValue]=(0,consume_shared_module_default_react_strict_.useState)(deal.value);const[probability,setProbability]=(0,consume_shared_module_default_react_strict_.useState)(null===deal.probability?"":deal.probability);const[expectedCloseDate,setExpectedCloseDate]=(0,consume_shared_module_default_react_strict_.useState)(deal.expected_close_date??"");const[pipeline,setPipeline]=(0,consume_shared_module_default_react_strict_.useState)(initialPipeline);const[stageId,setStageId]=(0,consume_shared_module_default_react_strict_.useState)(String(deal.stage_id));const[lostReason,setLostReason]=(0,consume_shared_module_default_react_strict_.useState)(deal.lost_reason??"");const statusMeta=STATUS_META[deal.status];const stageOptions=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{if(0===allStages.length)return[...stages].sort((a,b)=>a.order_nr-b.order_nr).map(s=>({value:String(s.id),label:s.name}));return stagesOfPipeline(allStages,pipeline).map(s=>({value:String(s.id),label:s.name}))},[allStages,stages,pipeline]);function changePipeline(next){if(null===next)return;const target=next;setPipeline(target);const first=stagesOfPipeline(allStages,target)[0];setStageId(void 0===first?null:String(first.id))}function save(){const moved=pipeline!==initialPipeline;update.mutate({title,value:""===value?0:Number(value),probability:""===probability?null:Number(probability),expected_close_date:""===expectedCloseDate?null:expectedCloseDate,stage_id:null===stageId?void 0:Number(stageId)},moved?{onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({title:"Pipeline",message:`Deal d\xe9plac\xe9 vers ${PIPELINE_LABEL[pipeline]}`,color:"green"});onClose()}}:void 0)}function markWon(){update.mutate({status:"won"},{onSuccess:onClose})}function markLost(){update.mutate({status:"lost",lost_reason:""===lostReason?null:lostReason},{onSuccess:onClose})}function reopen(){update.mutate({status:"open"},{onSuccess:onClose})}function handleDelete(){remove.mutate(deal.id,{onSuccess:onClose})}return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",children:[statusMeta?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:statusMeta.color,children:statusMeta.label}):null,"won"===deal.status&&null!==deal.won_at?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:`Gagn\xe9 le ${formatDay(deal.won_at)}`}):null,"lost"===deal.status&&null!==deal.lost_at?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:`Perdu le ${formatDay(deal.lost_at)}`}):null]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:2,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:`${temperature.P[deal.lead.temperature]?.emoji??""} ${personLabel(deal)}`.trim()}),deal.lead.company?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:deal.lead.company}):null,/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Anchor,{href:"/console/sales",size:"sm",children:"Voir le lead"})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Divider,{}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Titre",value:title,onChange:e=>setTitle(e.currentTarget.value)}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{grow:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:"Montant",value:value,onChange:setValue,min:0,thousandSeparator:" ",decimalSeparator:",",suffix:` ${deal.currency}`}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:"Probabilit\xe9 (%)",value:probability,onChange:setProbability,min:0,max:100})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(dates_esm_index_mjs_.DateInput,{label:"\xc9ch\xe9ance",placeholder:"Pas de date fix\xe9e",clearable:true,valueFormat:"DD/MM/YYYY",value:expectedCloseDate?new Date(expectedCloseDate):null,onChange:v=>setExpectedCloseDate(v?new Date(v).toISOString():"")}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"Pipeline",description:0===allStages.length?"Liste des \xe9tapes indisponible, le d\xe9placement n'est pas possible":void 0,data:PIPELINE_OPTIONS,value:pipeline,onChange:changePipeline,disabled:0===allStages.length}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"\xc9tape",data:stageOptions,value:stageId,onChange:setStageId}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{color:"red",variant:"light",onClick:handleDelete,children:"Supprimer"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{loading:update.isPending,onClick:save,children:"Enregistrer"})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Divider,{mt:"md"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:5,children:"Statut"}),"open"===deal.status?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Raison de la perte (optionnelle)",value:lostReason,onChange:e=>setLostReason(e.currentTarget.value)}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{color:"red",variant:"light",loading:update.isPending,onClick:markLost,children:"Perdu"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{color:"green",loading:update.isPending,onClick:markWon,children:"Gagn\xe9"})]})]}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{justify:"flex-end",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"light",loading:update.isPending,onClick:reopen,children:"Rouvrir"})})]})}function DealDetailDrawer({deal,stages,onClose}){const dealStages=useSalesDealStages();return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Drawer,{opened:null!==deal,onClose:onClose,position:"right",size:"lg",title:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:4,children:"Deal"}),children:null===deal?null:dealStages.isPending?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Loader,{}):/*#__PURE__*/(0,jsx_runtime.jsx)(DealDetailForm,{deal:deal,stages:stages,allStages:dealStages.data?.stages??[],onClose:onClose},deal.id)})}function stageName(stages,stageId){const stage=stages.find(s=>s.id===stageId);if(!stage)return"";return stage.name}function DealsTable({deals,stages,status,onRowClick}){const isLost="lost"===status;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{highlightOnHover:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Thead,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Titre"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Entreprise"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Montant"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:isLost?"Perdu le":"Gagn\xe9 le"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"\xc9tape"}),isLost?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Raison"}):null]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:deals.map(deal=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{style:{cursor:"pointer"},onClick:()=>onRowClick(deal.id),children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:deal.title}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:deal.lead.company??""}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:formatAmount(deal.value,deal.currency)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:formatDay(isLost?deal.lost_at:deal.won_at)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:stageName(stages,deal.stage_id)}),isLost?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:deal.lost_reason?void 0:"dimmed",children:deal.lost_reason??"Non renseign\xe9e"})}):null]},deal.id))})]})}function moveDealToStage(current,dealId,stageId){const deal=current.deals.find(d=>d.id===dealId);if(void 0===deal||deal.stage_id===stageId)return current;const fromStageId=deal.stage_id;return{stages:current.stages.map(stage=>{if(stage.id===fromStageId)return{...stage,deal_count:Math.max(0,stage.deal_count-1),total_value:stage.total_value-deal.value};if(stage.id===stageId)return{...stage,deal_count:stage.deal_count+1,total_value:stage.total_value+deal.value};return stage}),deals:current.deals.map(d=>d.id===dealId?{...d,stage_id:stageId}:d)}}function useMoveDealStage(pipeline,status){const api=(0,useApi.h)();const queryClient=(0,index_js_.useQueryClient)();const queryKey=["tech","sales","deals",pipeline,status];return(0,index_js_.useMutation)({mutationFn:async payload=>(await api.sales.updateDealV1({id:payload.id},{stage_id:payload.stage_id})).data,onMutate:async payload=>{await queryClient.cancelQueries({queryKey});const previous=queryClient.getQueryData(queryKey);if(void 0!==previous)queryClient.setQueryData(queryKey,moveDealToStage(previous,payload.id,payload.stage_id));return{previous}},onError:(err,_payload,context)=>{if(context?.previous!==void 0)queryClient.setQueryData(queryKey,context.previous);notifications_esm_index_mjs_.notifications.show({title:"Deal",message:err?.error?.error??err?.message??"\xc9chec du changement d'\xe9tape",color:"red"})},onSettled:()=>{queryClient.invalidateQueries({queryKey:["tech","sales"]})}})}function DealCard_personLabel(deal){const parts=[deal.lead.first_name,deal.lead.last_name].filter(Boolean);return parts.join(" ")}function DealCard({deal,stages,isDragging,onOpen,onDragStart,onDragEnd}){const update=useUpdateDeal(deal.id);const index=stages.findIndex(s=>s.id===deal.stage_id);const previous=index>0?stages[index-1]:null;const next=index>=0&&index<stages.length-1?stages[index+1]:null;function move(target){if(null===target)return;update.mutate({stage_id:target.id})}return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Card,{withBorder:true,padding:"sm",radius:"md",draggable:true,style:{cursor:isDragging?"grabbing":"grab",opacity:isDragging?.4:1,transition:"opacity 120ms ease"},onClick:()=>onOpen(deal.id),onDragStart:e=>{e.dataTransfer.effectAllowed="move";e.dataTransfer.setData("text/plain",String(deal.id));onDragStart(deal.id)},onDragEnd:onDragEnd,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:6,children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:4,wrap:"nowrap",align:"flex-start",style:{minWidth:0},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconGripVertical,{size:16,"aria-hidden":true,style:{flexShrink:0,marginTop:2,color:"var(--mantine-color-dimmed)"}}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:500,size:"sm",lineClamp:2,children:deal.title})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:"blue",children:formatAmount(deal.value,deal.currency)})]}),deal.lead.company?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:deal.lead.company}):null,/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:`${temperature.P[deal.lead.temperature]?.emoji??""} ${DealCard_personLabel(deal)}`.trim()}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",children:[null!==deal.probability?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:"gray",size:"sm",children:`${deal.probability} %`}):null,null!==deal.expected_close_date?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:"gray",size:"sm",children:`\xc9ch\xe9ance : ${formatDay(deal.expected_close_date)}`}):null]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{variant:"subtle",size:"sm","aria-label":"\xc9tape pr\xe9c\xe9dente",disabled:null===previous||update.isPending,onClick:e=>{e.stopPropagation();move(previous)},children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconChevronLeft,{size:16})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{variant:"subtle",size:"sm","aria-label":"\xc9tape suivante",disabled:null===next||update.isPending,onClick:e=>{e.stopPropagation();move(next)},children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconChevronRight,{size:16})})]})]})})}function KanbanBoard({pipeline,status,stages,deals,onOpen}){const move=useMoveDealStage(pipeline,status);const[draggedId,setDraggedId]=(0,consume_shared_module_default_react_strict_.useState)(null);const[hoveredStageId,setHoveredStageId]=(0,consume_shared_module_default_react_strict_.useState)(null);const draggedDeal=null===draggedId?null:deals.find(d=>d.id===draggedId)??null;function resetDrag(){setDraggedId(null);setHoveredStageId(null)}function handleDrop(e,stage){e.preventDefault();const raw=Number(e.dataTransfer.getData("text/plain"));const dealId=Number.isFinite(raw)&&raw>0?raw:draggedId;resetDrag();if(null===dealId)return;const deal=deals.find(d=>d.id===dealId);if(void 0===deal||deal.stage_id===stage.id)return;move.mutate({id:deal.id,stage_id:stage.id})}if(0===stages.length)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:"Aucune \xe9tape configur\xe9e pour ce pipeline"});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{style:{display:"flex",gap:"var(--mantine-spacing-md)",alignItems:"flex-start",overflowX:"auto",paddingBottom:"var(--mantine-spacing-sm)"},children:stages.map(stage=>{const stageDeals=deals.filter(d=>d.stage_id===stage.id);const isDropTarget=hoveredStageId===stage.id&&null!==draggedDeal&&draggedDeal.stage_id!==stage.id;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Paper,{withBorder:true,radius:"md",p:"sm",style:{flex:"0 0 300px",width:300,backgroundColor:isDropTarget?"var(--mantine-color-blue-light)":void 0,outline:isDropTarget?"2px solid var(--mantine-color-blue-filled)":void 0,outlineOffset:2,transition:"background-color 120ms ease"},onDragOver:e=>{if(null===draggedId)return;e.preventDefault();e.dataTransfer.dropEffect="move";if(hoveredStageId!==stage.id)setHoveredStageId(stage.id)},onDragLeave:e=>{if(e.currentTarget.contains(e.relatedTarget))return;if(hoveredStageId===stage.id)setHoveredStageId(null)},onDrop:e=>handleDrop(e,stage),children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",mih:140,children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:2,children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:600,size:"sm",children:stage.name}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:"gray",children:stage.deal_count})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:formatEur(stage.total_value)})]}),0===stageDeals.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:isDropTarget?"D\xe9poser ici":"Aucun deal"}):null,stageDeals.map(deal=>/*#__PURE__*/(0,jsx_runtime.jsx)(DealCard,{deal:deal,stages:stages,isDragging:draggedId===deal.id,onOpen:onOpen,onDragStart:setDraggedId,onDragEnd:resetDrag},deal.id))]})},stage.id)})})}function useCreateDeal(){const api=(0,useApi.h)();const queryClient=(0,index_js_.useQueryClient)();return(0,index_js_.useMutation)({mutationFn:async payload=>(await api.sales.createDealV1(payload)).data,onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:"Deal cr\xe9\xe9",color:"green"});queryClient.invalidateQueries({queryKey:["tech","sales"]})},onError:err=>{notifications_esm_index_mjs_.notifications.show({title:"Deal",message:err?.error?.error??err?.message??"\xc9chec de la cr\xe9ation",color:"red"})}})}var leadsQuery=__webpack_require__(1334);var NewLeadModal=__webpack_require__(9328);function leadLabel(lead){const name=[lead.first_name,lead.last_name].filter(Boolean).join(" ");if(lead.company&&name)return`${name} (${lead.company})`;if(lead.company)return lead.company;if(name)return name;return`Lead ${lead.id}`}function NewDealForm({onClose,stages}){const leads=(0,leadsQuery.m)("active");const create=useCreateDeal();const[leadId,setLeadId]=(0,consume_shared_module_default_react_strict_.useState)(null);const[newLeadOpened,setNewLeadOpened]=(0,consume_shared_module_default_react_strict_.useState)(false);const[createdLead,setCreatedLead]=(0,consume_shared_module_default_react_strict_.useState)(null);const[title,setTitle]=(0,consume_shared_module_default_react_strict_.useState)("");const[value,setValue]=(0,consume_shared_module_default_react_strict_.useState)("");const[stageId,setStageId]=(0,consume_shared_module_default_react_strict_.useState)(stages.length>0?String(stages[0].id):null);const leadOptions=(leads.data?.leads??[]).map(lead=>({value:String(lead.id),label:leadLabel(lead)}));if(createdLead&&!leadOptions.some(option=>option.value===String(createdLead.id)))leadOptions.push({value:String(createdLead.id),label:leadLabel(createdLead)});function submit(){if(null===leadId||null===stageId||""===title.trim())return void notifications_esm_index_mjs_.notifications.show({title:"Deal",message:"Renseignez un lead, un titre et une \xe9tape",color:"orange"});create.mutate({lead_id:Number(leadId),stage_id:Number(stageId),title:title.trim(),value:""===value?0:Number(value),currency:"EUR"},{onSuccess:onClose})}return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"Lead",placeholder:"Rechercher un lead",searchable:true,nothingFoundMessage:"Aucun lead",data:leadOptions,value:leadId,onChange:setLeadId}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",size:"compact-sm",style:{alignSelf:"flex-start"},onClick:()=>setNewLeadOpened(true),children:"+ Cr\xe9er un nouveau lead"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:"Titre",value:title,onChange:e=>setTitle(e.currentTarget.value)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:"Montant (EUR)",value:value,onChange:setValue,min:0,thousandSeparator:" ",decimalSeparator:","}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:"\xc9tape",data:stages.map(s=>({value:String(s.id),label:s.name})),value:stageId,onChange:setStageId}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"default",onClick:onClose,children:"Annuler"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{loading:create.isPending,onClick:submit,children:"Cr\xe9er"})]}),newLeadOpened?/*#__PURE__*/(0,jsx_runtime.jsx)(NewLeadModal.A,{opened:true,onClose:()=>setNewLeadOpened(false),onCreated:lead=>{setCreatedLead(lead);setLeadId(String(lead.id))}}):null]})}function NewDealModal({opened,onClose,stages}){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:opened,onClose:onClose,title:"Nouveau deal",children:opened?/*#__PURE__*/(0,jsx_runtime.jsx)(NewDealForm,{onClose:onClose,stages:stages}):null})}function PipelineApp(){const[pipeline,setPipeline]=(0,consume_shared_module_default_react_strict_.useState)("new_business");const[status,setStatus]=(0,consume_shared_module_default_react_strict_.useState)("open");const[selectedId,setSelectedId]=(0,consume_shared_module_default_react_strict_.useState)(null);const[newDealOpened,newDeal]=(0,esm_index_mjs_.useDisclosure)(false);const deals=useSalesDeals(pipeline,status);const exportDeals=useExportDeals();const stages=deals.data?.stages??[];const rows=deals.data?.deals??[];const selected=(0,consume_shared_module_default_react_strict_.useMemo)(()=>{if(null===selectedId)return null;return rows.find(d=>d.id===selectedId)??null},[rows,selectedId]);const total=rows.reduce((acc,d)=>acc+d.value,0);return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Container,{fluid:true,my:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",mb:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:2,children:"Pipeline"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",color:"blue",children:`${rows.length} deal(s) : ${formatEur(total)}`}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{onClick:newDeal.open,disabled:0===stages.length,children:"+ Nouveau deal"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"light",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTableExport,{size:16}),loading:exportDeals.isPending,disabled:exportDeals.isPending,onClick:()=>exportDeals.mutate(),children:"Exporter vers le reporting"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",mb:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SegmentedControl,{value:pipeline,onChange:setPipeline,data:[{label:"New Business",value:"new_business"},{label:"Upsell / Cross-sell",value:"upsell"}]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SegmentedControl,{value:status,onChange:setStatus,data:[{label:"Ouverts",value:"open"},{label:"Gagn\xe9s",value:"won"},{label:"Perdus",value:"lost"}]})]}),deals.isLoading?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Loader,{}):null,deals.data&&"open"===status?/*#__PURE__*/(0,jsx_runtime.jsx)(KanbanBoard,{pipeline:pipeline,status:status,stages:stages,deals:rows,onOpen:setSelectedId}):null,deals.data&&"open"!==status?/*#__PURE__*/(0,jsx_runtime.jsx)(jsx_runtime.Fragment,{children:0===rows.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:"Aucun deal"}):/*#__PURE__*/(0,jsx_runtime.jsx)(DealsTable,{deals:rows,stages:stages,status:status,onRowClick:setSelectedId})}):null,/*#__PURE__*/(0,jsx_runtime.jsx)(NewDealModal,{opened:newDealOpened,onClose:newDeal.close,stages:stages}),/*#__PURE__*/(0,jsx_runtime.jsx)(DealDetailDrawer,{deal:selected,stages:stages,onClose:()=>setSelectedId(null)})]})}function Pipeline(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(consume_shared_module_default_react_strict_.StrictMode,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(providers.C,{...props,children:/*#__PURE__*/(0,jsx_runtime.jsx)(PipelineApp,{})})})}}}]);