@airporting/integrations-app 0.4.121 → 0.4.123

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.
Files changed (37) hide show
  1. package/dist/mf/1018.js +1 -1
  2. package/dist/mf/1067.js +1 -1
  3. package/dist/mf/1857.js +1 -1
  4. package/dist/mf/2070.css +73 -73
  5. package/dist/mf/2070.js +1 -1
  6. package/dist/mf/3134.js +1 -1
  7. package/dist/mf/4756.js +2 -2
  8. package/dist/mf/5475.js +1 -1
  9. package/dist/mf/5625.js +1 -1
  10. package/dist/mf/5741.js +1 -1
  11. package/dist/mf/6124.js +1 -1
  12. package/dist/mf/6702.js +1 -1
  13. package/dist/mf/7285.js +1 -1
  14. package/dist/mf/7286.js +1 -1
  15. package/dist/mf/7493.js +1 -1
  16. package/dist/mf/8637.js +1 -1
  17. package/dist/mf/8978.js +4 -4
  18. package/dist/mf/9005.js +1 -0
  19. package/dist/mf/9110.js +1 -1
  20. package/dist/mf/9430.js +2 -2
  21. package/dist/mf/9666.js +1 -1
  22. package/dist/mf/@mf-types/compiled-types/api/fec-imports/fecImportMutations.d.ts +4 -0
  23. package/dist/mf/@mf-types/compiled-types/api/fec-imports/fecImportsQuery.d.ts +5 -0
  24. package/dist/mf/@mf-types/compiled-types/api/fec-imports/types.d.ts +46 -0
  25. package/dist/mf/@mf-types/compiled-types/api/useApiSynchro.d.ts +1 -0
  26. package/dist/mf/@mf-types/compiled-types/components/synchro/FecImportsPanel.d.ts +1 -0
  27. package/dist/mf/@mf-types/compiled-types/utils/connectorLogoUrl.d.ts +6 -0
  28. package/dist/mf/@mf-types.zip +0 -0
  29. package/dist/mf/__federation_expose_connectors.js +1 -1
  30. package/dist/mf/__federation_expose_single_connector.js +1 -1
  31. package/dist/mf/__federation_expose_synchronisation.js +1 -1
  32. package/dist/mf/index.js +3 -3
  33. package/dist/mf/integrations_app.js +3 -3
  34. package/dist/mf/mf-manifest.json +4 -2
  35. package/dist/mf/mf-stats.json +6 -4
  36. package/dist/mf/static/image/fec.png +0 -0
  37. package/package.json +1 -1
@@ -7,4 +7,4 @@
7
7
  *
8
8
  * This source code is licensed under the MIT license found in the
9
9
  * LICENSE file in the root directory of this source tree.
10
- */var REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element"),REACT_FRAGMENT_TYPE=Symbol.for("react.fragment");function jsxProd(type,config,maybeKey){var key=null;void 0!==maybeKey&&(key=""+maybeKey);void 0!==config.key&&(key=""+config.key);if("key"in config){maybeKey={};for(var propName in config)"key"!==propName&&(maybeKey[propName]=config[propName])}else maybeKey=config;config=maybeKey.ref;return{$$typeof:REACT_ELEMENT_TYPE,type:type,key:key,ref:void 0!==config?config:null,props:maybeKey}}exports.Fragment=REACT_FRAGMENT_TYPE;exports.jsx=jsxProd;exports.jsxs=jsxProd},4848:function(module,__unused_webpack_exports,__webpack_require__){module.exports=__webpack_require__(9698)},5408:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,{default:()=>Synchronisation});var jsx_runtime=__webpack_require__(4848);var index_js_=__webpack_require__(8556);var index_mjs_=__webpack_require__(2773);var esm_index_mjs_=__webpack_require__(2667);var InlineLoader=__webpack_require__(800);var modern_index_js_=__webpack_require__(7714);const AppConfigSynchroCtx=/*#__PURE__*/(0,index_js_.createContext)(null);const AppConfigSynchroProvider=AppConfigSynchroCtx.Provider;function useAppConfigSynchro(){const config=(0,index_js_.useContext)(AppConfigSynchroCtx);if(!config)throw new Error("Called `useAppConfigSynchro` outside a `<AppConfigSynchroProvider />`");return config}function useApiSynchro(){const config=useAppConfigSynchro();const baseUrl=config.api.replace(/\/$/,"");const headers={"Content-Type":"application/json",Authorization:config.token?`Bearer ${config.token}`:"",From:config.owner};const handleResponse=async res=>{if(!res.ok)throw new Error(`${res.status} ${res.statusText}`);return res.json()};return{get:path=>fetch(`${baseUrl}${path}`,{headers,cache:"no-store"}).then(handleResponse),post:(path,body)=>fetch(`${baseUrl}${path}`,{method:"POST",headers,cache:"no-store",body:void 0!==body?JSON.stringify(body):void 0}).then(handleResponse),put:(path,body)=>fetch(`${baseUrl}${path}`,{method:"PUT",headers,cache:"no-store",body:void 0!==body?JSON.stringify(body):void 0}).then(handleResponse),delete:path=>fetch(`${baseUrl}${path}`,{method:"DELETE",headers,cache:"no-store"}).then(handleResponse)}}function useSynchroListQuery(){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","list",config.company],queryFn:()=>api.get(`/synchro?cid=${config.company}`),staleTime:6e4,refetchOnWindowFocus:true,refetchOnReconnect:true})}function useSynchroDetailQuery(id){const api=useApiSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","detail",id],queryFn:()=>api.get(`/synchro/${id}`),enabled:null!==id,staleTime:3e4,refetchOnWindowFocus:true,refetchOnReconnect:true,refetchInterval:query=>{const tasks=query.state.data?.tasks??[];const hasRunning=tasks.some(t=>!t.finished);return hasRunning?5e3:false}})}var notifications_esm_index_mjs_=__webpack_require__(4931);function useSynchroRunMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:id=>api.post(`/synchro/${id}/run`),onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({color:"blue",variant:"filled",title:"Recette lanc\xe9e",message:"La synchronisation a d\xe9marr\xe9.",styles:{title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}}});return Promise.all([queryClient.invalidateQueries({queryKey:["synchro","detail"]}),queryClient.invalidateQueries({queryKey:["synchro","list",config.company]}),queryClient.invalidateQueries({queryKey:["synchro","my-runs",config.company]})])},onError:()=>{notifications_esm_index_mjs_.notifications.show({color:"red",variant:"filled",title:"Erreur",message:"Impossible de lancer la recette.",styles:{title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}}})}})}function useSynchroToggleMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();const detailKey=id=>["synchro","detail",id];const listKey=["synchro","list",config.company];return(0,modern_index_js_.useMutation)({mutationFn:({id,active})=>api.put(`/synchro/${id}`,{active}),onMutate:async({id,active})=>{await queryClient.cancelQueries({queryKey:detailKey(id)});await queryClient.cancelQueries({queryKey:listKey});const previousDetail=queryClient.getQueryData(detailKey(id));const previousList=queryClient.getQueryData(listKey);if(previousDetail)queryClient.setQueryData(detailKey(id),{...previousDetail,active});if(previousList)queryClient.setQueryData(listKey,previousList.map(r=>r.id===id?{...r,active}:r));return{previousDetail,previousList}},onError:(_err,{id},context)=>{if(context?.previousDetail)queryClient.setQueryData(detailKey(id),context.previousDetail);if(context?.previousList)queryClient.setQueryData(listKey,context.previousList);notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible de modifier la recette."})},onSettled:(_data,_err,{id})=>{queryClient.invalidateQueries({queryKey:detailKey(id)});queryClient.invalidateQueries({queryKey:listKey})}})}var tabler_icons_react_mjs_=__webpack_require__(5200);function useSynchroSubscriptionsQuery(){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","subscriptions",config.company],queryFn:()=>api.get(`/synchro/notifications/subscriptions?cid=${config.company}`),staleTime:3e5,refetchOnWindowFocus:false})}function statusColor(customer){if(!customer.active)return"gray";const task=customer.lastTask;if(!task)return"gray";if(!task.finished)return"yellow";return task.error?"red":"green"}function connectorLogoUrl(c){return c.logo_key?`https://img.logo.dev/${c.logo_key}?token=pk_QvyqAb6uTRGJE2_sDsEb9g&retina=true`:`https://s3.eu-west-3.amazonaws.com/media.airporting/connectors/${c.codename}.png`}function ConnectorLogo({connector,size=44}){if(!connector)return null;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:connector.name,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:connectorLogoUrl(connector),size:size,radius:"md",p:0,style:{flexShrink:0}})})}function isOverviewRecipe(r){return"Total"===r.recipe.name||"[Total]"===r.recipe.name}function buildSections(recipes){let overview=null;const byType=new Map;for(const r of recipes){if(isOverviewRecipe(r)){overview=r;continue}const t=r.recipe.connector_from?.type;const key=t?.codename??"other";if(!byType.has(key))byType.set(key,{type:t??{codename:"other",name:"Autres"},recipes:[]});byType.get(key).recipes.push(r)}const sections=Array.from(byType.values()).sort((a,b)=>a.type.name.localeCompare(b.type.name));return{overview,sections}}function RecipeRow({customer,selectedId,onSelect,subscribed,mobile=false}){const color=statusColor(customer);const isSelected=customer.id===selectedId;const from=customer.recipe.connector_from;const to=customer.recipe.connector_to;const isOverview=isOverviewRecipe(customer);const isInactive=!customer.active&&!isOverview;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.UnstyledButton,{onClick:()=>onSelect(customer.id),style:{position:"relative",borderLeft:`3px solid var(--mantine-color-${color}-6)`,background:isSelected?"var(--mantine-color-dark-6)":"transparent",borderRadius:4,display:"block",boxSizing:"border-box",width:"100%",padding:mobile?"10px 6px":"6px 10px",opacity:isInactive?.45:1,filter:isInactive?"grayscale(0.7)":void 0,overflow:"hidden"},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:mobile?18:8,wrap:"nowrap",justify:"center",children:isOverview?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Vue d'ensemble",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:mobile?12:6,wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconHome,{size:mobile?28:20}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:mobile?"md":"sm",fw:mobile?600:void 0,children:"Vue d'ensemble"})]})}):from||to?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:mobile?22:12,wrap:"nowrap",justify:"center",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ConnectorLogo,{connector:from,size:mobile?72:44}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:mobile?"xl":"lg",c:"dimmed",children:"→"}),/*#__PURE__*/(0,jsx_runtime.jsx)(ConnectorLogo,{connector:to,size:mobile?72:44})]}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:mobile?"md":"sm",truncate:true,children:customer.recipe.name})}),subscribed&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Notifications activ\xe9es",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconBell,{size:14,color:"var(--mantine-color-blue-5)",style:{position:"absolute",top:4,right:4}})})]})}function SynchroList({recipes,selectedId,onSelect,mobile=false}){const{overview,sections}=buildSections(recipes);const subsRes=useSynchroSubscriptionsQuery();const subscribed=new Set(subsRes.data?.subscriptions??[]);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ScrollArea,{h:"100%",scrollbars:"y",type:"hover",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:mobile?10:8,p:mobile?4:8,style:{boxSizing:"border-box",width:"100%"},children:[overview&&/*#__PURE__*/(0,jsx_runtime.jsx)(RecipeRow,{customer:overview,selectedId:selectedId,onSelect:onSelect,subscribed:subscribed.has(overview.id),mobile:mobile}),sections.map(section=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:mobile?8:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:6,c:"dimmed",pl:mobile?8:10,pt:6,children:section.type.name}),section.recipes.map(r=>/*#__PURE__*/(0,jsx_runtime.jsx)(RecipeRow,{customer:r,selectedId:selectedId,onSelect:onSelect,subscribed:subscribed.has(r.id),mobile:mobile},r.id))]},section.type.codename))]})})}const KEY=userId=>`synchro-tiles-cols:${userId}`;function useTilesColumns(userId){const[cols,setColsState]=(0,index_js_.useState)(()=>{const raw=localStorage.getItem(KEY(userId));return"1"===raw?1:2});(0,index_js_.useEffect)(()=>{localStorage.setItem(KEY(userId),String(cols))},[userId,cols]);const setCols=(0,index_js_.useCallback)(c=>setColsState(c),[]);const visibleLimit=1===cols?8:16;return{cols,setCols,visibleLimit}}var modals_esm_index_mjs_=__webpack_require__(4403);function useSynchroJobRunMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({id,jobId})=>api.post(`/synchro/${id}/jobs/${jobId}/run`),onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({color:"blue",variant:"filled",title:"T\xe2che lanc\xe9e",message:"La t\xe2che a d\xe9marr\xe9.",styles:{title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}}});return Promise.all([queryClient.invalidateQueries({queryKey:["synchro","detail"]}),queryClient.invalidateQueries({queryKey:["synchro","list",config.company]}),queryClient.invalidateQueries({queryKey:["synchro","my-runs",config.company]})])},onError:()=>{notifications_esm_index_mjs_.notifications.show({color:"red",variant:"filled",title:"Erreur",message:"Impossible de lancer la t\xe2che.",styles:{title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}}})}})}function useSynchroJobToggleMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();const detailKey=id=>["synchro","detail",id];const listKey=["synchro","list",config.company];return(0,modern_index_js_.useMutation)({mutationFn:({id,jobId,active})=>api.put(`/synchro/${id}/jobs/${jobId}/active`,{active}),onMutate:async({id,jobId,active})=>{await queryClient.cancelQueries({queryKey:detailKey(id)});const previousDetail=queryClient.getQueryData(detailKey(id));if(previousDetail)queryClient.setQueryData(detailKey(id),{...previousDetail,jobs:previousDetail.jobs.map(job=>job.id===jobId?{...job,active}:job)});return{previousDetail}},onError:(_err,{id},context)=>{if(context?.previousDetail)queryClient.setQueryData(detailKey(id),context.previousDetail);notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible de modifier la t\xe2che."})},onSettled:(_data,_err,{id})=>{queryClient.invalidateQueries({queryKey:detailKey(id)});queryClient.invalidateQueries({queryKey:listKey})}})}function useSynchroJobDeleteMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();const detailKey=id=>["synchro","detail",id];const listKey=["synchro","list",config.company];return(0,modern_index_js_.useMutation)({mutationFn:({id,jobId})=>api.delete(`/synchro/${id}/jobs/${jobId}`),onMutate:async({id,jobId})=>{await queryClient.cancelQueries({queryKey:detailKey(id)});const previousDetail=queryClient.getQueryData(detailKey(id));if(previousDetail)queryClient.setQueryData(detailKey(id),{...previousDetail,jobs:previousDetail.jobs.filter(job=>job.id!==jobId)});return{previousDetail}},onError:(_err,{id},context)=>{if(context?.previousDetail)queryClient.setQueryData(detailKey(id),context.previousDetail);notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible de supprimer la t\xe2che."})},onSettled:(_data,_err,{id})=>{queryClient.invalidateQueries({queryKey:detailKey(id)});queryClient.invalidateQueries({queryKey:listKey})}})}function useSynchroJobDefaultsQuery(id){const api=useApiSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","job-defaults",id],queryFn:()=>api.get(`/synchro/${id}/jobs/defaults`),enabled:null!==id,staleTime:3e5})}function useSynchroJobAddMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({id,defaultId})=>api.post(`/synchro/${id}/jobs`,{defaultId}),onSuccess:(_,{id})=>{queryClient.invalidateQueries({queryKey:["synchro","detail",id]});queryClient.invalidateQueries({queryKey:["synchro","list",config.company]})},onError:()=>{notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible d'ajouter la t\xe2che."})}})}function jobStatusColor(job){const task=job.lastTask;if(!task)return"gray";if(!task.finished)return"yellow";return task.error?"red":"green"}function synchro_functions_connectorLogoUrl(c){return c.logo_key?`https://img.logo.dev/${c.logo_key}?token=pk_QvyqAb6uTRGJE2_sDsEb9g&retina=true`:`https://s3.eu-west-3.amazonaws.com/media.airporting/connectors/${c.codename}.png`}function JobLogos({job}){if(!job.connector_from&&!job.connector_to)return null;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:3,wrap:"nowrap",style:{flexShrink:0},children:[job.connector_from&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:job.connector_from.name,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:synchro_functions_connectorLogoUrl(job.connector_from),size:20,radius:"md",p:0})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:"→"}),job.connector_to&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:job.connector_to.name,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:synchro_functions_connectorLogoUrl(job.connector_to),size:20,radius:"md",p:0})})]})}function SynchroFunctions({detail,onConfigJob,onShowRuns,mobile=false}){const isOverview="Total"===detail.recipe.name||"[Total]"===detail.recipe.name;const config=useAppConfigSynchro();const{cols,setCols,visibleLimit}=useTilesColumns(config.owner);const runJob=useSynchroJobRunMutation();const toggleJob=useSynchroJobToggleMutation();const deleteJob=useSynchroJobDeleteMutation();const addJob=useSynchroJobAddMutation();const jobOwnerId=job=>job.recipe_customer_id??detail.id;const[expanded,setExpanded]=(0,index_js_.useState)(false);const[openedAdd,setOpenedAdd]=(0,index_js_.useState)(false);const[chosenDefaultId,setChosenDefaultId]=(0,index_js_.useState)(null);const[selectionMode,setSelectionMode]=(0,index_js_.useState)(false);const[selectedIds,setSelectedIds]=(0,index_js_.useState)(new Set);const[bulkPending,setBulkPending]=(0,index_js_.useState)(false);const exitSelectionMode=()=>{setSelectionMode(false);setSelectedIds(new Set)};const toggleSelected=jobId=>{setSelectedIds(prev=>{const next=new Set(prev);if(next.has(jobId))next.delete(jobId);else next.add(jobId);return next})};const selectedJobs=(0,index_js_.useMemo)(()=>detail.jobs.filter(j=>selectedIds.has(j.id)),[detail.jobs,selectedIds]);const allSelectableIds=(0,index_js_.useMemo)(()=>detail.jobs.map(j=>j.id),[detail.jobs]);const allSelected=allSelectableIds.length>0&&allSelectableIds.every(id=>selectedIds.has(id));const toggleSelectAll=()=>{allSelected?setSelectedIds(new Set):setSelectedIds(new Set(allSelectableIds))};const runBulk=async(fn,eligible)=>{if(0===eligible.length)return;setBulkPending(true);try{await Promise.allSettled(eligible.map(fn))}finally{setBulkPending(false);exitSelectionMode()}};const bulkSetActive=active=>{const eligible=selectedJobs.filter(j=>j.allow_disable&&j.active!==active);if(0===eligible.length)return;runBulk(job=>toggleJob.mutateAsync({id:jobOwnerId(job),jobId:job.id,active}),eligible)};const bulkDelete=()=>{const eligible=selectedJobs.filter(j=>j.allow_delete);if(0===eligible.length)return;modals_esm_index_mjs_.modals.openConfirmModal({title:`Supprimer ${eligible.length} t\xe2che${eligible.length>1?"s":""} ?`,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"Cette action est irr\xe9versible. La configuration des t\xe2ches s\xe9lectionn\xe9es sera perdue."}),labels:{confirm:"Supprimer",cancel:"Annuler"},confirmProps:{color:"red"},onConfirm:()=>void runBulk(job=>deleteJob.mutateAsync({id:jobOwnerId(job),jobId:job.id}),eligible)})};const eligibleDisableCount=selectedJobs.filter(j=>j.allow_disable&&j.active).length;const eligibleEnableCount=selectedJobs.filter(j=>j.allow_disable&&!j.active).length;const eligibleDeleteCount=selectedJobs.filter(j=>j.allow_delete).length;const defaultsQuery=useSynchroJobDefaultsQuery(openedAdd?detail.id:null);const availableDefaults=(0,index_js_.useMemo)(()=>defaultsQuery.data??[],[defaultsQuery.data]);const handleAdd=async()=>{if(!chosenDefaultId)return;const def=availableDefaults.find(d=>String(d.id)===chosenDefaultId);if(!def)return;const{id:newJobId}=await addJob.mutateAsync({id:detail.id,defaultId:def.id});setOpenedAdd(false);setChosenDefaultId(null);onConfigJob({id:newJobId,task:def.task,task_fr:def.task_fr,order:0,settings:{},active:true,allow_delete:true,allow_disable:true})};const renderJobCol=job=>{const color=jobStatusColor(job);const isSelected=selectedIds.has(job.id);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Grid.Col,{span:1===cols?12:{base:12,sm:6},children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Card,{p:"md",withBorder:true,style:{cursor:"pointer",borderColor:selectionMode&&isSelected?"var(--mantine-color-teal-5)":void 0,backgroundColor:selectionMode&&isSelected?"var(--mantine-color-teal-0)":void 0},onClick:()=>{if(selectionMode)toggleSelected(job.id);else onConfigJob(job)},children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:8,wrap:"nowrap",style:{flex:1,minWidth:0},children:[selectionMode&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Checkbox,{checked:isSelected,onChange:()=>toggleSelected(job.id),onClick:e=>e.stopPropagation(),size:"sm"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{w:8,h:8,style:{borderRadius:"50%",background:`var(--mantine-color-${color}-6)`,flexShrink:0}}),/*#__PURE__*/(0,jsx_runtime.jsx)(JobLogos,{job:job}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{truncate:true,c:selectionMode&&isSelected?"teal.9":void 0,style:{fontSize:"1rem"},children:job.task_fr}),job.gsheet_collision&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{withArrow:true,multiline:true,w:320,label:/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",fw:600,children:"Conflit de destination Gsheet"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",children:["Onglet \xab ",job.gsheet_collision.worksheet," \xbb partag\xe9 avec :"]}),job.gsheet_collision.others.map((o,i)=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",children:["• ",o.recipe_name," — ",o.job_name_fr??"(sans nom)"]},i))]}),children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:"yellow",variant:"light",size:"sm",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconAlertTriangle,{size:12}),style:{cursor:"help",flexShrink:0},children:"Collision"})})]}),!selectionMode&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:4,wrap:"nowrap",onClick:e=>e.stopPropagation(),children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",color:"green",loading:runJob.isPending,title:"Lancer",onClick:()=>runJob.mutate({id:jobOwnerId(job),jobId:job.id}),children:"▶"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",color:"gray",title:"Configurer",onClick:e=>{e.stopPropagation();onConfigJob(job)},children:"⚙"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Menu,{shadow:"md",width:180,position:"bottom-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Menu.Target,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",color:"gray",title:"Plus d'options",onClick:e=>e.stopPropagation(),children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconDotsVertical,{size:16})})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Menu.Dropdown,{onClick:e=>e.stopPropagation(),children:[!mobile&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Menu.Item,{leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconHistory,{size:14}),onClick:()=>onShowRuns(job),children:"Voir l'historique"}),!mobile&&(job.allow_disable||job.allow_delete)&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Menu.Divider,{}),job.allow_disable&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Menu.Item,{leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCpuOff,{size:14}),onClick:()=>{if(job.active)modals_esm_index_mjs_.modals.openConfirmModal({title:"D\xe9sactiver cette t\xe2che ?",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"La t\xe2che ne sera plus ex\xe9cut\xe9e tant qu'elle reste d\xe9sactiv\xe9e."}),labels:{confirm:"D\xe9sactiver",cancel:"Annuler"},onConfirm:()=>toggleJob.mutate({id:jobOwnerId(job),jobId:job.id,active:false})});else toggleJob.mutate({id:jobOwnerId(job),jobId:job.id,active:true})},children:job.active?"D\xe9sactiver":"Activer"}),job.allow_delete&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Menu.Item,{color:"red",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTrash,{size:14}),onClick:()=>{modals_esm_index_mjs_.modals.openConfirmModal({title:"Supprimer cette t\xe2che ?",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"Cette action est irr\xe9versible. La configuration de la t\xe2che sera perdue."}),labels:{confirm:"Supprimer",cancel:"Annuler"},confirmProps:{color:"red"},onConfirm:()=>deleteJob.mutate({id:jobOwnerId(job),jobId:job.id})})},children:"Supprimer"})]})]})]})]})})},job.id)};const visibleJobs=detail.jobs.slice(0,visibleLimit);const hiddenJobs=detail.jobs.slice(visibleLimit);const hasMore=hiddenJobs.length>0;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[selectionMode&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Paper,{p:"xs",withBorder:true,style:{position:"sticky",top:0,zIndex:5,backgroundColor:"var(--mantine-color-body)"},children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:"sm",wrap:"nowrap",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Checkbox,{checked:allSelected,indeterminate:!allSelected&&selectedIds.size>0,onChange:toggleSelectAll,label:0===selectedIds.size?"S\xe9lectionner tout":`${selectedIds.size} s\xe9lectionn\xe9e${selectedIds.size>1?"s":""}`})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Button,{size:"xs",variant:"default",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCpu,{size:14}),disabled:0===eligibleEnableCount||bulkPending,loading:bulkPending,onClick:()=>bulkSetActive(true),children:["Activer",eligibleEnableCount>0?` (${eligibleEnableCount})`:""]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Button,{size:"xs",variant:"default",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCpuOff,{size:14}),disabled:0===eligibleDisableCount||bulkPending,loading:bulkPending,onClick:()=>bulkSetActive(false),children:["D\xe9sactiver",eligibleDisableCount>0?` (${eligibleDisableCount})`:""]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Button,{size:"xs",color:"red",variant:"light",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTrash,{size:14}),disabled:0===eligibleDeleteCount||bulkPending,loading:bulkPending,onClick:bulkDelete,children:["Supprimer",eligibleDeleteCount>0?` (${eligibleDeleteCount})`:""]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{size:"xs",variant:"subtle",color:"gray",onClick:exitSelectionMode,disabled:bulkPending,children:"Annuler"})]})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{justify:"flex-end",mb:"sm",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SegmentedControl,{value:String(cols),onChange:v=>setCols("1"===v?1:2),data:[{label:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconLayoutGrid,{size:16}),value:"2"},{label:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconLayoutColumns,{size:16}),value:"1"}]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Grid,{gutter:"md",children:visibleJobs.map(renderJobCol)}),hasMore&&/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Collapse,{in:expanded,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Grid,{gutter:"md",children:hiddenJobs.map(renderJobCol)})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{justify:"center",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",size:"sm",color:"gray",rightSection:expanded?/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconChevronUp,{size:14}):/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconChevronDown,{size:14}),onClick:()=>setExpanded(v=>!v),children:expanded?"R\xe9duire":`Voir ${hiddenJobs.length} jobs suppl\xe9mentaires`})})]}),!isOverview&&detail.active&&!selectionMode&&/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Divider,{mb:"md"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"center",gap:"sm",wrap:"nowrap",grow:mobile,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"filled",color:"teal",size:"sm",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconPlaylistAdd,{size:14}),onClick:()=>setOpenedAdd(true),children:"Ajouter une fonction"}),detail.jobs.length>0&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"default",size:"sm",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCheckbox,{size:14}),onClick:()=>setSelectionMode(true),children:"S\xe9lectionner"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:openedAdd,onClose:()=>{setOpenedAdd(false);setChosenDefaultId(null)},title:"Ajouter une fonction",size:"xl",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[defaultsQuery.isPending?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",children:"Chargement…"}):0===availableDefaults.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",children:"Aucune fonction suppl\xe9mentaire disponible."}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{data:availableDefaults.map(d=>({value:String(d.id),label:d.task_fr})),value:chosenDefaultId,onChange:setChosenDefaultId,placeholder:"Choisir une fonction",searchable:true,nothingFoundMessage:"Aucun r\xe9sultat"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",color:"gray",onClick:()=>{setOpenedAdd(false);setChosenDefaultId(null)},children:"Annuler"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{disabled:!chosenDefaultId,loading:addJob.isPending,onClick:handleAdd,children:"Ajouter"})]})]})})]})}function formatDuration(ms){if(null===ms)return"—";if(ms<1e3)return`${ms}ms`;const secs=ms/1e3;if(secs<60)return`${secs.toFixed(1)}s`;const mins=Math.floor(secs/60);const remainSecs=Math.round(secs%60);return`${mins}mn ${remainSecs}s`}function formatDate(iso){if(!iso)return"—";return new Date(iso).toLocaleString("fr-FR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}function synchro_history_connectorLogoUrl(c){return c.logo_key?`https://img.logo.dev/${c.logo_key}?token=pk_QvyqAb6uTRGJE2_sDsEb9g&retina=true`:`https://s3.eu-west-3.amazonaws.com/media.airporting/connectors/${c.codename}.png`}function TaskLogos({task}){if(!task.connector_from&&!task.connector_to)return null;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:3,wrap:"nowrap",children:[task.connector_from&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:task.connector_from.name,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:synchro_history_connectorLogoUrl(task.connector_from),size:20,radius:"md",p:0})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:"→"}),task.connector_to&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:task.connector_to.name,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:synchro_history_connectorLogoUrl(task.connector_to),size:20,radius:"md",p:0})})]})}function ErrorBadge({task}){const meta=task.error_meta;const errorMessage=task.error;const grafanaUrl=task.grafana_url;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard,{width:460,shadow:"md",openDelay:150,closeDelay:150,withArrow:true,position:"bottom-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Target,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:"red",style:{cursor:"help"},children:"Erreur"})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Dropdown,{children:meta?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",fw:500,children:meta.userMessage}),meta.hint?.url?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Button,{component:"a",href:meta.hint.url,target:"_blank",rel:"noopener noreferrer",variant:"light",size:"xs",children:[meta.hint.label," →"]}):meta.hint?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:meta.hint.label}):null,grafanaUrl&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Anchor,{href:grafanaUrl,target:"_blank",rel:"noopener noreferrer",size:"xs",c:"dimmed",children:"Voir les logs Grafana →"})]}):errorMessage?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:"D\xe9tails techniques"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Code,{block:true,style:{fontSize:11,maxHeight:200,overflow:"auto"},children:errorMessage}),grafanaUrl&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Anchor,{href:grafanaUrl,target:"_blank",rel:"noopener noreferrer",size:"xs",c:"dimmed",children:"Voir les logs Grafana →"})]}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:"Pas de d\xe9tails disponibles."})})]})}function SynchroHistory({tasks,destinationCodename}){const showRecipeCol=tasks.some(t=>t.connector_from||t.connector_to);const showSpreadsheetCol=void 0===destinationCodename?tasks.some(t=>t.spreadsheet):"google_sheet"===destinationCodename||"excel"===destinationCodename;if(0===tasks.length)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",children:"Aucun historique disponible."});return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{striped:true,highlightOnHover:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Thead,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[showRecipeCol&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Recette"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"T\xe2che"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"D\xe9marr\xe9e"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{pl:"xs",children:"Type"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Statut"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Dur\xe9e"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"#ops"}),showSpreadsheetCol&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Tableur"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Logs"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:tasks.map(task=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[showRecipeCol&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(TaskLogos,{task:task})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:task.job_name_fr}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:formatDate(task.startedAt)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ThemeIcon,{variant:"transparent",color:"gray",children:"manual"===task.trigger_source?/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconUser,{size:18,stroke:1.5}):/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconRobot,{size:18,stroke:1.5})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"manual"===task.trigger_source?task.owner:"Planifi\xe9"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:task.finished?task.error||task.error_meta?/*#__PURE__*/(0,jsx_runtime.jsx)(ErrorBadge,{task:task}):task.sheet_sync&&!task.sheet_sync.done?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Badge,{color:"blue",children:["\xc9criture Sheet… (",task.sheet_sync.step??"init",")"]}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:"green",children:"OK"}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:"yellow",children:"En cours"})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:formatDuration(task.runDuration)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:task.trace_count}),showSpreadsheetCol&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:task.spreadsheet_url?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:task.worksheet??"Ouvrir le tableur",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{component:"a",href:task.spreadsheet_url,target:"_blank",variant:"subtle",size:"sm",color:"gray",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconFileSpreadsheet,{size:18})})}):"—"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:task.grafana_url?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Voir les logs",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{component:"a",href:task.grafana_url,target:"_blank",rel:"noopener noreferrer",variant:"subtle","aria-label":"Voir les logs",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTerminal,{size:16})})}):"—"})]},task.id))})]})}function useSynchroJobConfigQuery(recipeId,jobId){const api=useApiSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","job-config",recipeId,jobId],queryFn:()=>api.get(`/synchro/${recipeId}/jobs/${jobId}/config`),enabled:null!==recipeId&&null!==jobId})}function useSynchroJobSaveMutation(){const api=useApiSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({id,jobId,data})=>api.put(`/synchro/${id}/jobs/${jobId}`,data),onSuccess:(_,{id,jobId})=>{queryClient.invalidateQueries({queryKey:["synchro","detail",id]});queryClient.invalidateQueries({queryKey:["synchro","job-config",id,jobId]});notifications_esm_index_mjs_.notifications.show({title:"Configuration sauvegard\xe9e",message:"Les param\xe8tres sont enregistr\xe9s."})},onError:()=>{notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible de sauvegarder la configuration."})}})}function useSynchroJobRenameMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({id,jobId,name})=>api.put(`/synchro/${id}/jobs/${jobId}/rename`,{name}),onSuccess:(_,{id})=>{queryClient.invalidateQueries({queryKey:["synchro","detail",id]});queryClient.invalidateQueries({queryKey:["synchro","list",config.company]});notifications_esm_index_mjs_.notifications.show({color:"green",title:"T\xe2che renomm\xe9e",message:"Le nouveau nom a bien \xe9t\xe9 enregistr\xe9."})},onError:()=>{notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible de renommer la t\xe2che."})}})}var dist_index_js_=__webpack_require__(4259);var form_esm_index_mjs_=__webpack_require__(4491);var dates_esm_index_mjs_=__webpack_require__(5899);const START_PRESETS=[{value:"today",label:"Jour courant"},{value:"month_start",label:"D\xe9but du mois"},{value:"prev_month_start",label:"D\xe9but du mois pr\xe9c\xe9dent"},{value:"year_start",label:"D\xe9but de l'ann\xe9e"}];const END_PRESETS=[{value:"today",label:"Jour courant"},{value:"month_end",label:"Fin du mois"},{value:"prev_month_end",label:"Fin du mois pr\xe9c\xe9dent"},{value:"year_end",label:"Fin de l'ann\xe9e"}];const READ_MODE_BY_SENTINEL={TODAY:"today",START_CURRENT_MONTH:"month_start",START_LAST_MONTH:"prev_month_start",START_CURRENT_YEAR:"year_start",END_CURRENT_MONTH:"month_end",END_LAST_MONTH:"prev_month_end",END_CURRENT_YEAR:"year_end"};const WRITE_SENTINEL_BY_MODE={today:"TODAY",month_start:"START_CURRENT_MONTH",prev_month_start:"START_LAST_MONTH",year_start:"START_CURRENT_YEAR",month_end:"END_CURRENT_MONTH",prev_month_end:"END_LAST_MONTH",year_end:"END_CURRENT_YEAR"};function parseValue(val){const base={exactDate:null,direction:"MINUS",amount:1,unit:"DAYS",raw:val??""};if(!val)return{...base,mode:"today"};if(READ_MODE_BY_SENTINEL[val])return{...base,mode:READ_MODE_BY_SENTINEL[val]};const legacyRel=val.match(/^(MAJOR|MINUS)_(\d+)_([A-Z]+)$/);if(legacyRel)return{...base,mode:"relative",direction:legacyRel[1],amount:Number(legacyRel[2]),unit:legacyRel[3]};const d=new Date(val);if(!isNaN(d.getTime()))return{...base,mode:"exact",exactDate:d};return{...base,mode:"passthrough"}}function serializeValue(parsed){const{mode,exactDate,direction,amount,unit,raw}=parsed;if("passthrough"===mode)return raw;if("exact"===mode){if(!exactDate)return"";const y=exactDate.getFullYear();const m=String(exactDate.getMonth()+1).padStart(2,"0");const d=String(exactDate.getDate()).padStart(2,"0");return`${y}-${m}-${d}`}if("relative"===mode)return`${direction}_${amount}_${unit}`;return WRITE_SENTINEL_BY_MODE[mode]??"TODAY"}function InputDateBoundary({label,help,required,disabled,value,onChange,variant}){const parsed=parseValue(value);const[mode,setMode]=(0,index_js_.useState)(parsed.mode);const[exactDate,setExactDate]=(0,index_js_.useState)(parsed.exactDate);const[direction,setDirection]=(0,index_js_.useState)(parsed.direction);const[amount,setAmount]=(0,index_js_.useState)(parsed.amount);const[unit,setUnit]=(0,index_js_.useState)(parsed.unit);const rawRef=(0,index_js_.useRef)(parsed.raw);const didMount=(0,index_js_.useRef)(false);(0,index_js_.useEffect)(()=>{if(!didMount.current){didMount.current=true;return}onChange(serializeValue({mode,exactDate,direction,amount,unit,raw:rawRef.current}))},[mode,exactDate,direction,amount,unit]);const presets="start"===variant?START_PRESETS:END_PRESETS;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[label&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",fw:500,children:[label," ",required&&/*#__PURE__*/(0,jsx_runtime.jsx)("span",{style:{color:"var(--mantine-color-red-6)"},children:"*"})]}),help&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:help}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Radio.Group,{value:mode,onChange:v=>setMode(v),children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"md",wrap:"wrap",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Radio,{value:"exact",label:"Date exacte",disabled:disabled,style:{flex:"1 1 150px",minWidth:0}}),/*#__PURE__*/(0,jsx_runtime.jsx)(dates_esm_index_mjs_.DateInput,{leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCalendar,{size:16}),value:exactDate,onChange:d=>{setExactDate(d?new Date(d):null);setMode("exact")},disabled:disabled||"exact"!==mode,valueFormat:"DD-MM-YYYY",placeholder:"JJ-MM-AAAA",style:{flex:"1 1 180px",minWidth:0}})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"md",wrap:"wrap",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Radio,{value:"relative",label:"Date relative",disabled:disabled,style:{flex:"1 1 150px",minWidth:0}}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{data:[{value:"MINUS",label:"pass\xe9e"},{value:"MAJOR",label:"future"}],value:direction,onChange:v=>{setDirection(v??"MINUS");setMode("relative")},disabled:disabled||"relative"!==mode,style:{flex:"1 1 100px",minWidth:92},allowDeselect:false}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{value:amount,onChange:v=>{setAmount(Number(v));setMode("relative")},min:0,disabled:disabled||"relative"!==mode,style:{flex:"1 1 80px",minWidth:76}}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{data:[{value:"DAYS",label:"Jour(s)"},{value:"WEEKS",label:"Semaine(s)"},{value:"MONTHS",label:"Mois"},{value:"YEARS",label:"Ann\xe9e(s)"}],value:unit,onChange:v=>{setUnit(v??"DAYS");setMode("relative")},disabled:disabled||"relative"!==mode,style:{flex:"1 1 120px",minWidth:110},allowDeselect:false})]}),presets.map(p=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Radio,{value:p.value,label:p.label,disabled:disabled},p.value))]})})]})}function useSpreadsheetsQuery(){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","spreadsheets",config.company],queryFn:()=>api.get(`/synchro/spreadsheets?cid=${config.company}`)})}function normalizeValue(raw){if(null==raw)return null;if("string"==typeof raw)return raw;if(Array.isArray(raw)){const first=raw[0];if(null==first)return null;if("string"==typeof first)return first;if("object"==typeof first){const v=first.spreadsheet_id;return"string"==typeof v?v:null}return null}if("object"==typeof raw){const v=raw.spreadsheet_id;return"string"==typeof v?v:null}return null}function InputGsheetsSelector({label,help,required,disabled,value,onChange,error}){const{data:spreadsheets,isPending}=useSpreadsheetsQuery();const options=(0,index_js_.useMemo)(()=>(spreadsheets??[]).map(s=>({value:s.id,label:s.name})),[spreadsheets]);const normalized=(0,index_js_.useMemo)(()=>normalizeValue(value),[value]);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:label??"Tableur",description:help??void 0,required:required,disabled:disabled||isPending,placeholder:isPending?"Chargement...":"S\xe9lectionner un tableur",data:options,value:normalized,onChange:onChange,error:error,searchable:true,clearable:true,allowDeselect:false})}function useSynchroExcelFilesQuery(){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","excel-files",config.company],queryFn:()=>api.get(`/synchro/excel-files?cid=${config.company}`)})}function InputExcelSelector_normalizeValue(raw){if(null==raw)return null;if("string"==typeof raw)return raw;if(Array.isArray(raw)){const first=raw[0];if(null==first)return null;if("string"==typeof first)return first;if("object"==typeof first){const v=first.spreadsheet_id;return"string"==typeof v?v:null}return null}if("object"==typeof raw){const v=raw.spreadsheet_id;return"string"==typeof v?v:null}return null}function InputExcelSelector({label,help,required,disabled,value,onChange,error}){const{data:files,isPending}=useSynchroExcelFilesQuery();const options=(0,index_js_.useMemo)(()=>(files??[]).map(f=>({value:f.id,label:f.name})),[files]);const normalized=(0,index_js_.useMemo)(()=>InputExcelSelector_normalizeValue(value),[value]);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:label??"Fichier Excel",description:help??void 0,required:required,disabled:disabled||isPending,placeholder:isPending?"Chargement...":"S\xe9lectionner un fichier Excel",data:options,value:normalized,onChange:onChange,error:error,searchable:true,clearable:true,allowDeselect:false})}function dedupeSelectData(options){const seen=new Set;const out=[];for(const option of options)if(option.value){if(!seen.has(option.value)){seen.add(option.value);out.push(option)}}return out}function buildOptions(source,cfg){const mapped=source.map(row=>{const value=String(row?.[cfg.valueField]??"");const label=String(row?.[cfg.labelField??cfg.valueField]??value);const secondary=(cfg.secondaryFields??[]).map(f=>row?.[f]).filter(v=>null!=v&&""!==v).join(" \xb7 ");return{value,label,secondary}});return dedupeSelectData(mapped)}function InputAccountSelector({accountCfg,sourceValues,label,description,required,disabled,multiple,value,onChange,error}){const hasSource=Array.isArray(sourceValues)&&sourceValues.length>0;const options=(0,index_js_.useMemo)(()=>hasSource?buildOptions(sourceValues,accountCfg):[],[hasSource,sourceValues,accountCfg]);const extractValue=(0,index_js_.useCallback)(raw=>{if(null==raw)return"";if("string"==typeof raw)return raw;if(Array.isArray(raw)){const first=raw[0];if(null==first)return"";if("string"==typeof first)return first;return String(first?.[accountCfg.valueField]??"")}if("object"==typeof raw)return String(raw?.[accountCfg.valueField]??"");return String(raw)},[accountCfg.valueField]);const wrapValue=(0,index_js_.useCallback)(v=>{if(!hasSource)return[];const row=sourceValues.find(r=>String(r?.[accountCfg.valueField]??"")===v);return row?[row]:[]},[hasSource,sourceValues,accountCfg.valueField]);const renderOption=(0,index_js_.useCallback)(({option,checked})=>{const match=options.find(d=>d.value===option.value);return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"sm",wrap:"nowrap",w:"100%",children:[checked&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.CheckIcon,{size:12}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:match?.label??option.value}),match?.secondary&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",opacity:.5,children:match.secondary})]})]})},[options]);const multiValue=(0,index_js_.useMemo)(()=>{if(!multiple)return[];const arr=Array.isArray(value)?value:value?[value]:[];return arr.map(v=>extractValue([v])).filter(Boolean)},[multiple,value,extractValue]);const singleValue=(0,index_js_.useMemo)(()=>{if(multiple)return null;return extractValue(value)||null},[multiple,value,extractValue]);const handleMultiChange=(0,index_js_.useCallback)(values=>{onChange(values.flatMap(v=>wrapValue(v)))},[onChange,wrapValue]);const handleSingleChange=(0,index_js_.useCallback)(v=>{onChange(v?wrapValue(v):[])},[onChange,wrapValue]);const allSelected=options.length>0&&multiValue.length===options.length;const toggleAll=(0,index_js_.useCallback)(()=>{allSelected?handleMultiChange([]):handleMultiChange(options.map(o=>o.value))},[allSelected,options,handleMultiChange]);const multiLabel=(0,index_js_.useMemo)(()=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",gap:"xs",w:"100%",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{component:"span",size:"sm",fw:500,children:[label,required&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{component:"span",c:"red",inherit:true,children:[" ","*"]})]}),options.length>0&&!disabled&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Anchor,{component:"button",type:"button",size:"xs",onClick:toggleAll,children:allSelected?"Tout d\xe9s\xe9lectionner":"Tout s\xe9lectionner"})]}),[label,required,options.length,disabled,allSelected,toggleAll]);const fallbackValue=(0,index_js_.useMemo)(()=>{if(hasSource)return"";if(null==value)return"";if("string"==typeof value)return value;if(Array.isArray(value)){const first=value[0];if(null==first)return"";if("string"==typeof first)return first;return String(first?.[accountCfg.valueField]??"")}if("object"==typeof value)return String(value?.[accountCfg.valueField]??"");return String(value)},[hasSource,value,accountCfg.valueField]);const handleFallbackChange=(0,index_js_.useCallback)(e=>onChange(e.currentTarget.value),[onChange]);if(!hasSource)return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Alert,{variant:"light",color:"gray",children:"Source non charg\xe9e — saisie manuelle de l'identifiant."}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:label,description:description,required:required,disabled:disabled,value:fallbackValue,onChange:handleFallbackChange,error:error})]});if(multiple)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.MultiSelect,{label:multiLabel,description:description,required:required,withAsterisk:false,disabled:disabled,data:options,value:multiValue,onChange:handleMultiChange,renderOption:renderOption,error:error,searchable:true});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:label,description:description,required:required,disabled:disabled,data:options,value:singleValue,onChange:handleSingleChange,renderOption:renderOption,error:error,searchable:true,allowDeselect:false})}function buildEmittedArray(rows,value,editedCode,editedCategory){return rows.map(row=>{if(row.code===editedCode)return{code:row.code,label:row.label,category:editedCategory};const existing=value?.find(v=>v.code===row.code);return{code:row.code,label:row.label,category:existing?.category??row.suggested_category??""}})}function mergeRows(rows,value){const rowCodes=new Set(rows.map(r=>r.code));const extra=(value??[]).filter(v=>!rowCodes.has(v.code)).map(v=>({code:v.code,label:v.label,suggested_category:v.category}));return[...rows,...extra]}function InputCfsCategoryMapping({label,help,required,disabled,value,onChange,error,sourceValues}){const rows=(0,index_js_.useMemo)(()=>sourceValues??[],[sourceValues]);const displayRows=(0,index_js_.useMemo)(()=>mergeRows(rows,value),[rows,value]);(0,index_js_.useEffect)(()=>{if(rows.length>0&&(!value||0===value.length)){const defaults=rows.map(row=>({code:row.code,label:row.label,category:row.suggested_category??""}));onChange(defaults)}},[]);const allCategories=(0,index_js_.useMemo)(()=>Array.from(new Set([...displayRows.map(r=>r.suggested_category??"").filter(Boolean),...(value??[]).map(v=>v.category).filter(Boolean)])).sort(),[displayRows,value]);const handleCategoryChange=(0,index_js_.useCallback)((code,newCategory)=>{onChange(buildEmittedArray(displayRows,value,code,newCategory))},[displayRows,value,onChange]);if(0===displayRows.length)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:0,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Input.Wrapper,{label:label??void 0,description:help??void 0,required:required,error:error,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",mt:"xs",children:"Aucun code — saisie indisponible."})})});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:0,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Input.Wrapper,{label:label??void 0,description:help??void 0,required:required,error:error,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{mt:"xs",withTableBorder:true,withColumnBorders: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:"Code"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Compte"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Cat\xe9gorie"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:displayRows.map(row=>{const entry=value?.find(v=>v.code===row.code);const currentCategory=entry?.category??row.suggested_category??"";return/*#__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)(index_mjs_.Text,{size:"sm",children:row.code})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:row.label})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Autocomplete,{value:currentCategory,data:allCategories,onChange:newCategory=>handleCategoryChange(row.code,newCategory),disabled:disabled,size:"xs"})})]},row.code)})})]})})})}const EMPTY_ARRAY=[];const ACCOUNT_ID_NAME_SHAPE={valueField:"account_id",labelField:"account_name",secondaryFields:["account_id"]};const ACCOUNT_SELECTOR_REGISTRY={airporting_account_selector:{valueField:"account_match",labelField:"account_name",secondaryFields:["bank_name","iban"]},alma_account_selector:ACCOUNT_ID_NAME_SHAPE,bridge_account_selector:ACCOUNT_ID_NAME_SHAPE,chargebee_account_selector:ACCOUNT_ID_NAME_SHAPE,ibanfirst_account_selector:ACCOUNT_ID_NAME_SHAPE,paypal_account_selector:ACCOUNT_ID_NAME_SHAPE,pennylane_account_selector:ACCOUNT_ID_NAME_SHAPE,profitwell_account_selector:ACCOUNT_ID_NAME_SHAPE,qonto_account_selector:ACCOUNT_ID_NAME_SHAPE,revolut_account_selector:ACCOUNT_ID_NAME_SHAPE,shopify_account_selector:ACCOUNT_ID_NAME_SHAPE,sobank_account_selector:{valueField:"Account_Name",secondaryFields:["Iban"]},konfipay_account_selector:{valueField:"Account_Name",secondaryFields:["Iban"]},stripe_account_selector:ACCOUNT_ID_NAME_SHAPE,sycomore_account_selector:ACCOUNT_ID_NAME_SHAPE,wise_account_selector:ACCOUNT_ID_NAME_SHAPE,zohobooks_account_selector:{valueField:"account_id",labelField:"account_name",secondaryFields:["currency"]},zohobooks_reporting_tag_option_selector:{valueField:"value",labelField:"label",secondaryFields:[]}};function FormField({config,value,onChange,error,connectorCodename,collisionWarning}){const label=config.label??config.name??"";const description=config.help??void 0;const required=config.required??false;const disabled=config.disabled??false;const appConfig=useAppConfigSynchro();const csvSplitValue=(0,index_js_.useMemo)(()=>{if(Array.isArray(value))return value;if("string"==typeof value&&value.length>0)return value.split(",").filter(Boolean);return[]},[value]);const wrapSingleValue=(0,index_js_.useMemo)(()=>{if(Array.isArray(value))return value;if(null!=value&&""!==value)return[String(value)];return[]},[value]);const arrayValue=(0,index_js_.useMemo)(()=>Array.isArray(value)?value:EMPTY_ARRAY,[value]);const selectOptions=(0,index_js_.useMemo)(()=>{if(!config.full||"object"!=typeof config.full)return[];const f=config.full;const source=Array.isArray(f.options)?f.options:Array.isArray(f.values)?f.values:null;if(!source)return[];const mapped=source.map(o=>"string"==typeof o?{value:o,label:o}:{value:String(o.value??o.id??o),label:String(o.label??o.name??o)});return dedupeSelectData(mapped)},[config.full]);const selectMultipleValue=(0,index_js_.useMemo)(()=>{if(csvSplitValue.length>0)return csvSplitValue;const def=config.full?.default;return Array.isArray(def)?def:EMPTY_ARRAY},[csvSplitValue,config.full]);switch(config.type){case"text":if(config.multiple)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TagsInput,{label:label,description:description,required:required,disabled:disabled,value:wrapSingleValue,onChange:onChange,error:error});return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:label,description:description,required:required,disabled:disabled,value:value??"",onChange:e=>onChange(e.currentTarget.value),error:error}),collisionWarning&&collisionWarning.length>0&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Alert,{variant:"light",color:"yellow",icon:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconAlertTriangle,{size:14}),p:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",fw:600,children:"Attention, cet onglet est d\xe9j\xe0 pris :"}),collisionWarning.map(c=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",children:["• ",c.recipe_name," — ",c.job_name_fr??"(sans nom)"]},c.job_id))]})]});case"email":if(config.multiple)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TagsInput,{label:label,description:description,required:required,disabled:disabled,value:wrapSingleValue,onChange:onChange,error:error,placeholder:"Entr\xe9e / virgule pour valider",splitChars:[",",";"," "]});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{type:"email",label:label,description:description,required:required,disabled:disabled,value:value??"",onChange:e=>onChange(e.currentTarget.value),error:error});case"password":{const hasExistingValue=null!=connectorCodename&&null!=config.name&&null!=value&&""!==value;const baseUrl=appConfig.api.replace(/\/$/,"");const authHeaders={Authorization:appConfig.token?`Bearer ${appConfig.token}`:"",From:appConfig.owner};return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.PasswordInput,{label:label,description:description,required:required&&!hasExistingValue,disabled:disabled,value:value??"",onChange:e=>onChange(e.currentTarget.value),error:error,placeholder:hasExistingValue?"Laisser vide pour conserver le mot de passe actuel":void 0,visibilityToggleButtonProps:hasExistingValue?{style:{display:"none"}}:void 0}),hasExistingValue&&/*#__PURE__*/(0,jsx_runtime.jsx)(dist_index_js_.SecretField,{label:`${label} — voir la valeur actuelle`,fetchSecret:async revealToken=>{const res=await fetch(`${baseUrl}/v1/connectors/${appConfig.company}/${connectorCodename}/auth-secrets`,{headers:{...authHeaders,"X-Reveal-Token":revealToken}});if(!res.ok){const err=Object.assign(new Error(`${res.status}`),{status:res.status});throw err}const data=await res.json();const key=config.name;return data.secrets?.[key]??""}})]})}case"hidden":return null;case"msg":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:label});case"switch":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{label:label,description:description,disabled:disabled,checked:!!value,onChange:e=>onChange(e.currentTarget.checked)});case"zoho_gla_axes_selector":case"select":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:label,description:description,required:required,disabled:disabled,data:selectOptions,value:value??null,onChange:onChange,error:error,searchable:true,allowDeselect:false});case"date_boundary_start":return/*#__PURE__*/(0,jsx_runtime.jsx)(InputDateBoundary,{label:label,help:description,required:required,disabled:disabled,value:value,onChange:onChange,variant:"start"});case"date_boundary_end":return/*#__PURE__*/(0,jsx_runtime.jsx)(InputDateBoundary,{label:label,help:description,required:required,disabled:disabled,value:value,onChange:onChange,variant:"end"});case"tags_multiple":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TagsInput,{label:label,description:description,required:required,disabled:disabled,value:csvSplitValue,onChange:onChange,error:error});case"gsheets_account_selector":return/*#__PURE__*/(0,jsx_runtime.jsx)(InputGsheetsSelector,{label:label,help:description,required:required,disabled:disabled,value:value,onChange:onChange,error:error});case"excel_account_selector":return/*#__PURE__*/(0,jsx_runtime.jsx)(InputExcelSelector,{label:label,help:description,required:required,disabled:disabled,value:value,onChange:onChange,error:error});case"totp":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:label,description:description,required:required,disabled:disabled,value:value??"",onChange:e=>onChange(e.currentTarget.value),error:error,placeholder:"123456",autoComplete:"one-time-code",inputMode:"numeric"});case"hubspot_deal_property_selector":case"hubspot_line_item_property_selector":case"pennylane_gla_axes_selector":case"select_multiple":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.MultiSelect,{label:label,description:description,required:required,disabled:disabled,data:selectOptions,value:selectMultipleValue,onChange:onChange,error:error,searchable:true});case"number":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:label,description:description,required:required,disabled:disabled,value:value??"",onChange:onChange,error:error});case"checkbox":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Checkbox,{label:label,description:description,disabled:disabled,checked:!!value,onChange:e=>onChange(e.currentTarget.checked)});case"multi_select":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.MultiSelect,{label:label,description:description,required:required,disabled:disabled,data:selectOptions,value:arrayValue,onChange:onChange,error:error,searchable:true});case"recipe_cf_pipedrive":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TagsInput,{label:label,description:description,required:required,disabled:disabled,value:csvSplitValue,onChange:onChange,error:error});case"pennylane_cfs_category_mapping":return/*#__PURE__*/(0,jsx_runtime.jsx)(InputCfsCategoryMapping,{label:label,help:description,required:required,disabled:disabled,value:value,onChange:onChange,error:error,sourceValues:config.full?.values});default:{const accountCfg=config.type?ACCOUNT_SELECTOR_REGISTRY[config.type]:void 0;if(accountCfg)return/*#__PURE__*/(0,jsx_runtime.jsx)(InputAccountSelector,{accountCfg:accountCfg,sourceValues:config.full?.values,label:label,description:description,required:required,disabled:disabled,multiple:config.multiple,value:value,onChange:onChange,error:error});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Alert,{variant:"light",color:"yellow",title:`Type "${config.type}" non support\xe9`,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",children:["Champ : ",config.name]})})}}}function SynchroDynamicForm({config,save,connectorCodename,otherJobDestinations}){if(config.isPending||!config.data)return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{height:30,mt:6,radius:"xl"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{height:12,mt:6,w:"30%",radius:"xl"})]});if(!config.data.sections?.length)return null;return/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroDynamicFormInner,{data:config.data,save:save,connectorCodename:connectorCodename,otherJobDestinations:otherJobDestinations})}const WORKSHEET_FIELD_NAMES=new Set(["Sheet_Name","sheet_name","worksheet","Worksheet_Name","worksheetName"]);const SPREADSHEET_FIELD_NAMES=["Spreadsheet_Id","sheetId","spreadsheet_id","spreadsheetId"];function findFirstString(values,keys){for(const k of keys){const v=values[k];if("string"==typeof v&&v.length>0)return v}return null}function sectionLegend(section){const raw=section.name;if(!raw)return null;const tail=raw.split(".").pop()??raw;return tail.replace(/_/g," ")}function SynchroDynamicFormInner({data,save,connectorCodename,otherJobDestinations}){const form=(0,form_esm_index_mjs_.useForm)({initialValues:data.initialData});const{sections}=data;const{setFieldValue}=form;const fieldOnChanges=(0,index_js_.useMemo)(()=>{const map={};for(const section of sections)for(const field of section.fields){const name=field.name;if(name&&!(name in map))map[name]=value=>setFieldValue(name,value)}return map},[sections,setFieldValue]);const takenWorksheets=(0,index_js_.useMemo)(()=>{const map=new Map;for(const d of otherJobDestinations??[]){const k=`${d.spreadsheet_id}\0${d.worksheet}`;const list=map.get(k);if(list)list.push(d);else map.set(k,[d])}return map},[otherJobDestinations]);const currentSpreadsheetId=findFirstString(form.values,SPREADSHEET_FIELD_NAMES);const noop=(0,index_js_.useMemo)(()=>()=>{},[]);const renderField=(fieldConfig,key)=>{const name=fieldConfig.name;let collisionWarning=null;if(name&&WORKSHEET_FIELD_NAMES.has(name)&&currentSpreadsheetId&&"string"==typeof form.values[name]&&form.values[name].length>0){const k=`${currentSpreadsheetId}\0${form.values[name]}`;const collisions=takenWorksheets.get(k);if(collisions&&collisions.length>0)collisionWarning=collisions}return/*#__PURE__*/(0,jsx_runtime.jsx)(FormField,{config:fieldConfig,value:form.values[name],onChange:fieldOnChanges[name]??noop,error:form.errors[name],connectorCodename:connectorCodename,collisionWarning:collisionWarning},key)};return/*#__PURE__*/(0,jsx_runtime.jsx)("form",{autoComplete:"off",onSubmit:form.onSubmit(values=>save.mutate(values)),children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[sections.map((section,si)=>{const legend=sectionLegend(section);const fields=section.fields.map((fieldConfig,fi)=>renderField(fieldConfig,`${si}-${fi}`));if(!legend)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:"md",children:fields},si);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Fieldset,{legend:legend,variant:"filled",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:"md",children:fields})},si)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{justify:"flex-end",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{type:"submit",loading:save.isPending,children:"Enregistrer"})})]})})}function JobConfigModal({job,recipeId,tasks,destinationCodename,companyDestinations,opened,onClose}){const save=useSynchroJobSaveMutation();const rename=useSynchroJobRenameMutation();const configQuery=useSynchroJobConfigQuery(opened?recipeId:null,opened?job?.id??null:null);const[editingName,setEditingName]=(0,index_js_.useState)(false);const[nameDraft,setNameDraft]=(0,index_js_.useState)("");(0,index_js_.useEffect)(()=>{if(!opened){setEditingName(false);setNameDraft("")}},[opened]);(0,index_js_.useEffect)(()=>{setNameDraft(job?.task_fr??"")},[job?.task_fr]);const saveMutation=(0,index_js_.useMemo)(()=>({...save,mutate:values=>{if(!job)return;save.mutate({id:recipeId,jobId:job.id,data:values},{onSuccess:()=>onClose()})}}),[save,job,recipeId,onClose]);if(!job)return null;const hasForm=configQuery.data?.sections?.length>0;const jobTasks=(tasks??[]).filter(t=>t.job_name_fr===job.task_fr);const startEdit=()=>{setNameDraft(job.task_fr??"");setEditingName(true)};const cancelEdit=()=>{setEditingName(false);setNameDraft("")};const submitEdit=()=>{const trimmed=nameDraft.trim();if(!trimmed||trimmed===job.task_fr)return void cancelEdit();rename.mutate({id:recipeId,jobId:job.id,name:trimmed},{onSuccess:()=>setEditingName(false)})};const titleNode=editingName?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",style:{flex:1},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{value:nameDraft,onChange:e=>setNameDraft(e.currentTarget.value),onKeyDown:e=>{if("Enter"===e.key)submitEdit();if("Escape"===e.key)cancelEdit()},autoFocus:true,size:"sm",style:{flex:1,minWidth:240},disabled:rename.isPending}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",color:"green",variant:"subtle",loading:rename.isPending,onClick:submitEdit,title:"Enregistrer",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCheck,{size:16})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",color:"gray",variant:"subtle",onClick:cancelEdit,disabled:rename.isPending,title:"Annuler",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconX,{size:16})})]}):/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:6,wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:600,children:job.task_fr}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Renommer la t\xe2che",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",color:"gray",onClick:startEdit,children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconPencil,{size:14})})})]});return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Modal,{opened:opened,onClose:onClose,title:titleNode,size:"lg",children:[job.gsheet_collision&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Alert,{color:"yellow",icon:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconAlertTriangle,{size:16}),title:"Conflit de destination Gsheet",mb:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",children:["D'autres synchros \xe9crivent sur l'onglet \xab"," ",/*#__PURE__*/(0,jsx_runtime.jsx)("strong",{children:job.gsheet_collision.worksheet})," \xbb de ce m\xeame spreadsheet :"]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:2,mt:6,children:job.gsheet_collision.others.map((o,i)=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",children:["• ",o.recipe_name," — ",o.job_name_fr??"(sans nom)"]},i))}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",mt:6,children:"V\xe9rifie que ce n'est pas un \xe9crasement involontaire."})]}),configQuery.isPending||hasForm?/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroDynamicForm,{config:configQuery,save:saveMutation,connectorCodename:job.connector_from?.codename??job.connector_to?.codename,otherJobDestinations:(companyDestinations??[]).filter(d=>d.job_id!==job.id)}):/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",children:"Rien \xe0 configurer pour cette t\xe2che."}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:6,c:"dimmed",children:"Historique"}),/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroHistory,{tasks:jobTasks,destinationCodename:destinationCodename})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{justify:"flex-end",mt:"md",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",color:"gray",onClick:onClose,children:"Fermer"})})]})}function useCreateScheduleMutation(){const api=useApiSynchro();const qc=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({recipeCustomerId,data})=>api.post(`/synchro/${recipeCustomerId}/schedules`,data),onSuccess:()=>qc.invalidateQueries({queryKey:["synchro"]})})}function useUpdateScheduleMutation(){const api=useApiSynchro();const qc=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({recipeCustomerId,scheduleId,data})=>api.put(`/synchro/${recipeCustomerId}/schedules/${scheduleId}`,data),onSuccess:()=>qc.invalidateQueries({queryKey:["synchro"]})})}function useDeleteScheduleMutation(){const api=useApiSynchro();const qc=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({recipeCustomerId,scheduleId})=>api.delete(`/synchro/${recipeCustomerId}/schedules/${scheduleId}`),onSuccess:()=>qc.invalidateQueries({queryKey:["synchro"]})})}const DAY_LABELS={monday:"Lun",tuesday:"Mar",wednesday:"Mer",thursday:"Jeu",friday:"Ven",saturday:"Sam",sunday:"Dim"};const ALL_DAYS=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];function SynchroSchedules({schedules,jobs,recipeCustomerId}){const[opened,{open,close}]=(0,esm_index_mjs_.useDisclosure)(false);const[editing,setEditing]=(0,index_js_.useState)(null);const handleEdit=s=>{setEditing(s);open()};const handleNew=()=>{setEditing(null);open()};return/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[0===schedules.length&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",children:"Aucun d\xe9clencheur configur\xe9."}),schedules.map(s=>/*#__PURE__*/(0,jsx_runtime.jsx)(ScheduleCard,{schedule:s,jobs:jobs,recipeCustomerId:recipeCustomerId,onEdit:()=>handleEdit(s)},s.id)),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"light",size:"xs",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconPlus,{size:14}),onClick:handleNew,w:"fit-content",children:"Ajouter un d\xe9clencheur"})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ScheduleModal,{opened:opened,onClose:close,schedule:editing,jobs:jobs,recipeCustomerId:recipeCustomerId})]})}function ScheduleCard({schedule,jobs,recipeCustomerId,onEdit}){const deleteMut=useDeleteScheduleMutation();const hour=String(schedule.hour??0).padStart(2,"0");const minute=String(schedule.minute??0).padStart(2,"0");const taskLabels=schedule.tasks.map(t=>{const job=jobs.find(j=>String(j.id)===t);return job?.active?job.task_fr:null}).filter(Boolean);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Card,{withBorder:true,p:"sm",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:6,style:{flex:1},children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconClock,{size:16}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",fw:500,children:[hour,":",minute]}),schedule.frequency&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",size:"sm",children:schedule.frequency}),schedule.draft&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",size:"sm",color:"yellow",children:"Brouillon"})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCalendar,{size:16}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:4,children:ALL_DAYS.map(day=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{size:"xs",variant:schedule.days.includes(day)?"filled":"light",color:schedule.days.includes(day)?"teal":"gray",children:DAY_LABELS[day]},day))})]}),taskLabels.length>0&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:4,wrap:"wrap",children:taskLabels.map((label,i)=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{size:"xs",variant:"outline",children:label},i))})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",onClick:onEdit,title:"Modifier",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconPencil,{size:14})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",color:"red",loading:deleteMut.isPending,onClick:()=>deleteMut.mutate({recipeCustomerId,scheduleId:schedule.id}),title:"Supprimer",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTrash,{size:14})})]})]})})}function ScheduleModal({opened,onClose,schedule,jobs,recipeCustomerId}){const createMut=useCreateScheduleMutation();const updateMut=useUpdateScheduleMutation();const[days,setDays]=(0,index_js_.useState)(ALL_DAYS);const[hour,setHour]=(0,index_js_.useState)(1);const[minute,setMinute]=(0,index_js_.useState)(0);const[selectedTasks,setSelectedTasks]=(0,index_js_.useState)([]);(0,index_js_.useEffect)(()=>{if(schedule){setDays(schedule.days);setHour(schedule.hour??1);setMinute(schedule.minute??0);setSelectedTasks(schedule.tasks)}else{setDays(ALL_DAYS);setHour(1);setMinute(0);setSelectedTasks([])}},[schedule,opened]);const toggleDay=day=>{setDays(prev=>prev.includes(day)?prev.filter(d=>d!==day):[...prev,day])};const toggleTask=task=>{setSelectedTasks(prev=>prev.includes(task)?prev.filter(t=>t!==task):[...prev,task])};const handleSave=()=>{const data={days,hour,minute,tasks:selectedTasks};if(schedule)updateMut.mutate({recipeCustomerId,scheduleId:schedule.id,data},{onSuccess:onClose});else createMut.mutate({recipeCustomerId,data},{onSuccess:onClose})};const isPending=createMut.isPending||updateMut.isPending;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:opened,onClose:onClose,title:schedule?"Modifier le d\xe9clencheur":"Nouveau d\xe9clencheur",size:"md",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:"Heure",value:hour,onChange:v=>setHour(Number(v)),min:0,max:23,w:80}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:"Minute",value:minute,onChange:v=>setMinute(Number(v)),min:0,max:59,w:80})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",fw:500,children:"Jours"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:4,children:ALL_DAYS.map(day=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{size:"lg",variant:days.includes(day)?"filled":"light",color:days.includes(day)?"teal":"gray",style:{cursor:"pointer"},onClick:()=>toggleDay(day),children:DAY_LABELS[day]},day))})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",fw:500,children:"Jobs \xe0 d\xe9clencher"}),jobs.map(job=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Checkbox,{label:job.task_fr??job.task,checked:selectedTasks.includes(String(job.id)),onChange:()=>toggleTask(String(job.id))},job.id))]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",color:"gray",onClick:onClose,children:"Annuler"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{onClick:handleSave,loading:isPending,children:schedule?"Enregistrer":"Cr\xe9er"})]})]})})}function subsKey(company){return["synchro","subscriptions",company]}function useSubscriptionToggle(active){const api=useApiSynchro();const config=useAppConfigSynchro();const qc=(0,modern_index_js_.useQueryClient)();const key=subsKey(config.company);return(0,modern_index_js_.useMutation)({mutationFn:synchroId=>active?api.post(`/synchro/${synchroId}/notifications/subscribe`):api.delete(`/synchro/${synchroId}/notifications/subscribe`),onMutate:async synchroId=>{await qc.cancelQueries({queryKey:key});const previous=qc.getQueryData(key);if(previous){const next=active?previous.subscriptions.includes(synchroId)?previous.subscriptions:[...previous.subscriptions,synchroId]:previous.subscriptions.filter(id=>id!==synchroId);qc.setQueryData(key,{...previous,subscriptions:next})}return{previous}},onError:(_err,_vars,context)=>{if(context?.previous)qc.setQueryData(key,context.previous)},onSettled:()=>{qc.invalidateQueries({queryKey:key})}})}function useSynchroSubscribeMutation(){return useSubscriptionToggle(true)}function useSynchroUnsubscribeMutation(){return useSubscriptionToggle(false)}function EnableNotificationsModal({opened,onClose,onActivate}){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:opened,onClose:onClose,title:"Activer les notifications",centered:true,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"Souhaitez-vous activer les notifications du syst\xe8me d'exploitation pour \xeatre pr\xe9venu de la fin de vos runs m\xeame si l'onglet est en arri\xe8re-plan ?"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:"Vous pouvez r\xe9pondre plus tard — la cloche fonctionnera quand m\xeame via les notifications dans l'app."}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",onClick:onClose,children:"Plus tard"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{onClick:onActivate,children:"Activer"})]})]})})}function SynchroBell({synchroId}){const subsRes=useSynchroSubscriptionsQuery();const subscribe=useSynchroSubscribeMutation();const unsubscribe=useSynchroUnsubscribeMutation();const[permissionModalOpen,setPermissionModalOpen]=(0,index_js_.useState)(false);const isSubscribed=subsRes.data?.subscriptions.includes(synchroId)??false;const loading=subscribe.isPending||unsubscribe.isPending;const performToggle=()=>{if(isSubscribed)unsubscribe.mutate(synchroId);else subscribe.mutate(synchroId)};const handleClick=()=>{if(!isSubscribed&&"undefined"!=typeof Notification&&"default"===Notification.permission)return void setPermissionModalOpen(true);performToggle()};const handleActivate=()=>{setPermissionModalOpen(false);if("undefined"!=typeof Notification)Notification.requestPermission().finally(()=>performToggle());else performToggle()};const handleSkipPermission=()=>{setPermissionModalOpen(false);performToggle()};const label=isSubscribed?"Notifications activ\xe9es — cliquer pour d\xe9sactiver":"Activer les notifications pour cette synchro";return/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:label,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{variant:isSubscribed?"filled":"outline",color:isSubscribed?"blue":"gray",onClick:handleClick,loading:loading,"aria-label":label,children:isSubscribed?/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconBell,{size:18}):/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconBellOff,{size:18})})}),/*#__PURE__*/(0,jsx_runtime.jsx)(EnableNotificationsModal,{opened:permissionModalOpen,onClose:handleSkipPermission,onActivate:handleActivate})]})}function useMyRunsQuery(){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","my-runs",config.company],queryFn:()=>api.get(`/synchro/notifications/my-runs?cid=${config.company}`),staleTime:0,refetchInterval:query=>{const runs=query.state.data?.runs??[];const hasActive=runs.some(r=>r.tasks.some(t=>!t.finished));return hasActive?5e3:false},refetchIntervalInBackground:true,refetchOnWindowFocus:true})}const TTL_MS=36e5;function cleanup(){const now=Date.now();for(const key of Object.keys(localStorage)){if(!key.startsWith("notified:"))continue;const ts=Number(localStorage.getItem(key));if(!Number.isFinite(ts)||now-ts>TTL_MS)localStorage.removeItem(key)}}function alreadyNotified(key){cleanup();return null!==localStorage.getItem(key)}function markNotified(key){localStorage.setItem(key,String(Date.now()))}function synchroRunKey(recipeUuid){return`notified:synchro:${recipeUuid}`}function jobRunKey(taskId){return`notified:job:${taskId}`}function tasksAllFinished(run){return run.tasks.every(t=>t.finished)}function errorCount(run){return run.tasks.filter(t=>null!==t.error).length}function emitNotification(run,isSynchroLevel,navigateToSynchro){const errors=errorCount(run);const total=run.tasks.length;let title;let message;let color;if(isSynchroLevel){title=run.recipe_customer_name;if(0===errors){message=`Termin\xe9e — ${total} job${total>1?"s":""} OK`;color="green"}else{message=`Termin\xe9e avec ${errors} erreur${errors>1?"s":""} (${total-errors} OK)`;color="yellow"}}else{const task=run.tasks[0];title=`${run.recipe_customer_name} — ${task.job_name_fr??"Job"}`;if(null===task.error){message="Termin\xe9";color="green"}else{message=`\xc9chec : ${task.error}`;color="red"}}notifications_esm_index_mjs_.notifications.show({title,message,color,variant:"filled",autoClose:8e3,onClick:()=>navigateToSynchro(run.recipe_customer_id),style:{cursor:"pointer"},styles:{title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}}});if("undefined"!=typeof Notification&&"granted"===Notification.permission)try{const osNotif=new Notification(title,{body:message,tag:run.recipe_uuid});osNotif.onclick=()=>{window.focus();navigateToSynchro(run.recipe_customer_id);osNotif.close()}}catch{}return 0===errors?"ok":"ko"}function useNotifyOnRunComplete(navigateToSynchro,onTabNotify){const myRunsRes=useMyRunsQuery();const subsRes=useSynchroSubscriptionsQuery();const qc=(0,modern_index_js_.useQueryClient)();const runs=myRunsRes.data?.runs;const subscriptionList=subsRes.data?.subscriptions;(0,index_js_.useEffect)(()=>{if(!runs||!subscriptionList)return;const subscribed=new Set(subscriptionList);for(const run of runs){if(!subscribed.has(run.recipe_customer_id))continue;const isSynchroLevel=run.tasks.length>1;if(isSynchroLevel){const dedupKey=synchroRunKey(run.recipe_uuid);if(alreadyNotified(dedupKey))continue;if(!tasksAllFinished(run))continue;const kind=emitNotification(run,true,navigateToSynchro);onTabNotify?.(kind);markNotified(dedupKey);qc.invalidateQueries({queryKey:["synchro","detail",run.recipe_customer_id]});qc.invalidateQueries({queryKey:["synchro","list"]})}else{const task=run.tasks[0];const dedupKey=jobRunKey(task.id);if(alreadyNotified(dedupKey))continue;if(!task.finished)continue;const kind=emitNotification(run,false,navigateToSynchro);onTabNotify?.(kind);markNotified(dedupKey);qc.invalidateQueries({queryKey:["synchro","detail",run.recipe_customer_id]});qc.invalidateQueries({queryKey:["synchro","list"]})}}},[runs,subscriptionList,navigateToSynchro,onTabNotify,qc])}let originalHref=null;function setFaviconBadge(color){const link=document.querySelector("link[rel~='icon']");if(!link)return;if(null===originalHref)originalHref=link.href;if(null===color){link.href=originalHref;return}const img=new Image;img.crossOrigin="anonymous";img.src=originalHref;img.onload=()=>{const canvas=document.createElement("canvas");canvas.width=32;canvas.height=32;const ctx=canvas.getContext("2d");if(!ctx)return;ctx.drawImage(img,0,0,32,32);ctx.fillStyle="green"===color?"#22c55e":"#ef4444";ctx.beginPath();ctx.arc(24,24,7,0,2*Math.PI);ctx.fill();link.href=canvas.toDataURL("image/png")};img.onerror=()=>{const canvas=document.createElement("canvas");canvas.width=32;canvas.height=32;const ctx=canvas.getContext("2d");if(!ctx)return;ctx.fillStyle="green"===color?"#22c55e":"#ef4444";ctx.beginPath();ctx.arc(16,16,12,0,2*Math.PI);ctx.fill();link.href=canvas.toDataURL("image/png")}}function useTabNotificationIndicator(){const countRef=(0,index_js_.useRef)(0);const lastColorRef=(0,index_js_.useRef)(null);const originalTitleRef=(0,index_js_.useRef)(null);(0,index_js_.useEffect)(()=>{if(null===originalTitleRef.current)originalTitleRef.current=document.title;const onVisibility=()=>{if("visible"===document.visibilityState){countRef.current=0;lastColorRef.current=null;if(originalTitleRef.current)document.title=originalTitleRef.current;setFaviconBadge(null)}};document.addEventListener("visibilitychange",onVisibility);return()=>document.removeEventListener("visibilitychange",onVisibility)},[]);return{notify(kind){if("visible"===document.visibilityState)return;countRef.current+=1;lastColorRef.current="ok"===kind?"green":"red";if(originalTitleRef.current)document.title=`(${countRef.current}) ${originalTitleRef.current}`;setFaviconBadge(lastColorRef.current)}}}const EnableNotificationsBanner_KEY=uid=>`notifications-permission-asked:${uid}`;function EnableNotificationsBanner({userId}){const[hidden,setHidden]=(0,index_js_.useState)(true);(0,index_js_.useEffect)(()=>{if("undefined"==typeof Notification)return;const asked=localStorage.getItem(EnableNotificationsBanner_KEY(userId));if(!asked&&"default"===Notification.permission)setHidden(false)},[userId]);if(hidden)return null;const enable=async()=>{const result=await Notification.requestPermission();localStorage.setItem(EnableNotificationsBanner_KEY(userId),result);setHidden(true)};const dismiss=()=>{localStorage.setItem(EnableNotificationsBanner_KEY(userId),"dismissed");setHidden(true)};return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Alert,{icon:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconBell,{size:18}),color:"blue",mb:"md",withCloseButton:true,onClose:dismiss,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"Activez les notifications pour \xeatre pr\xe9venu de la fin de vos syncros."}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{size:"xs",onClick:enable,children:"Activer"})]})})}function SynchroApp(){const config=useAppConfigSynchro();const isMobile=(0,esm_index_mjs_.useMediaQuery)("(max-width: 48em)",false);const{notify}=useTabNotificationIndicator();const[selectedId,setSelectedIdState]=(0,index_js_.useState)(()=>{const param=new URLSearchParams(window.location.search).get("recipeId");const parsed=param?Number(param):NaN;return Number.isInteger(parsed)&&parsed>0?parsed:null});const[configJobSnapshot,setConfigJobSnapshot]=(0,index_js_.useState)(null);const[runsModalJobSnapshot,setRunsModalJobSnapshot]=(0,index_js_.useState)(null);const listRes=useSynchroListQuery();const detailRes=useSynchroDetailQuery(selectedId);const runAll=useSynchroRunMutation();const toggle=useSynchroToggleMutation();const recipes=listRes.data??[];const detail=detailRes.data;const configJob=configJobSnapshot?detail?.jobs.find(j=>j.id===configJobSnapshot.id)??configJobSnapshot:null;const runsModalJob=runsModalJobSnapshot?detail?.jobs.find(j=>j.id===runsModalJobSnapshot.id)??runsModalJobSnapshot:null;const setSelectedId=(0,index_js_.useCallback)(id=>{setSelectedIdState(id);const url=new URL(window.location.href);if(null===id)url.searchParams.delete("recipeId");else url.searchParams.set("recipeId",String(id));window.history.replaceState({},"",url)},[]);useNotifyOnRunComplete(setSelectedId,notify);(0,index_js_.useEffect)(()=>{if(0===recipes.length)return;const exists=null!==selectedId&&recipes.some(r=>r.id===selectedId);if(exists)return;const hasRecipeParam=new URLSearchParams(window.location.search).has("recipeId");if(isMobile&&!hasRecipeParam){if(null!==selectedId)setSelectedId(null);return}setSelectedId(recipes[0].id)},[isMobile,recipes,selectedId,setSelectedId]);if(listRes.isPending)return/*#__PURE__*/(0,jsx_runtime.jsx)(InlineLoader.F,{label:"Chargement des synchronisations..."});const listPanel=/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:5,p:"sm",c:"dimmed",children:"Synchronisations"}),0===recipes.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",px:"sm",children:"Aucune recette configur\xe9e."}):/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroList,{recipes:recipes,selectedId:selectedId,onSelect:setSelectedId,mobile:isMobile})]});const detailPanel=null===selectedId?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",children:"S\xe9lectionnez une recette."}):detailRes.isPending?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{h:40}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{h:120}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{h:200})]}):detail?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"lg",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:3,children:"Total"===detail.recipe.name||"[Total]"===detail.recipe.name?"Vue d'ensemble":detail.recipe.name}),!isMobile&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"sm",justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroBell,{synchroId:detail.id}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{checked:detail.active,label:detail.active?"Actif":"Inactif",onChange:()=>toggle.mutate({id:detail.id,active:!detail.active})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"light",color:"green",loading:runAll.isPending,onClick:()=>runAll.mutate(detail.id),children:"▶ Lancer tout"})]})]}),!("Total"===detail.recipe.name||"[Total]"===detail.recipe.name)&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:5,c:"dimmed",children:"D\xe9clencheurs"}),/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroSchedules,{schedules:detail.schedules,jobs:detail.jobs,recipeCustomerId:detail.id})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroFunctions,{detail:detail,onConfigJob:setConfigJobSnapshot,onShowRuns:isMobile?()=>void 0:setRunsModalJobSnapshot,mobile:isMobile}),!isMobile&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Accordion,{defaultValue:"history",variant:"default",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Accordion.Item,{value:"history",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Accordion.Control,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:5,c:"dimmed",children:"Historique"})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Accordion.Panel,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroHistory,{tasks:detail.tasks,destinationCodename:detail.recipe.connector_to?.codename??null})})]})})]}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",children:"Impossible de charger la recette."});return/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(EnableNotificationsBanner,{userId:config.owner}),isMobile?null===selectedId?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{h:"100%",p:"xs",children:listPanel}):/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{h:"100%",gap:"sm",p:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",color:"gray",justify:"start",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconArrowLeft,{size:18}),onClick:()=>setSelectedId(null),children:"Toutes les synchros"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{flex:1,style:{overflowY:"auto",minHeight:0,paddingBottom:"calc(132px + env(safe-area-inset-bottom))"},children:detailPanel})]}):/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{wrap:"nowrap",h:"100%",align:"flex-start",gap:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{w:220,h:"100%",style:{flexShrink:0,borderRight:"1px solid var(--mantine-color-dark-5)"},children:listPanel}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{flex:1,p:"md",style:{overflowY:"auto"},children:detailPanel})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(JobConfigModal,{job:configJob,recipeId:configJob?.recipe_customer_id??selectedId??0,tasks:detail?.tasks,destinationCodename:detail?.recipe.connector_to?.codename??null,companyDestinations:detail?.company_destinations,opened:null!==configJob,onClose:()=>setConfigJobSnapshot(null)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:null!==runsModalJob,onClose:()=>setRunsModalJobSnapshot(null),title:runsModalJob?`Historique — ${runsModalJob.task_fr}`:"Historique des ex\xe9cutions",size:"xl",children:runsModalJob&&detail&&/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroHistory,{tasks:detail.tasks.filter(t=>t.job_name_fr===runsModalJob.task_fr),destinationCodename:detail.recipe.connector_to?.codename??null})})]})}var dist_esm_index_mjs_=__webpack_require__(4449);const theme=(0,index_mjs_.createTheme)((0,dist_esm_index_mjs_.assign)(dist_index_js_.theme,{components:{}}));const cssVarResolver=x=>(0,dist_esm_index_mjs_.assign)(dist_index_js_.cssVarResolver(x),{dark:{},light:{},variables:{}});function ProvidersSynchro(props){const{children,config,mantine,tanstack}=props;return/*#__PURE__*/(0,jsx_runtime.jsx)(AppConfigSynchroProvider,{value:config,children:/*#__PURE__*/(0,jsx_runtime.jsx)(modern_index_js_.QueryClientProvider,{client:tanstack?.queryClient??new modern_index_js_.QueryClient,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.MantineProvider,{theme:theme,cssVariablesResolver:cssVarResolver,defaultColorScheme:mantine?.defaultColorScheme,forceColorScheme:mantine?.forceColorScheme,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(notifications_esm_index_mjs_.Notifications,{}),/*#__PURE__*/(0,jsx_runtime.jsx)(dist_index_js_.RevealTokenProvider,{children:children})]})})})}function Synchronisation(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_js_.StrictMode,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(ProvidersSynchro,{...props,children:/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroApp,{})})})}},800:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{F:()=>InlineLoader});var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(4848);var _mantine_core__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(2773);function InlineLoader({label}){return/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Center,{flex:1,h:"100%",children:/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Stack,{align:"center",gap:"md",children:[/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Loader,{size:"md",color:"teal"}),label&&/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Text,{fz:"sm",c:"dimmed",children:label})]})})}}}]);
10
+ */var REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element"),REACT_FRAGMENT_TYPE=Symbol.for("react.fragment");function jsxProd(type,config,maybeKey){var key=null;void 0!==maybeKey&&(key=""+maybeKey);void 0!==config.key&&(key=""+config.key);if("key"in config){maybeKey={};for(var propName in config)"key"!==propName&&(maybeKey[propName]=config[propName])}else maybeKey=config;config=maybeKey.ref;return{$$typeof:REACT_ELEMENT_TYPE,type:type,key:key,ref:void 0!==config?config:null,props:maybeKey}}exports.Fragment=REACT_FRAGMENT_TYPE;exports.jsx=jsxProd;exports.jsxs=jsxProd},4848:function(module,__unused_webpack_exports,__webpack_require__){module.exports=__webpack_require__(9698)},2503:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,{default:()=>Synchronisation});var jsx_runtime=__webpack_require__(4848);var index_js_=__webpack_require__(7060);var index_mjs_=__webpack_require__(4763);var esm_index_mjs_=__webpack_require__(8403);var InlineLoader=__webpack_require__(800);var modern_index_js_=__webpack_require__(7370);const AppConfigSynchroCtx=/*#__PURE__*/(0,index_js_.createContext)(null);const AppConfigSynchroProvider=AppConfigSynchroCtx.Provider;function useAppConfigSynchro(){const config=(0,index_js_.useContext)(AppConfigSynchroCtx);if(!config)throw new Error("Called `useAppConfigSynchro` outside a `<AppConfigSynchroProvider />`");return config}function useApiSynchro(){const config=useAppConfigSynchro();const baseUrl=config.api.replace(/\/$/,"");const authHeaders={Authorization:config.token?`Bearer ${config.token}`:"",From:config.owner};const jsonHeaders={...authHeaders,"Content-Type":"application/json"};const handleResponse=async res=>{if(!res.ok){const fallback=`${res.status} ${res.statusText}`;const text=await res.text().catch(()=>"");if(!text)throw new Error(fallback);let message=text;try{const body=JSON.parse(text);message=Array.isArray(body.message)?body.message.join(", "):body.message??fallback}catch{message=text}throw new Error(message||fallback)}return res.json()};return{get:path=>fetch(`${baseUrl}${path}`,{headers:jsonHeaders,cache:"no-store"}).then(handleResponse),post:(path,body)=>fetch(`${baseUrl}${path}`,{method:"POST",headers:jsonHeaders,cache:"no-store",body:void 0!==body?JSON.stringify(body):void 0}).then(handleResponse),postForm:(path,body)=>fetch(`${baseUrl}${path}`,{method:"POST",headers:authHeaders,cache:"no-store",body}).then(handleResponse),put:(path,body)=>fetch(`${baseUrl}${path}`,{method:"PUT",headers:jsonHeaders,cache:"no-store",body:void 0!==body?JSON.stringify(body):void 0}).then(handleResponse),delete:path=>fetch(`${baseUrl}${path}`,{method:"DELETE",headers:jsonHeaders,cache:"no-store"}).then(handleResponse)}}function useSynchroListQuery(){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","list",config.company],queryFn:()=>api.get(`/synchro?cid=${config.company}`),staleTime:6e4,refetchOnWindowFocus:true,refetchOnReconnect:true})}function useSynchroDetailQuery(id){const api=useApiSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","detail",id],queryFn:()=>api.get(`/synchro/${id}`),enabled:null!==id,staleTime:3e4,refetchOnWindowFocus:true,refetchOnReconnect:true,refetchInterval:query=>{const tasks=query.state.data?.tasks??[];const hasRunning=tasks.some(t=>!t.finished);return hasRunning?5e3:false}})}var notifications_esm_index_mjs_=__webpack_require__(7467);function useSynchroRunMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:id=>api.post(`/synchro/${id}/run`),onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({color:"blue",variant:"filled",title:"Recette lanc\xe9e",message:"La synchronisation a d\xe9marr\xe9.",styles:{title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}}});return Promise.all([queryClient.invalidateQueries({queryKey:["synchro","detail"]}),queryClient.invalidateQueries({queryKey:["synchro","list",config.company]}),queryClient.invalidateQueries({queryKey:["synchro","my-runs",config.company]})])},onError:()=>{notifications_esm_index_mjs_.notifications.show({color:"red",variant:"filled",title:"Erreur",message:"Impossible de lancer la recette.",styles:{title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}}})}})}function useSynchroToggleMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();const detailKey=id=>["synchro","detail",id];const listKey=["synchro","list",config.company];return(0,modern_index_js_.useMutation)({mutationFn:({id,active})=>api.put(`/synchro/${id}`,{active}),onMutate:async({id,active})=>{await queryClient.cancelQueries({queryKey:detailKey(id)});await queryClient.cancelQueries({queryKey:listKey});const previousDetail=queryClient.getQueryData(detailKey(id));const previousList=queryClient.getQueryData(listKey);if(previousDetail)queryClient.setQueryData(detailKey(id),{...previousDetail,active});if(previousList)queryClient.setQueryData(listKey,previousList.map(r=>r.id===id?{...r,active}:r));return{previousDetail,previousList}},onError:(_err,{id},context)=>{if(context?.previousDetail)queryClient.setQueryData(detailKey(id),context.previousDetail);if(context?.previousList)queryClient.setQueryData(listKey,context.previousList);notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible de modifier la recette."})},onSettled:(_data,_err,{id})=>{queryClient.invalidateQueries({queryKey:detailKey(id)});queryClient.invalidateQueries({queryKey:listKey})}})}var tabler_icons_react_mjs_=__webpack_require__(4462);function useSynchroSubscriptionsQuery(){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","subscriptions",config.company],queryFn:()=>api.get(`/synchro/notifications/subscriptions?cid=${config.company}`),staleTime:3e5,refetchOnWindowFocus:false})}var connectorLogoUrl=__webpack_require__(1034);function statusColor(customer){if(!customer.active)return"gray";const task=customer.lastTask;if(!task)return"gray";if(!task.finished)return"yellow";return task.error?"red":"green"}function ConnectorLogo({connector,size=44}){if(!connector)return null;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:connector.name,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:(0,connectorLogoUrl.U)(connector),size:size,radius:"md",p:0,style:{flexShrink:0}})})}function isOverviewRecipe(r){return"Total"===r.recipe.name||"[Total]"===r.recipe.name}function buildSections(recipes){let overview=null;const byType=new Map;for(const r of recipes){if(isOverviewRecipe(r)){overview=r;continue}const t=r.recipe.connector_from?.type;const key=t?.codename??"other";if(!byType.has(key))byType.set(key,{type:t??{codename:"other",name:"Autres"},recipes:[]});byType.get(key).recipes.push(r)}const sections=Array.from(byType.values()).sort((a,b)=>a.type.name.localeCompare(b.type.name));return{overview,sections}}function RecipeRow({customer,selectedId,onSelect,subscribed,mobile=false}){const color=statusColor(customer);const isSelected=customer.id===selectedId;const from=customer.recipe.connector_from;const to=customer.recipe.connector_to;const isOverview=isOverviewRecipe(customer);const isInactive=!customer.active&&!isOverview;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.UnstyledButton,{onClick:()=>onSelect(customer.id),style:{position:"relative",borderLeft:`3px solid var(--mantine-color-${color}-6)`,background:isSelected?"var(--mantine-color-dark-6)":"transparent",borderRadius:4,display:"block",boxSizing:"border-box",width:"100%",padding:mobile?"10px 6px":"6px 10px",opacity:isInactive?.45:1,filter:isInactive?"grayscale(0.7)":void 0,overflow:"hidden"},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:mobile?18:8,wrap:"nowrap",justify:"center",children:isOverview?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Vue d'ensemble",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:mobile?12:6,wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconHome,{size:mobile?28:20}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:mobile?"md":"sm",fw:mobile?600:void 0,children:"Vue d'ensemble"})]})}):from||to?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:mobile?22:12,wrap:"nowrap",justify:"center",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(ConnectorLogo,{connector:from,size:mobile?72:44}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:mobile?"xl":"lg",c:"dimmed",children:"→"}),/*#__PURE__*/(0,jsx_runtime.jsx)(ConnectorLogo,{connector:to,size:mobile?72:44})]}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:mobile?"md":"sm",truncate:true,children:customer.recipe.name})}),subscribed&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Notifications activ\xe9es",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconBell,{size:14,color:"var(--mantine-color-blue-5)",style:{position:"absolute",top:4,right:4}})})]})}function SynchroList({recipes,selectedId,onSelect,mobile=false}){const{overview,sections}=buildSections(recipes);const subsRes=useSynchroSubscriptionsQuery();const subscribed=new Set(subsRes.data?.subscriptions??[]);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ScrollArea,{h:"100%",scrollbars:"y",type:"hover",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:mobile?10:8,p:mobile?4:8,style:{boxSizing:"border-box",width:"100%"},children:[overview&&/*#__PURE__*/(0,jsx_runtime.jsx)(RecipeRow,{customer:overview,selectedId:selectedId,onSelect:onSelect,subscribed:subscribed.has(overview.id),mobile:mobile}),sections.map(section=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:mobile?8:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:6,c:"dimmed",pl:mobile?8:10,pt:6,children:section.type.name}),section.recipes.map(r=>/*#__PURE__*/(0,jsx_runtime.jsx)(RecipeRow,{customer:r,selectedId:selectedId,onSelect:onSelect,subscribed:subscribed.has(r.id),mobile:mobile},r.id))]},section.type.codename))]})})}const KEY=userId=>`synchro-tiles-cols:${userId}`;function useTilesColumns(userId){const[cols,setColsState]=(0,index_js_.useState)(()=>{const raw=localStorage.getItem(KEY(userId));return"1"===raw?1:2});(0,index_js_.useEffect)(()=>{localStorage.setItem(KEY(userId),String(cols))},[userId,cols]);const setCols=(0,index_js_.useCallback)(c=>setColsState(c),[]);const visibleLimit=1===cols?8:16;return{cols,setCols,visibleLimit}}var modals_esm_index_mjs_=__webpack_require__(7035);function useSynchroJobRunMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({id,jobId})=>api.post(`/synchro/${id}/jobs/${jobId}/run`),onSuccess:()=>{notifications_esm_index_mjs_.notifications.show({color:"blue",variant:"filled",title:"T\xe2che lanc\xe9e",message:"La t\xe2che a d\xe9marr\xe9.",styles:{title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}}});return Promise.all([queryClient.invalidateQueries({queryKey:["synchro","detail"]}),queryClient.invalidateQueries({queryKey:["synchro","list",config.company]}),queryClient.invalidateQueries({queryKey:["synchro","my-runs",config.company]})])},onError:()=>{notifications_esm_index_mjs_.notifications.show({color:"red",variant:"filled",title:"Erreur",message:"Impossible de lancer la t\xe2che.",styles:{title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}}})}})}function useSynchroJobToggleMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();const detailKey=id=>["synchro","detail",id];const listKey=["synchro","list",config.company];return(0,modern_index_js_.useMutation)({mutationFn:({id,jobId,active})=>api.put(`/synchro/${id}/jobs/${jobId}/active`,{active}),onMutate:async({id,jobId,active})=>{await queryClient.cancelQueries({queryKey:detailKey(id)});const previousDetail=queryClient.getQueryData(detailKey(id));if(previousDetail)queryClient.setQueryData(detailKey(id),{...previousDetail,jobs:previousDetail.jobs.map(job=>job.id===jobId?{...job,active}:job)});return{previousDetail}},onError:(_err,{id},context)=>{if(context?.previousDetail)queryClient.setQueryData(detailKey(id),context.previousDetail);notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible de modifier la t\xe2che."})},onSettled:(_data,_err,{id})=>{queryClient.invalidateQueries({queryKey:detailKey(id)});queryClient.invalidateQueries({queryKey:listKey})}})}function useSynchroJobDeleteMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();const detailKey=id=>["synchro","detail",id];const listKey=["synchro","list",config.company];return(0,modern_index_js_.useMutation)({mutationFn:({id,jobId})=>api.delete(`/synchro/${id}/jobs/${jobId}`),onMutate:async({id,jobId})=>{await queryClient.cancelQueries({queryKey:detailKey(id)});const previousDetail=queryClient.getQueryData(detailKey(id));if(previousDetail)queryClient.setQueryData(detailKey(id),{...previousDetail,jobs:previousDetail.jobs.filter(job=>job.id!==jobId)});return{previousDetail}},onError:(_err,{id},context)=>{if(context?.previousDetail)queryClient.setQueryData(detailKey(id),context.previousDetail);notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible de supprimer la t\xe2che."})},onSettled:(_data,_err,{id})=>{queryClient.invalidateQueries({queryKey:detailKey(id)});queryClient.invalidateQueries({queryKey:listKey})}})}function useSynchroJobDefaultsQuery(id){const api=useApiSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","job-defaults",id],queryFn:()=>api.get(`/synchro/${id}/jobs/defaults`),enabled:null!==id,staleTime:3e5})}function useSynchroJobAddMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({id,defaultId})=>api.post(`/synchro/${id}/jobs`,{defaultId}),onSuccess:(_,{id})=>{queryClient.invalidateQueries({queryKey:["synchro","detail",id]});queryClient.invalidateQueries({queryKey:["synchro","list",config.company]})},onError:()=>{notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible d'ajouter la t\xe2che."})}})}function jobStatusColor(job){const task=job.lastTask;if(!task)return"gray";if(!task.finished)return"yellow";return task.error?"red":"green"}function JobLogos({job}){if(!job.connector_from&&!job.connector_to)return null;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:3,wrap:"nowrap",style:{flexShrink:0},children:[job.connector_from&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:job.connector_from.name,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:(0,connectorLogoUrl.U)(job.connector_from),size:20,radius:"md",p:0})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:"→"}),job.connector_to&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:job.connector_to.name,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:(0,connectorLogoUrl.U)(job.connector_to),size:20,radius:"md",p:0})})]})}function SynchroFunctions({detail,onConfigJob,onShowRuns,mobile=false}){const isOverview="Total"===detail.recipe.name||"[Total]"===detail.recipe.name;const config=useAppConfigSynchro();const{cols,setCols,visibleLimit}=useTilesColumns(config.owner);const runJob=useSynchroJobRunMutation();const toggleJob=useSynchroJobToggleMutation();const deleteJob=useSynchroJobDeleteMutation();const addJob=useSynchroJobAddMutation();const jobOwnerId=job=>job.recipe_customer_id??detail.id;const[expanded,setExpanded]=(0,index_js_.useState)(false);const[openedAdd,setOpenedAdd]=(0,index_js_.useState)(false);const[chosenDefaultId,setChosenDefaultId]=(0,index_js_.useState)(null);const[selectionMode,setSelectionMode]=(0,index_js_.useState)(false);const[selectedIds,setSelectedIds]=(0,index_js_.useState)(new Set);const[bulkPending,setBulkPending]=(0,index_js_.useState)(false);const exitSelectionMode=()=>{setSelectionMode(false);setSelectedIds(new Set)};const toggleSelected=jobId=>{setSelectedIds(prev=>{const next=new Set(prev);if(next.has(jobId))next.delete(jobId);else next.add(jobId);return next})};const selectedJobs=(0,index_js_.useMemo)(()=>detail.jobs.filter(j=>selectedIds.has(j.id)),[detail.jobs,selectedIds]);const allSelectableIds=(0,index_js_.useMemo)(()=>detail.jobs.map(j=>j.id),[detail.jobs]);const allSelected=allSelectableIds.length>0&&allSelectableIds.every(id=>selectedIds.has(id));const toggleSelectAll=()=>{allSelected?setSelectedIds(new Set):setSelectedIds(new Set(allSelectableIds))};const runBulk=async(fn,eligible)=>{if(0===eligible.length)return;setBulkPending(true);try{await Promise.allSettled(eligible.map(fn))}finally{setBulkPending(false);exitSelectionMode()}};const bulkSetActive=active=>{const eligible=selectedJobs.filter(j=>j.allow_disable&&j.active!==active);if(0===eligible.length)return;runBulk(job=>toggleJob.mutateAsync({id:jobOwnerId(job),jobId:job.id,active}),eligible)};const bulkDelete=()=>{const eligible=selectedJobs.filter(j=>j.allow_delete);if(0===eligible.length)return;modals_esm_index_mjs_.modals.openConfirmModal({title:`Supprimer ${eligible.length} t\xe2che${eligible.length>1?"s":""} ?`,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"Cette action est irr\xe9versible. La configuration des t\xe2ches s\xe9lectionn\xe9es sera perdue."}),labels:{confirm:"Supprimer",cancel:"Annuler"},confirmProps:{color:"red"},onConfirm:()=>void runBulk(job=>deleteJob.mutateAsync({id:jobOwnerId(job),jobId:job.id}),eligible)})};const eligibleDisableCount=selectedJobs.filter(j=>j.allow_disable&&j.active).length;const eligibleEnableCount=selectedJobs.filter(j=>j.allow_disable&&!j.active).length;const eligibleDeleteCount=selectedJobs.filter(j=>j.allow_delete).length;const defaultsQuery=useSynchroJobDefaultsQuery(openedAdd?detail.id:null);const availableDefaults=(0,index_js_.useMemo)(()=>defaultsQuery.data??[],[defaultsQuery.data]);const handleAdd=async()=>{if(!chosenDefaultId)return;const def=availableDefaults.find(d=>String(d.id)===chosenDefaultId);if(!def)return;const{id:newJobId}=await addJob.mutateAsync({id:detail.id,defaultId:def.id});setOpenedAdd(false);setChosenDefaultId(null);onConfigJob({id:newJobId,task:def.task,task_fr:def.task_fr,order:0,settings:{},active:true,allow_delete:true,allow_disable:true})};const renderJobCol=job=>{const color=jobStatusColor(job);const isSelected=selectedIds.has(job.id);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Grid.Col,{span:1===cols?12:{base:12,sm:6},children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Card,{p:"md",withBorder:true,style:{cursor:"pointer",borderColor:selectionMode&&isSelected?"var(--mantine-color-teal-5)":void 0,backgroundColor:selectionMode&&isSelected?"var(--mantine-color-teal-0)":void 0},onClick:()=>{if(selectionMode)toggleSelected(job.id);else onConfigJob(job)},children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:8,wrap:"nowrap",style:{flex:1,minWidth:0},children:[selectionMode&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Checkbox,{checked:isSelected,onChange:()=>toggleSelected(job.id),onClick:e=>e.stopPropagation(),size:"sm"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{w:8,h:8,style:{borderRadius:"50%",background:`var(--mantine-color-${color}-6)`,flexShrink:0}}),/*#__PURE__*/(0,jsx_runtime.jsx)(JobLogos,{job:job}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{truncate:true,c:selectionMode&&isSelected?"teal.9":void 0,style:{fontSize:"1rem"},children:job.task_fr}),job.gsheet_collision&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{withArrow:true,multiline:true,w:320,label:/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",fw:600,children:"Conflit de destination Gsheet"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",children:["Onglet \xab ",job.gsheet_collision.worksheet," \xbb partag\xe9 avec :"]}),job.gsheet_collision.others.map((o,i)=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",children:["• ",o.recipe_name," — ",o.job_name_fr??"(sans nom)"]},i))]}),children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:"yellow",variant:"light",size:"sm",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconAlertTriangle,{size:12}),style:{cursor:"help",flexShrink:0},children:"Collision"})})]}),!selectionMode&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:4,wrap:"nowrap",onClick:e=>e.stopPropagation(),children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",color:"green",loading:runJob.isPending,title:"Lancer",onClick:()=>runJob.mutate({id:jobOwnerId(job),jobId:job.id}),children:"▶"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",color:"gray",title:"Configurer",onClick:e=>{e.stopPropagation();onConfigJob(job)},children:"⚙"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Menu,{shadow:"md",width:180,position:"bottom-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Menu.Target,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",color:"gray",title:"Plus d'options",onClick:e=>e.stopPropagation(),children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconDotsVertical,{size:16})})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Menu.Dropdown,{onClick:e=>e.stopPropagation(),children:[!mobile&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Menu.Item,{leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconHistory,{size:14}),onClick:()=>onShowRuns(job),children:"Voir l'historique"}),!mobile&&(job.allow_disable||job.allow_delete)&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Menu.Divider,{}),job.allow_disable&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Menu.Item,{leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCpuOff,{size:14}),onClick:()=>{if(job.active)modals_esm_index_mjs_.modals.openConfirmModal({title:"D\xe9sactiver cette t\xe2che ?",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"La t\xe2che ne sera plus ex\xe9cut\xe9e tant qu'elle reste d\xe9sactiv\xe9e."}),labels:{confirm:"D\xe9sactiver",cancel:"Annuler"},onConfirm:()=>toggleJob.mutate({id:jobOwnerId(job),jobId:job.id,active:false})});else toggleJob.mutate({id:jobOwnerId(job),jobId:job.id,active:true})},children:job.active?"D\xe9sactiver":"Activer"}),job.allow_delete&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Menu.Item,{color:"red",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTrash,{size:14}),onClick:()=>{modals_esm_index_mjs_.modals.openConfirmModal({title:"Supprimer cette t\xe2che ?",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"Cette action est irr\xe9versible. La configuration de la t\xe2che sera perdue."}),labels:{confirm:"Supprimer",cancel:"Annuler"},confirmProps:{color:"red"},onConfirm:()=>deleteJob.mutate({id:jobOwnerId(job),jobId:job.id})})},children:"Supprimer"})]})]})]})]})})},job.id)};const visibleJobs=detail.jobs.slice(0,visibleLimit);const hiddenJobs=detail.jobs.slice(visibleLimit);const hasMore=hiddenJobs.length>0;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[selectionMode&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Paper,{p:"xs",withBorder:true,style:{position:"sticky",top:0,zIndex:5,backgroundColor:"var(--mantine-color-body)"},children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:"sm",wrap:"nowrap",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Checkbox,{checked:allSelected,indeterminate:!allSelected&&selectedIds.size>0,onChange:toggleSelectAll,label:0===selectedIds.size?"S\xe9lectionner tout":`${selectedIds.size} s\xe9lectionn\xe9e${selectedIds.size>1?"s":""}`})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Button,{size:"xs",variant:"default",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCpu,{size:14}),disabled:0===eligibleEnableCount||bulkPending,loading:bulkPending,onClick:()=>bulkSetActive(true),children:["Activer",eligibleEnableCount>0?` (${eligibleEnableCount})`:""]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Button,{size:"xs",variant:"default",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCpuOff,{size:14}),disabled:0===eligibleDisableCount||bulkPending,loading:bulkPending,onClick:()=>bulkSetActive(false),children:["D\xe9sactiver",eligibleDisableCount>0?` (${eligibleDisableCount})`:""]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Button,{size:"xs",color:"red",variant:"light",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTrash,{size:14}),disabled:0===eligibleDeleteCount||bulkPending,loading:bulkPending,onClick:bulkDelete,children:["Supprimer",eligibleDeleteCount>0?` (${eligibleDeleteCount})`:""]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{size:"xs",variant:"subtle",color:"gray",onClick:exitSelectionMode,disabled:bulkPending,children:"Annuler"})]})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{justify:"flex-end",mb:"sm",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.SegmentedControl,{value:String(cols),onChange:v=>setCols("1"===v?1:2),data:[{label:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconLayoutGrid,{size:16}),value:"2"},{label:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconLayoutColumns,{size:16}),value:"1"}]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Grid,{gutter:"md",children:visibleJobs.map(renderJobCol)}),hasMore&&/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Collapse,{in:expanded,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Grid,{gutter:"md",children:hiddenJobs.map(renderJobCol)})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{justify:"center",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",size:"sm",color:"gray",rightSection:expanded?/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconChevronUp,{size:14}):/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconChevronDown,{size:14}),onClick:()=>setExpanded(v=>!v),children:expanded?"R\xe9duire":`Voir ${hiddenJobs.length} jobs suppl\xe9mentaires`})})]}),!isOverview&&detail.active&&!selectionMode&&/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Divider,{mb:"md"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"center",gap:"sm",wrap:"nowrap",grow:mobile,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"filled",color:"teal",size:"sm",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconPlaylistAdd,{size:14}),onClick:()=>setOpenedAdd(true),children:"Ajouter une fonction"}),detail.jobs.length>0&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"default",size:"sm",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCheckbox,{size:14}),onClick:()=>setSelectionMode(true),children:"S\xe9lectionner"})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:openedAdd,onClose:()=>{setOpenedAdd(false);setChosenDefaultId(null)},title:"Ajouter une fonction",size:"xl",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[defaultsQuery.isPending?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",children:"Chargement…"}):0===availableDefaults.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",children:"Aucune fonction suppl\xe9mentaire disponible."}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{data:availableDefaults.map(d=>({value:String(d.id),label:d.task_fr})),value:chosenDefaultId,onChange:setChosenDefaultId,placeholder:"Choisir une fonction",searchable:true,nothingFoundMessage:"Aucun r\xe9sultat"}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",color:"gray",onClick:()=>{setOpenedAdd(false);setChosenDefaultId(null)},children:"Annuler"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{disabled:!chosenDefaultId,loading:addJob.isPending,onClick:handleAdd,children:"Ajouter"})]})]})})]})}function formatDuration(ms){if(null===ms)return"—";if(ms<1e3)return`${ms}ms`;const secs=ms/1e3;if(secs<60)return`${secs.toFixed(1)}s`;const mins=Math.floor(secs/60);const remainSecs=Math.round(secs%60);return`${mins}mn ${remainSecs}s`}function formatDate(iso){if(!iso)return"—";return new Date(iso).toLocaleString("fr-FR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}function TaskLogos({task}){if(!task.connector_from&&!task.connector_to)return null;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:3,wrap:"nowrap",children:[task.connector_from&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:task.connector_from.name,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:(0,connectorLogoUrl.U)(task.connector_from),size:20,radius:"md",p:0})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:"→"}),task.connector_to&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:task.connector_to.name,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Avatar,{src:(0,connectorLogoUrl.U)(task.connector_to),size:20,radius:"md",p:0})})]})}function ErrorBadge({task}){const meta=task.error_meta;const errorMessage=task.error;const grafanaUrl=task.grafana_url;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.HoverCard,{width:460,shadow:"md",openDelay:150,closeDelay:150,withArrow:true,position:"bottom-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Target,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:"red",style:{cursor:"help"},children:"Erreur"})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.HoverCard.Dropdown,{children:meta?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",fw:500,children:meta.userMessage}),meta.hint?.url?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Button,{component:"a",href:meta.hint.url,target:"_blank",rel:"noopener noreferrer",variant:"light",size:"xs",children:[meta.hint.label," →"]}):meta.hint?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:meta.hint.label}):null,grafanaUrl&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Anchor,{href:grafanaUrl,target:"_blank",rel:"noopener noreferrer",size:"xs",c:"dimmed",children:"Voir les logs Grafana →"})]}):errorMessage?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:"D\xe9tails techniques"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Code,{block:true,style:{fontSize:11,maxHeight:200,overflow:"auto"},children:errorMessage}),grafanaUrl&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Anchor,{href:grafanaUrl,target:"_blank",rel:"noopener noreferrer",size:"xs",c:"dimmed",children:"Voir les logs Grafana →"})]}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:"Pas de d\xe9tails disponibles."})})]})}function SynchroHistory({tasks,destinationCodename}){const showRecipeCol=tasks.some(t=>t.connector_from||t.connector_to);const showSpreadsheetCol=void 0===destinationCodename?tasks.some(t=>t.spreadsheet):"google_sheet"===destinationCodename||"excel"===destinationCodename;if(0===tasks.length)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",children:"Aucun historique disponible."});return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{striped:true,highlightOnHover:true,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Thead,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[showRecipeCol&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Recette"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"T\xe2che"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"D\xe9marr\xe9e"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{pl:"xs",children:"Type"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Statut"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Dur\xe9e"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"#ops"}),showSpreadsheetCol&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Tableur"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Logs"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:tasks.map(task=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[showRecipeCol&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(TaskLogos,{task:task})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:task.job_name_fr}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:formatDate(task.startedAt)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ThemeIcon,{variant:"transparent",color:"gray",children:"manual"===task.trigger_source?/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconUser,{size:18,stroke:1.5}):/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconRobot,{size:18,stroke:1.5})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"manual"===task.trigger_source?task.owner:"Planifi\xe9"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:task.finished?task.error||task.error_meta?/*#__PURE__*/(0,jsx_runtime.jsx)(ErrorBadge,{task:task}):task.sheet_sync&&!task.sheet_sync.done?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Badge,{color:"blue",children:["\xc9criture Sheet… (",task.sheet_sync.step??"init",")"]}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:"green",children:"OK"}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:"yellow",children:"En cours"})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:formatDuration(task.runDuration)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:task.trace_count}),showSpreadsheetCol&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:task.spreadsheet_url?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:task.worksheet??"Ouvrir le tableur",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{component:"a",href:task.spreadsheet_url,target:"_blank",variant:"subtle",size:"sm",color:"gray",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconFileSpreadsheet,{size:18})})}):"—"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:task.grafana_url?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Voir les logs",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{component:"a",href:task.grafana_url,target:"_blank",rel:"noopener noreferrer",variant:"subtle","aria-label":"Voir les logs",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTerminal,{size:16})})}):"—"})]},task.id))})]})}function useSynchroJobConfigQuery(recipeId,jobId){const api=useApiSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","job-config",recipeId,jobId],queryFn:()=>api.get(`/synchro/${recipeId}/jobs/${jobId}/config`),enabled:null!==recipeId&&null!==jobId})}function useSynchroJobSaveMutation(){const api=useApiSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({id,jobId,data})=>api.put(`/synchro/${id}/jobs/${jobId}`,data),onSuccess:(_,{id,jobId})=>{queryClient.invalidateQueries({queryKey:["synchro","detail",id]});queryClient.invalidateQueries({queryKey:["synchro","job-config",id,jobId]});notifications_esm_index_mjs_.notifications.show({title:"Configuration sauvegard\xe9e",message:"Les param\xe8tres sont enregistr\xe9s."})},onError:()=>{notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible de sauvegarder la configuration."})}})}function useSynchroJobRenameMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({id,jobId,name})=>api.put(`/synchro/${id}/jobs/${jobId}/rename`,{name}),onSuccess:(_,{id})=>{queryClient.invalidateQueries({queryKey:["synchro","detail",id]});queryClient.invalidateQueries({queryKey:["synchro","list",config.company]});notifications_esm_index_mjs_.notifications.show({color:"green",title:"T\xe2che renomm\xe9e",message:"Le nouveau nom a bien \xe9t\xe9 enregistr\xe9."})},onError:()=>{notifications_esm_index_mjs_.notifications.show({color:"red",title:"Erreur",message:"Impossible de renommer la t\xe2che."})}})}var dist_index_js_=__webpack_require__(7115);var form_esm_index_mjs_=__webpack_require__(195);var dates_esm_index_mjs_=__webpack_require__(1525);const START_PRESETS=[{value:"today",label:"Jour courant"},{value:"month_start",label:"D\xe9but du mois"},{value:"prev_month_start",label:"D\xe9but du mois pr\xe9c\xe9dent"},{value:"year_start",label:"D\xe9but de l'ann\xe9e"}];const END_PRESETS=[{value:"today",label:"Jour courant"},{value:"month_end",label:"Fin du mois"},{value:"prev_month_end",label:"Fin du mois pr\xe9c\xe9dent"},{value:"year_end",label:"Fin de l'ann\xe9e"}];const READ_MODE_BY_SENTINEL={TODAY:"today",START_CURRENT_MONTH:"month_start",START_LAST_MONTH:"prev_month_start",START_CURRENT_YEAR:"year_start",END_CURRENT_MONTH:"month_end",END_LAST_MONTH:"prev_month_end",END_CURRENT_YEAR:"year_end"};const WRITE_SENTINEL_BY_MODE={today:"TODAY",month_start:"START_CURRENT_MONTH",prev_month_start:"START_LAST_MONTH",year_start:"START_CURRENT_YEAR",month_end:"END_CURRENT_MONTH",prev_month_end:"END_LAST_MONTH",year_end:"END_CURRENT_YEAR"};function parseValue(val){const base={exactDate:null,direction:"MINUS",amount:1,unit:"DAYS",raw:val??""};if(!val)return{...base,mode:"today"};if(READ_MODE_BY_SENTINEL[val])return{...base,mode:READ_MODE_BY_SENTINEL[val]};const legacyRel=val.match(/^(MAJOR|MINUS)_(\d+)_([A-Z]+)$/);if(legacyRel)return{...base,mode:"relative",direction:legacyRel[1],amount:Number(legacyRel[2]),unit:legacyRel[3]};const d=new Date(val);if(!isNaN(d.getTime()))return{...base,mode:"exact",exactDate:d};return{...base,mode:"passthrough"}}function serializeValue(parsed){const{mode,exactDate,direction,amount,unit,raw}=parsed;if("passthrough"===mode)return raw;if("exact"===mode){if(!exactDate)return"";const y=exactDate.getFullYear();const m=String(exactDate.getMonth()+1).padStart(2,"0");const d=String(exactDate.getDate()).padStart(2,"0");return`${y}-${m}-${d}`}if("relative"===mode)return`${direction}_${amount}_${unit}`;return WRITE_SENTINEL_BY_MODE[mode]??"TODAY"}function InputDateBoundary({label,help,required,disabled,value,onChange,variant}){const parsed=parseValue(value);const[mode,setMode]=(0,index_js_.useState)(parsed.mode);const[exactDate,setExactDate]=(0,index_js_.useState)(parsed.exactDate);const[direction,setDirection]=(0,index_js_.useState)(parsed.direction);const[amount,setAmount]=(0,index_js_.useState)(parsed.amount);const[unit,setUnit]=(0,index_js_.useState)(parsed.unit);const rawRef=(0,index_js_.useRef)(parsed.raw);const didMount=(0,index_js_.useRef)(false);(0,index_js_.useEffect)(()=>{if(!didMount.current){didMount.current=true;return}onChange(serializeValue({mode,exactDate,direction,amount,unit,raw:rawRef.current}))},[mode,exactDate,direction,amount,unit]);const presets="start"===variant?START_PRESETS:END_PRESETS;return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[label&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",fw:500,children:[label," ",required&&/*#__PURE__*/(0,jsx_runtime.jsx)("span",{style:{color:"var(--mantine-color-red-6)"},children:"*"})]}),help&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:help}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Radio.Group,{value:mode,onChange:v=>setMode(v),children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"md",wrap:"wrap",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Radio,{value:"exact",label:"Date exacte",disabled:disabled,style:{flex:"1 1 150px",minWidth:0}}),/*#__PURE__*/(0,jsx_runtime.jsx)(dates_esm_index_mjs_.DateInput,{leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCalendar,{size:16}),value:exactDate,onChange:d=>{setExactDate(d?new Date(d):null);setMode("exact")},disabled:disabled||"exact"!==mode,valueFormat:"DD-MM-YYYY",placeholder:"JJ-MM-AAAA",style:{flex:"1 1 180px",minWidth:0}})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"md",wrap:"wrap",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Radio,{value:"relative",label:"Date relative",disabled:disabled,style:{flex:"1 1 150px",minWidth:0}}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{data:[{value:"MINUS",label:"pass\xe9e"},{value:"MAJOR",label:"future"}],value:direction,onChange:v=>{setDirection(v??"MINUS");setMode("relative")},disabled:disabled||"relative"!==mode,style:{flex:"1 1 100px",minWidth:92},allowDeselect:false}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{value:amount,onChange:v=>{setAmount(Number(v));setMode("relative")},min:0,disabled:disabled||"relative"!==mode,style:{flex:"1 1 80px",minWidth:76}}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{data:[{value:"DAYS",label:"Jour(s)"},{value:"WEEKS",label:"Semaine(s)"},{value:"MONTHS",label:"Mois"},{value:"YEARS",label:"Ann\xe9e(s)"}],value:unit,onChange:v=>{setUnit(v??"DAYS");setMode("relative")},disabled:disabled||"relative"!==mode,style:{flex:"1 1 120px",minWidth:110},allowDeselect:false})]}),presets.map(p=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Radio,{value:p.value,label:p.label,disabled:disabled},p.value))]})})]})}function useSpreadsheetsQuery(){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","spreadsheets",config.company],queryFn:()=>api.get(`/synchro/spreadsheets?cid=${config.company}`)})}function normalizeValue(raw){if(null==raw)return null;if("string"==typeof raw)return raw;if(Array.isArray(raw)){const first=raw[0];if(null==first)return null;if("string"==typeof first)return first;if("object"==typeof first){const v=first.spreadsheet_id;return"string"==typeof v?v:null}return null}if("object"==typeof raw){const v=raw.spreadsheet_id;return"string"==typeof v?v:null}return null}function InputGsheetsSelector({label,help,required,disabled,value,onChange,error}){const{data:spreadsheets,isPending}=useSpreadsheetsQuery();const options=(0,index_js_.useMemo)(()=>(spreadsheets??[]).map(s=>({value:s.id,label:s.name})),[spreadsheets]);const normalized=(0,index_js_.useMemo)(()=>normalizeValue(value),[value]);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:label??"Tableur",description:help??void 0,required:required,disabled:disabled||isPending,placeholder:isPending?"Chargement...":"S\xe9lectionner un tableur",data:options,value:normalized,onChange:onChange,error:error,searchable:true,clearable:true,allowDeselect:false})}function useSynchroExcelFilesQuery(){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","excel-files",config.company],queryFn:()=>api.get(`/synchro/excel-files?cid=${config.company}`)})}function InputExcelSelector_normalizeValue(raw){if(null==raw)return null;if("string"==typeof raw)return raw;if(Array.isArray(raw)){const first=raw[0];if(null==first)return null;if("string"==typeof first)return first;if("object"==typeof first){const v=first.spreadsheet_id;return"string"==typeof v?v:null}return null}if("object"==typeof raw){const v=raw.spreadsheet_id;return"string"==typeof v?v:null}return null}function InputExcelSelector({label,help,required,disabled,value,onChange,error}){const{data:files,isPending}=useSynchroExcelFilesQuery();const options=(0,index_js_.useMemo)(()=>(files??[]).map(f=>({value:f.id,label:f.name})),[files]);const normalized=(0,index_js_.useMemo)(()=>InputExcelSelector_normalizeValue(value),[value]);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:label??"Fichier Excel",description:help??void 0,required:required,disabled:disabled||isPending,placeholder:isPending?"Chargement...":"S\xe9lectionner un fichier Excel",data:options,value:normalized,onChange:onChange,error:error,searchable:true,clearable:true,allowDeselect:false})}function dedupeSelectData(options){const seen=new Set;const out=[];for(const option of options)if(option.value){if(!seen.has(option.value)){seen.add(option.value);out.push(option)}}return out}function buildOptions(source,cfg){const mapped=source.map(row=>{const value=String(row?.[cfg.valueField]??"");const label=String(row?.[cfg.labelField??cfg.valueField]??value);const secondary=(cfg.secondaryFields??[]).map(f=>row?.[f]).filter(v=>null!=v&&""!==v).join(" \xb7 ");return{value,label,secondary}});return dedupeSelectData(mapped)}function InputAccountSelector({accountCfg,sourceValues,label,description,required,disabled,multiple,value,onChange,error}){const hasSource=Array.isArray(sourceValues)&&sourceValues.length>0;const options=(0,index_js_.useMemo)(()=>hasSource?buildOptions(sourceValues,accountCfg):[],[hasSource,sourceValues,accountCfg]);const extractValue=(0,index_js_.useCallback)(raw=>{if(null==raw)return"";if("string"==typeof raw)return raw;if(Array.isArray(raw)){const first=raw[0];if(null==first)return"";if("string"==typeof first)return first;return String(first?.[accountCfg.valueField]??"")}if("object"==typeof raw)return String(raw?.[accountCfg.valueField]??"");return String(raw)},[accountCfg.valueField]);const wrapValue=(0,index_js_.useCallback)(v=>{if(!hasSource)return[];const row=sourceValues.find(r=>String(r?.[accountCfg.valueField]??"")===v);return row?[row]:[]},[hasSource,sourceValues,accountCfg.valueField]);const renderOption=(0,index_js_.useCallback)(({option,checked})=>{const match=options.find(d=>d.value===option.value);return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"sm",wrap:"nowrap",w:"100%",children:[checked&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.CheckIcon,{size:12}),/*#__PURE__*/(0,jsx_runtime.jsxs)("div",{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:match?.label??option.value}),match?.secondary&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",opacity:.5,children:match.secondary})]})]})},[options]);const multiValue=(0,index_js_.useMemo)(()=>{if(!multiple)return[];const arr=Array.isArray(value)?value:value?[value]:[];return arr.map(v=>extractValue([v])).filter(Boolean)},[multiple,value,extractValue]);const singleValue=(0,index_js_.useMemo)(()=>{if(multiple)return null;return extractValue(value)||null},[multiple,value,extractValue]);const handleMultiChange=(0,index_js_.useCallback)(values=>{onChange(values.flatMap(v=>wrapValue(v)))},[onChange,wrapValue]);const handleSingleChange=(0,index_js_.useCallback)(v=>{onChange(v?wrapValue(v):[])},[onChange,wrapValue]);const allSelected=options.length>0&&multiValue.length===options.length;const toggleAll=(0,index_js_.useCallback)(()=>{allSelected?handleMultiChange([]):handleMultiChange(options.map(o=>o.value))},[allSelected,options,handleMultiChange]);const multiLabel=(0,index_js_.useMemo)(()=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",gap:"xs",w:"100%",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{component:"span",size:"sm",fw:500,children:[label,required&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{component:"span",c:"red",inherit:true,children:[" ","*"]})]}),options.length>0&&!disabled&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Anchor,{component:"button",type:"button",size:"xs",onClick:toggleAll,children:allSelected?"Tout d\xe9s\xe9lectionner":"Tout s\xe9lectionner"})]}),[label,required,options.length,disabled,allSelected,toggleAll]);const fallbackValue=(0,index_js_.useMemo)(()=>{if(hasSource)return"";if(null==value)return"";if("string"==typeof value)return value;if(Array.isArray(value)){const first=value[0];if(null==first)return"";if("string"==typeof first)return first;return String(first?.[accountCfg.valueField]??"")}if("object"==typeof value)return String(value?.[accountCfg.valueField]??"");return String(value)},[hasSource,value,accountCfg.valueField]);const handleFallbackChange=(0,index_js_.useCallback)(e=>onChange(e.currentTarget.value),[onChange]);if(!hasSource)return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Alert,{variant:"light",color:"gray",children:"Source non charg\xe9e — saisie manuelle de l'identifiant."}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:label,description:description,required:required,disabled:disabled,value:fallbackValue,onChange:handleFallbackChange,error:error})]});if(multiple)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.MultiSelect,{label:multiLabel,description:description,required:required,withAsterisk:false,disabled:disabled,data:options,value:multiValue,onChange:handleMultiChange,renderOption:renderOption,error:error,searchable:true});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:label,description:description,required:required,disabled:disabled,data:options,value:singleValue,onChange:handleSingleChange,renderOption:renderOption,error:error,searchable:true,allowDeselect:false})}function buildEmittedArray(rows,value,editedCode,editedCategory){return rows.map(row=>{if(row.code===editedCode)return{code:row.code,label:row.label,category:editedCategory};const existing=value?.find(v=>v.code===row.code);return{code:row.code,label:row.label,category:existing?.category??row.suggested_category??""}})}function mergeRows(rows,value){const rowCodes=new Set(rows.map(r=>r.code));const extra=(value??[]).filter(v=>!rowCodes.has(v.code)).map(v=>({code:v.code,label:v.label,suggested_category:v.category}));return[...rows,...extra]}function InputCfsCategoryMapping({label,help,required,disabled,value,onChange,error,sourceValues}){const rows=(0,index_js_.useMemo)(()=>sourceValues??[],[sourceValues]);const displayRows=(0,index_js_.useMemo)(()=>mergeRows(rows,value),[rows,value]);(0,index_js_.useEffect)(()=>{if(rows.length>0&&(!value||0===value.length)){const defaults=rows.map(row=>({code:row.code,label:row.label,category:row.suggested_category??""}));onChange(defaults)}},[]);const allCategories=(0,index_js_.useMemo)(()=>Array.from(new Set([...displayRows.map(r=>r.suggested_category??"").filter(Boolean),...(value??[]).map(v=>v.category).filter(Boolean)])).sort(),[displayRows,value]);const handleCategoryChange=(0,index_js_.useCallback)((code,newCategory)=>{onChange(buildEmittedArray(displayRows,value,code,newCategory))},[displayRows,value,onChange]);if(0===displayRows.length)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:0,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Input.Wrapper,{label:label??void 0,description:help??void 0,required:required,error:error,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",mt:"xs",children:"Aucun code — saisie indisponible."})})});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:0,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Input.Wrapper,{label:label??void 0,description:help??void 0,required:required,error:error,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{mt:"xs",withTableBorder:true,withColumnBorders: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:"Code"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Compte"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Cat\xe9gorie"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:displayRows.map(row=>{const entry=value?.find(v=>v.code===row.code);const currentCategory=entry?.category??row.suggested_category??"";return/*#__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)(index_mjs_.Text,{size:"sm",children:row.code})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:row.label})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Autocomplete,{value:currentCategory,data:allCategories,onChange:newCategory=>handleCategoryChange(row.code,newCategory),disabled:disabled,size:"xs"})})]},row.code)})})]})})})}const EMPTY_ARRAY=[];const ACCOUNT_ID_NAME_SHAPE={valueField:"account_id",labelField:"account_name",secondaryFields:["account_id"]};const ACCOUNT_SELECTOR_REGISTRY={airporting_account_selector:{valueField:"account_match",labelField:"account_name",secondaryFields:["bank_name","iban"]},alma_account_selector:ACCOUNT_ID_NAME_SHAPE,bridge_account_selector:ACCOUNT_ID_NAME_SHAPE,chargebee_account_selector:ACCOUNT_ID_NAME_SHAPE,ibanfirst_account_selector:ACCOUNT_ID_NAME_SHAPE,paypal_account_selector:ACCOUNT_ID_NAME_SHAPE,pennylane_account_selector:ACCOUNT_ID_NAME_SHAPE,profitwell_account_selector:ACCOUNT_ID_NAME_SHAPE,qonto_account_selector:ACCOUNT_ID_NAME_SHAPE,revolut_account_selector:ACCOUNT_ID_NAME_SHAPE,shopify_account_selector:ACCOUNT_ID_NAME_SHAPE,sobank_account_selector:{valueField:"Account_Name",secondaryFields:["Iban"]},konfipay_account_selector:{valueField:"Account_Name",secondaryFields:["Iban"]},quickbooks_account_selector:ACCOUNT_ID_NAME_SHAPE,stripe_account_selector:ACCOUNT_ID_NAME_SHAPE,sycomore_account_selector:ACCOUNT_ID_NAME_SHAPE,wise_account_selector:ACCOUNT_ID_NAME_SHAPE,zohobooks_account_selector:{valueField:"account_id",labelField:"account_name",secondaryFields:["currency"]},zohobooks_reporting_tag_option_selector:{valueField:"value",labelField:"label",secondaryFields:[]}};function FormField({config,value,onChange,error,connectorCodename,collisionWarning}){const label=config.label??config.name??"";const description=config.help??void 0;const required=config.required??false;const disabled=config.disabled??false;const appConfig=useAppConfigSynchro();const csvSplitValue=(0,index_js_.useMemo)(()=>{if(Array.isArray(value))return value;if("string"==typeof value&&value.length>0)return value.split(",").filter(Boolean);return[]},[value]);const wrapSingleValue=(0,index_js_.useMemo)(()=>{if(Array.isArray(value))return value;if(null!=value&&""!==value)return[String(value)];return[]},[value]);const arrayValue=(0,index_js_.useMemo)(()=>Array.isArray(value)?value:EMPTY_ARRAY,[value]);const selectOptions=(0,index_js_.useMemo)(()=>{if(!config.full||"object"!=typeof config.full)return[];const f=config.full;const source=Array.isArray(f.options)?f.options:Array.isArray(f.values)?f.values:null;if(!source)return[];const mapped=source.map(o=>"string"==typeof o?{value:o,label:o}:{value:String(o.value??o.id??o),label:String(o.label??o.name??o)});return dedupeSelectData(mapped)},[config.full]);const selectMultipleValue=(0,index_js_.useMemo)(()=>{if(csvSplitValue.length>0)return csvSplitValue;const def=config.full?.default;return Array.isArray(def)?def:EMPTY_ARRAY},[csvSplitValue,config.full]);switch(config.type){case"text":if(config.multiple)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TagsInput,{label:label,description:description,required:required,disabled:disabled,value:wrapSingleValue,onChange:onChange,error:error});return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:label,description:description,required:required,disabled:disabled,value:value??"",onChange:e=>onChange(e.currentTarget.value),error:error}),collisionWarning&&collisionWarning.length>0&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Alert,{variant:"light",color:"yellow",icon:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconAlertTriangle,{size:14}),p:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",fw:600,children:"Attention, cet onglet est d\xe9j\xe0 pris :"}),collisionWarning.map(c=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",children:["• ",c.recipe_name," — ",c.job_name_fr??"(sans nom)"]},c.job_id))]})]});case"email":if(config.multiple)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TagsInput,{label:label,description:description,required:required,disabled:disabled,value:wrapSingleValue,onChange:onChange,error:error,placeholder:"Entr\xe9e / virgule pour valider",splitChars:[",",";"," "]});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{type:"email",label:label,description:description,required:required,disabled:disabled,value:value??"",onChange:e=>onChange(e.currentTarget.value),error:error});case"password":{const hasExistingValue=null!=connectorCodename&&null!=config.name&&null!=value&&""!==value;const baseUrl=appConfig.api.replace(/\/$/,"");const authHeaders={Authorization:appConfig.token?`Bearer ${appConfig.token}`:"",From:appConfig.owner};return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.PasswordInput,{label:label,description:description,required:required&&!hasExistingValue,disabled:disabled,value:value??"",onChange:e=>onChange(e.currentTarget.value),error:error,placeholder:hasExistingValue?"Laisser vide pour conserver le mot de passe actuel":void 0,visibilityToggleButtonProps:hasExistingValue?{style:{display:"none"}}:void 0}),hasExistingValue&&/*#__PURE__*/(0,jsx_runtime.jsx)(dist_index_js_.SecretField,{label:`${label} — voir la valeur actuelle`,fetchSecret:async revealToken=>{const res=await fetch(`${baseUrl}/v1/connectors/${appConfig.company}/${connectorCodename}/auth-secrets`,{headers:{...authHeaders,"X-Reveal-Token":revealToken}});if(!res.ok){const err=Object.assign(new Error(`${res.status}`),{status:res.status});throw err}const data=await res.json();const key=config.name;return data.secrets?.[key]??""}})]})}case"hidden":return null;case"msg":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:label});case"switch":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{label:label,description:description,disabled:disabled,checked:!!value,onChange:e=>onChange(e.currentTarget.checked)});case"zoho_gla_axes_selector":case"select":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Select,{label:label,description:description,required:required,disabled:disabled,data:selectOptions,value:value??null,onChange:onChange,error:error,searchable:true,allowDeselect:false});case"date_boundary_start":return/*#__PURE__*/(0,jsx_runtime.jsx)(InputDateBoundary,{label:label,help:description,required:required,disabled:disabled,value:value,onChange:onChange,variant:"start"});case"date_boundary_end":return/*#__PURE__*/(0,jsx_runtime.jsx)(InputDateBoundary,{label:label,help:description,required:required,disabled:disabled,value:value,onChange:onChange,variant:"end"});case"tags_multiple":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TagsInput,{label:label,description:description,required:required,disabled:disabled,value:csvSplitValue,onChange:onChange,error:error});case"gsheets_account_selector":return/*#__PURE__*/(0,jsx_runtime.jsx)(InputGsheetsSelector,{label:label,help:description,required:required,disabled:disabled,value:value,onChange:onChange,error:error});case"excel_account_selector":return/*#__PURE__*/(0,jsx_runtime.jsx)(InputExcelSelector,{label:label,help:description,required:required,disabled:disabled,value:value,onChange:onChange,error:error});case"totp":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{label:label,description:description,required:required,disabled:disabled,value:value??"",onChange:e=>onChange(e.currentTarget.value),error:error,placeholder:"123456",autoComplete:"one-time-code",inputMode:"numeric"});case"hubspot_deal_property_selector":case"hubspot_line_item_property_selector":case"pennylane_gla_axes_selector":case"select_multiple":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.MultiSelect,{label:label,description:description,required:required,disabled:disabled,data:selectOptions,value:selectMultipleValue,onChange:onChange,error:error,searchable:true});case"number":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:label,description:description,required:required,disabled:disabled,value:value??"",onChange:onChange,error:error});case"checkbox":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Checkbox,{label:label,description:description,disabled:disabled,checked:!!value,onChange:e=>onChange(e.currentTarget.checked)});case"multi_select":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.MultiSelect,{label:label,description:description,required:required,disabled:disabled,data:selectOptions,value:arrayValue,onChange:onChange,error:error,searchable:true});case"recipe_cf_pipedrive":return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TagsInput,{label:label,description:description,required:required,disabled:disabled,value:csvSplitValue,onChange:onChange,error:error});case"pennylane_cfs_category_mapping":return/*#__PURE__*/(0,jsx_runtime.jsx)(InputCfsCategoryMapping,{label:label,help:description,required:required,disabled:disabled,value:value,onChange:onChange,error:error,sourceValues:config.full?.values});default:{const accountCfg=config.type?ACCOUNT_SELECTOR_REGISTRY[config.type]:void 0;if(accountCfg)return/*#__PURE__*/(0,jsx_runtime.jsx)(InputAccountSelector,{accountCfg:accountCfg,sourceValues:config.full?.values,label:label,description:description,required:required,disabled:disabled,multiple:config.multiple,value:value,onChange:onChange,error:error});return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Alert,{variant:"light",color:"yellow",title:`Type "${config.type}" non support\xe9`,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"xs",children:["Champ : ",config.name]})})}}}function SynchroDynamicForm({config,save,connectorCodename,otherJobDestinations}){if(config.isPending||!config.data)return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{height:30,mt:6,radius:"xl"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{height:12,mt:6,w:"30%",radius:"xl"})]});if(!config.data.sections?.length)return null;return/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroDynamicFormInner,{data:config.data,save:save,connectorCodename:connectorCodename,otherJobDestinations:otherJobDestinations})}const WORKSHEET_FIELD_NAMES=new Set(["Sheet_Name","sheet_name","worksheet","Worksheet_Name","worksheetName"]);const SPREADSHEET_FIELD_NAMES=["Spreadsheet_Id","sheetId","spreadsheet_id","spreadsheetId"];function findFirstString(values,keys){for(const k of keys){const v=values[k];if("string"==typeof v&&v.length>0)return v}return null}function sectionLegend(section){const raw=section.name;if(!raw)return null;const tail=raw.split(".").pop()??raw;return tail.replace(/_/g," ")}function SynchroDynamicFormInner({data,save,connectorCodename,otherJobDestinations}){const form=(0,form_esm_index_mjs_.useForm)({initialValues:data.initialData});const{sections}=data;const{setFieldValue}=form;const fieldOnChanges=(0,index_js_.useMemo)(()=>{const map={};for(const section of sections)for(const field of section.fields){const name=field.name;if(name&&!(name in map))map[name]=value=>setFieldValue(name,value)}return map},[sections,setFieldValue]);const takenWorksheets=(0,index_js_.useMemo)(()=>{const map=new Map;for(const d of otherJobDestinations??[]){const k=`${d.spreadsheet_id}\0${d.worksheet}`;const list=map.get(k);if(list)list.push(d);else map.set(k,[d])}return map},[otherJobDestinations]);const currentSpreadsheetId=findFirstString(form.values,SPREADSHEET_FIELD_NAMES);const noop=(0,index_js_.useMemo)(()=>()=>{},[]);const renderField=(fieldConfig,key)=>{const name=fieldConfig.name;let collisionWarning=null;if(name&&WORKSHEET_FIELD_NAMES.has(name)&&currentSpreadsheetId&&"string"==typeof form.values[name]&&form.values[name].length>0){const k=`${currentSpreadsheetId}\0${form.values[name]}`;const collisions=takenWorksheets.get(k);if(collisions&&collisions.length>0)collisionWarning=collisions}return/*#__PURE__*/(0,jsx_runtime.jsx)(FormField,{config:fieldConfig,value:form.values[name],onChange:fieldOnChanges[name]??noop,error:form.errors[name],connectorCodename:connectorCodename,collisionWarning:collisionWarning},key)};return/*#__PURE__*/(0,jsx_runtime.jsx)("form",{autoComplete:"off",onSubmit:form.onSubmit(values=>save.mutate(values)),children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[sections.map((section,si)=>{const legend=sectionLegend(section);const fields=section.fields.map((fieldConfig,fi)=>renderField(fieldConfig,`${si}-${fi}`));if(!legend)return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:"md",children:fields},si);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Fieldset,{legend:legend,variant:"filled",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:"md",children:fields})},si)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{justify:"flex-end",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{type:"submit",loading:save.isPending,children:"Enregistrer"})})]})})}function JobConfigModal({job,recipeId,tasks,destinationCodename,companyDestinations,opened,onClose}){const save=useSynchroJobSaveMutation();const rename=useSynchroJobRenameMutation();const configQuery=useSynchroJobConfigQuery(opened?recipeId:null,opened?job?.id??null:null);const[editingName,setEditingName]=(0,index_js_.useState)(false);const[nameDraft,setNameDraft]=(0,index_js_.useState)("");(0,index_js_.useEffect)(()=>{if(!opened){setEditingName(false);setNameDraft("")}},[opened]);(0,index_js_.useEffect)(()=>{setNameDraft(job?.task_fr??"")},[job?.task_fr]);const saveMutation=(0,index_js_.useMemo)(()=>({...save,mutate:values=>{if(!job)return;save.mutate({id:recipeId,jobId:job.id,data:values},{onSuccess:()=>onClose()})}}),[save,job,recipeId,onClose]);if(!job)return null;const hasForm=configQuery.data?.sections?.length>0;const jobTasks=(tasks??[]).filter(t=>t.job_name_fr===job.task_fr);const startEdit=()=>{setNameDraft(job.task_fr??"");setEditingName(true)};const cancelEdit=()=>{setEditingName(false);setNameDraft("")};const submitEdit=()=>{const trimmed=nameDraft.trim();if(!trimmed||trimmed===job.task_fr)return void cancelEdit();rename.mutate({id:recipeId,jobId:job.id,name:trimmed},{onSuccess:()=>setEditingName(false)})};const titleNode=editingName?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",style:{flex:1},children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.TextInput,{value:nameDraft,onChange:e=>setNameDraft(e.currentTarget.value),onKeyDown:e=>{if("Enter"===e.key)submitEdit();if("Escape"===e.key)cancelEdit()},autoFocus:true,size:"sm",style:{flex:1,minWidth:240},disabled:rename.isPending}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",color:"green",variant:"subtle",loading:rename.isPending,onClick:submitEdit,title:"Enregistrer",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCheck,{size:16})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",color:"gray",variant:"subtle",onClick:cancelEdit,disabled:rename.isPending,title:"Annuler",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconX,{size:16})})]}):/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:6,wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{fw:600,children:job.task_fr}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Renommer la t\xe2che",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",color:"gray",onClick:startEdit,children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconPencil,{size:14})})})]});return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Modal,{opened:opened,onClose:onClose,title:titleNode,size:"lg",children:[job.gsheet_collision&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Alert,{color:"yellow",icon:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconAlertTriangle,{size:16}),title:"Conflit de destination Gsheet",mb:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",children:["D'autres synchros \xe9crivent sur l'onglet \xab"," ",/*#__PURE__*/(0,jsx_runtime.jsx)("strong",{children:job.gsheet_collision.worksheet})," \xbb de ce m\xeame spreadsheet :"]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:2,mt:6,children:job.gsheet_collision.others.map((o,i)=>/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",children:["• ",o.recipe_name," — ",o.job_name_fr??"(sans nom)"]},i))}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",mt:6,children:"V\xe9rifie que ce n'est pas un \xe9crasement involontaire."})]}),configQuery.isPending||hasForm?/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroDynamicForm,{config:configQuery,save:saveMutation,connectorCodename:job.connector_from?.codename??job.connector_to?.codename,otherJobDestinations:(companyDestinations??[]).filter(d=>d.job_id!==job.id)}):/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",children:"Rien \xe0 configurer pour cette t\xe2che."}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:6,c:"dimmed",children:"Historique"}),/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroHistory,{tasks:jobTasks,destinationCodename:destinationCodename})]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{justify:"flex-end",mt:"md",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",color:"gray",onClick:onClose,children:"Fermer"})})]})}function useCreateScheduleMutation(){const api=useApiSynchro();const qc=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({recipeCustomerId,data})=>api.post(`/synchro/${recipeCustomerId}/schedules`,data),onSuccess:()=>qc.invalidateQueries({queryKey:["synchro"]})})}function useUpdateScheduleMutation(){const api=useApiSynchro();const qc=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({recipeCustomerId,scheduleId,data})=>api.put(`/synchro/${recipeCustomerId}/schedules/${scheduleId}`,data),onSuccess:()=>qc.invalidateQueries({queryKey:["synchro"]})})}function useDeleteScheduleMutation(){const api=useApiSynchro();const qc=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:({recipeCustomerId,scheduleId})=>api.delete(`/synchro/${recipeCustomerId}/schedules/${scheduleId}`),onSuccess:()=>qc.invalidateQueries({queryKey:["synchro"]})})}const DAY_LABELS={monday:"Lun",tuesday:"Mar",wednesday:"Mer",thursday:"Jeu",friday:"Ven",saturday:"Sam",sunday:"Dim"};const ALL_DAYS=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];function SynchroSchedules({schedules,jobs,recipeCustomerId}){const[opened,{open,close}]=(0,esm_index_mjs_.useDisclosure)(false);const[editing,setEditing]=(0,index_js_.useState)(null);const handleEdit=s=>{setEditing(s);open()};const handleNew=()=>{setEditing(null);open()};return/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[0===schedules.length&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",size:"sm",children:"Aucun d\xe9clencheur configur\xe9."}),schedules.map(s=>/*#__PURE__*/(0,jsx_runtime.jsx)(ScheduleCard,{schedule:s,jobs:jobs,recipeCustomerId:recipeCustomerId,onEdit:()=>handleEdit(s)},s.id)),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"light",size:"xs",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconPlus,{size:14}),onClick:handleNew,w:"fit-content",children:"Ajouter un d\xe9clencheur"})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(ScheduleModal,{opened:opened,onClose:close,schedule:editing,jobs:jobs,recipeCustomerId:recipeCustomerId})]})}function ScheduleCard({schedule,jobs,recipeCustomerId,onEdit}){const deleteMut=useDeleteScheduleMutation();const hour=String(schedule.hour??0).padStart(2,"0");const minute=String(schedule.minute??0).padStart(2,"0");const taskLabels=schedule.tasks.map(t=>{const job=jobs.find(j=>String(j.id)===t);return job?.active?job.task_fr:null}).filter(Boolean);return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Card,{withBorder:true,p:"sm",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:6,style:{flex:1},children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconClock,{size:16}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",fw:500,children:[hour,":",minute]}),schedule.frequency&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",size:"sm",children:schedule.frequency}),schedule.draft&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{variant:"light",size:"sm",color:"yellow",children:"Brouillon"})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCalendar,{size:16}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:4,children:ALL_DAYS.map(day=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{size:"xs",variant:schedule.days.includes(day)?"filled":"light",color:schedule.days.includes(day)?"teal":"gray",children:DAY_LABELS[day]},day))})]}),taskLabels.length>0&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:4,wrap:"wrap",children:taskLabels.map((label,i)=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{size:"xs",variant:"outline",children:label},i))})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",onClick:onEdit,title:"Modifier",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconPencil,{size:14})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{size:"sm",variant:"subtle",color:"red",loading:deleteMut.isPending,onClick:()=>deleteMut.mutate({recipeCustomerId,scheduleId:schedule.id}),title:"Supprimer",children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTrash,{size:14})})]})]})})}function ScheduleModal({opened,onClose,schedule,jobs,recipeCustomerId}){const createMut=useCreateScheduleMutation();const updateMut=useUpdateScheduleMutation();const[days,setDays]=(0,index_js_.useState)(ALL_DAYS);const[hour,setHour]=(0,index_js_.useState)(1);const[minute,setMinute]=(0,index_js_.useState)(0);const[selectedTasks,setSelectedTasks]=(0,index_js_.useState)([]);(0,index_js_.useEffect)(()=>{if(schedule){setDays(schedule.days);setHour(schedule.hour??1);setMinute(schedule.minute??0);setSelectedTasks(schedule.tasks)}else{setDays(ALL_DAYS);setHour(1);setMinute(0);setSelectedTasks([])}},[schedule,opened]);const toggleDay=day=>{setDays(prev=>prev.includes(day)?prev.filter(d=>d!==day):[...prev,day])};const toggleTask=task=>{setSelectedTasks(prev=>prev.includes(task)?prev.filter(t=>t!==task):[...prev,task])};const handleSave=()=>{const data={days,hour,minute,tasks:selectedTasks};if(schedule)updateMut.mutate({recipeCustomerId,scheduleId:schedule.id,data},{onSuccess:onClose});else createMut.mutate({recipeCustomerId,data},{onSuccess:onClose})};const isPending=createMut.isPending||updateMut.isPending;return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:opened,onClose:onClose,title:schedule?"Modifier le d\xe9clencheur":"Nouveau d\xe9clencheur",size:"md",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:"Heure",value:hour,onChange:v=>setHour(Number(v)),min:0,max:23,w:80}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.NumberInput,{label:"Minute",value:minute,onChange:v=>setMinute(Number(v)),min:0,max:59,w:80})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",fw:500,children:"Jours"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Group,{gap:4,children:ALL_DAYS.map(day=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{size:"lg",variant:days.includes(day)?"filled":"light",color:days.includes(day)?"teal":"gray",style:{cursor:"pointer"},onClick:()=>toggleDay(day),children:DAY_LABELS[day]},day))})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:4,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",fw:500,children:"Jobs \xe0 d\xe9clencher"}),jobs.map(job=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Checkbox,{label:job.task_fr??job.task,checked:selectedTasks.includes(String(job.id)),onChange:()=>toggleTask(String(job.id))},job.id))]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",color:"gray",onClick:onClose,children:"Annuler"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{onClick:handleSave,loading:isPending,children:schedule?"Enregistrer":"Cr\xe9er"})]})]})})}function subsKey(company){return["synchro","subscriptions",company]}function useSubscriptionToggle(active){const api=useApiSynchro();const config=useAppConfigSynchro();const qc=(0,modern_index_js_.useQueryClient)();const key=subsKey(config.company);return(0,modern_index_js_.useMutation)({mutationFn:synchroId=>active?api.post(`/synchro/${synchroId}/notifications/subscribe`):api.delete(`/synchro/${synchroId}/notifications/subscribe`),onMutate:async synchroId=>{await qc.cancelQueries({queryKey:key});const previous=qc.getQueryData(key);if(previous){const next=active?previous.subscriptions.includes(synchroId)?previous.subscriptions:[...previous.subscriptions,synchroId]:previous.subscriptions.filter(id=>id!==synchroId);qc.setQueryData(key,{...previous,subscriptions:next})}return{previous}},onError:(_err,_vars,context)=>{if(context?.previous)qc.setQueryData(key,context.previous)},onSettled:()=>{qc.invalidateQueries({queryKey:key})}})}function useSynchroSubscribeMutation(){return useSubscriptionToggle(true)}function useSynchroUnsubscribeMutation(){return useSubscriptionToggle(false)}function EnableNotificationsModal({opened,onClose,onActivate}){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:opened,onClose:onClose,title:"Activer les notifications",centered:true,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"Souhaitez-vous activer les notifications du syst\xe8me d'exploitation pour \xeatre pr\xe9venu de la fin de vos runs m\xeame si l'onglet est en arri\xe8re-plan ?"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",children:"Vous pouvez r\xe9pondre plus tard — la cloche fonctionnera quand m\xeame via les notifications dans l'app."}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"flex-end",gap:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",onClick:onClose,children:"Plus tard"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{onClick:onActivate,children:"Activer"})]})]})})}function SynchroBell({synchroId}){const subsRes=useSynchroSubscriptionsQuery();const subscribe=useSynchroSubscribeMutation();const unsubscribe=useSynchroUnsubscribeMutation();const[permissionModalOpen,setPermissionModalOpen]=(0,index_js_.useState)(false);const isSubscribed=subsRes.data?.subscriptions.includes(synchroId)??false;const loading=subscribe.isPending||unsubscribe.isPending;const performToggle=()=>{if(isSubscribed)unsubscribe.mutate(synchroId);else subscribe.mutate(synchroId)};const handleClick=()=>{if(!isSubscribed&&"undefined"!=typeof Notification&&"default"===Notification.permission)return void setPermissionModalOpen(true);performToggle()};const handleActivate=()=>{setPermissionModalOpen(false);if("undefined"!=typeof Notification)Notification.requestPermission().finally(()=>performToggle());else performToggle()};const handleSkipPermission=()=>{setPermissionModalOpen(false);performToggle()};const label=isSubscribed?"Notifications activ\xe9es — cliquer pour d\xe9sactiver":"Activer les notifications pour cette synchro";return/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:label,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{variant:isSubscribed?"filled":"outline",color:isSubscribed?"blue":"gray",onClick:handleClick,loading:loading,"aria-label":label,children:isSubscribed?/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconBell,{size:18}):/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconBellOff,{size:18})})}),/*#__PURE__*/(0,jsx_runtime.jsx)(EnableNotificationsModal,{opened:permissionModalOpen,onClose:handleSkipPermission,onActivate:handleActivate})]})}const fecImportsKey=companyId=>["fec-imports",companyId];const fecImportDetailKey=(companyId,importId)=>["fec-imports",companyId,importId];function useFecImportsQuery(enabled=true){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:fecImportsKey(config.company),queryFn:()=>api.get(`/fec-imports?cid=${config.company}`),enabled,staleTime:3e4})}function useFecImportDetailQuery(importId){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:fecImportDetailKey(config.company,importId),queryFn:()=>api.get(`/fec-imports/${importId}?cid=${config.company}`),enabled:null!==importId,staleTime:3e4})}const notificationStyles={title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}};function useFecImportUploadMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:file=>{const form=new FormData;form.append("file",file);return api.postForm(`/fec-imports?cid=${config.company}`,form)},onSuccess:result=>{notifications_esm_index_mjs_.notifications.show({color:"validated"===result.status?"green":"red",variant:"filled",title:"validated"===result.status?"FEC valid\xe9":"FEC rejet\xe9 par la validation",message:"validated"===result.status?"Le fichier peut \xeatre import\xe9 dans le GLA.":"Corrigez les erreurs avant de relancer un upload.",styles:notificationStyles});return Promise.all([queryClient.invalidateQueries({queryKey:fecImportsKey(config.company)}),queryClient.setQueryData(fecImportDetailKey(config.company,result.id),result)])},onError:error=>{notifications_esm_index_mjs_.notifications.show({color:"red",variant:"filled",title:"Upload impossible",message:error instanceof Error?error.message:"Erreur inconnue.",styles:notificationStyles})}})}function useFecImportCommitMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:importId=>api.post(`/fec-imports/${importId}/commit?cid=${config.company}`),onSuccess:result=>{notifications_esm_index_mjs_.notifications.show({color:"green",variant:"filled",title:"Import FEC appliqu\xe9",message:"Les lignes ont \xe9t\xe9 ajout\xe9es au GLA.",styles:notificationStyles});return Promise.all([queryClient.invalidateQueries({queryKey:fecImportsKey(config.company)}),queryClient.invalidateQueries({queryKey:fecImportDetailKey(config.company,result.id)})])},onError:error=>{notifications_esm_index_mjs_.notifications.show({color:"red",variant:"filled",title:"Import impossible",message:error instanceof Error?error.message:"Erreur inconnue.",styles:notificationStyles})}})}function useFecImportDeleteMutation(){const api=useApiSynchro();const config=useAppConfigSynchro();const queryClient=(0,modern_index_js_.useQueryClient)();return(0,modern_index_js_.useMutation)({mutationFn:importId=>api.delete(`/fec-imports/${importId}?cid=${config.company}`),onSuccess:result=>{notifications_esm_index_mjs_.notifications.show({color:"blue",variant:"filled",title:"Import FEC supprim\xe9",message:"Les lignes GLA li\xe9es \xe0 cet import ont \xe9t\xe9 retir\xe9es.",styles:notificationStyles});return Promise.all([queryClient.invalidateQueries({queryKey:fecImportsKey(config.company)}),queryClient.invalidateQueries({queryKey:fecImportDetailKey(config.company,result.id)})])},onError:error=>{notifications_esm_index_mjs_.notifications.show({color:"red",variant:"filled",title:"Suppression impossible",message:error instanceof Error?error.message:"Erreur inconnue.",styles:notificationStyles})}})}const numberFormatter=new Intl.NumberFormat("fr-FR",{maximumFractionDigits:2});const amountFormatter=new Intl.NumberFormat("fr-FR",{minimumFractionDigits:2,maximumFractionDigits:2});function statusLabel(status){switch(status){case"validated":return"Valid\xe9";case"failed":return"\xc0 corriger";case"committed":return"Import\xe9";case"deleted":return"Supprim\xe9"}}function FecImportsPanel_statusColor(status){switch(status){case"validated":return"green";case"failed":return"red";case"committed":return"blue";case"deleted":return"gray"}}function FecImportsPanel_formatDate(value,withTime=false){if(!value)return"-";const date=new Date(value);if(Number.isNaN(date.getTime()))return"-";return new Intl.DateTimeFormat("fr-FR",{day:"2-digit",month:"2-digit",year:"numeric",...withTime?{hour:"2-digit",minute:"2-digit"}:{}}).format(date)}function formatPeriod(row){const start=FecImportsPanel_formatDate(row.period_start);const end=FecImportsPanel_formatDate(row.period_end);if("-"===start&&"-"===end)return"-";if(start===end)return start;return`${start} → ${end}`}function formatAmount(value){if(null==value)return"-";return amountFormatter.format(value)}function firstIssue(row){const issue=row.errors[0]??row.warnings[0];return issue?.message??null}function confirmCommit(row,commit){modals_esm_index_mjs_.modals.openConfirmModal({title:"Importer ce FEC dans le GLA ?",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",children:[row.line_count," lignes seront ajout\xe9es dans le grand livre analytique."]}),labels:{confirm:"Importer",cancel:"Annuler"},confirmProps:{color:"green"},onConfirm:()=>commit.mutate(row.id)})}function confirmDelete(row,deleteImport){modals_esm_index_mjs_.modals.openConfirmModal({title:"Supprimer cet import FEC ?",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:"committed"===row.status?"Les lignes GLA li\xe9es \xe0 cet import seront supprim\xe9es.":"L'import sera marqu\xe9 comme supprim\xe9."}),labels:{confirm:"Supprimer",cancel:"Annuler"},confirmProps:{color:"red"},onConfirm:()=>deleteImport.mutate(row.id)})}function ImportActions({row,selected,onSelect,commit,deleteImport}){return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Voir l'aper\xe7u",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{"aria-label":"Voir l'aper\xe7u",variant:selected?"filled":"subtle",onClick:onSelect,children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconEye,{size:16})})}),"validated"===row.status&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Importer dans le GLA",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{"aria-label":"Importer dans le GLA",color:"green",loading:commit.isPending,onClick:()=>confirmCommit(row,commit),children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconCheck,{size:16})})}),"deleted"!==row.status&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:"Supprimer l'import",withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ActionIcon,{"aria-label":"Supprimer l'import",color:"red",variant:"subtle",loading:deleteImport.isPending,onClick:()=>confirmDelete(row,deleteImport),children:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconTrash,{size:16})})})]})}function RowsPreview({importId}){const detailQuery=useFecImportDetailQuery(importId);const detail=detailQuery.data;if(detailQuery.isPending)return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{h:28}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{h:120})]});if(!detail)return null;const topIssues=[...detail.errors,...detail.warnings].slice(0,4);return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"sm",children:[topIssues.length>0&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Alert,{color:detail.errors.length>0?"red":"yellow",children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Stack,{gap:4,children:topIssues.map(issue=>/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",children:issue.message},`${issue.code}-${issue.message}`))})}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"lg",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",c:"dimmed",children:[numberFormatter.format(detail.line_count)," lignes"]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",c:"dimmed",children:["D\xe9bit ",formatAmount(detail.total_debit)]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Text,{size:"sm",c:"dimmed",children:["Cr\xe9dit ",formatAmount(detail.total_credit)]})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ScrollArea,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{striped:true,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:"#"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Journal"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"\xc9criture"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Date"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Compte"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{ta:"right",children:"D\xe9bit"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{ta:"right",children:"Cr\xe9dit"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Contr\xf4le"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:detail.rows.map(row=>{const issue=firstIssue(row);return/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table.Tr,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:row.row_number}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:row.journal_code??"-"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:row.entry_number??"-"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:FecImportsPanel_formatDate(row.entry_date)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:row.account_number??"-"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{ta:"right",children:formatAmount(row.debit)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{ta:"right",children:formatAmount(row.credit)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:issue?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Tooltip,{label:issue,withArrow:true,children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:row.errors.length>0?"red":"yellow",variant:"light",children:row.errors.length>0?"Erreur":"Alerte"})}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:"green",variant:"light",children:"OK"})})]},row.row_number)})})]})})]})}function FecImportsPanel(){const[file,setFile]=(0,index_js_.useState)(null);const[selectedImportId,setSelectedImportId]=(0,index_js_.useState)(null);const importsQuery=useFecImportsQuery();const upload=useFecImportUploadMutation();const commit=useFecImportCommitMutation();const deleteImport=useFecImportDeleteMutation();const imports=importsQuery.data??[];const handleUpload=()=>{if(!file)return;upload.mutate(file,{onSuccess:result=>{setSelectedImportId(result.id);setFile(null)}})};return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Paper,{withBorder:true,p:"md",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"md",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconFileText,{size:18}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:5,children:"Import FEC"})]}),imports.some(row=>"failed"===row.status)&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Badge,{color:"red",variant:"light",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconAlertTriangle,{size:12}),children:"Validation requise"})]}),/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{align:"end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.FileInput,{label:"Fichier FEC",placeholder:"Choisir un fichier",value:file,onChange:setFile,leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconFileText,{size:16}),accept:".txt,.csv,.fec,text/plain,text/csv",clearable:true,style:{flex:1,minWidth:240}}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconUpload,{size:16}),loading:upload.isPending,disabled:!file,onClick:handleUpload,children:"Uploader"})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Divider,{}),importsQuery.isPending?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{h:36}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{h:80})]}):0===imports.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",children:"Aucun import FEC."}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.ScrollArea,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Table,{striped:true,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:"Statut"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Fichier"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"P\xe9riode"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{ta:"right",children:"Lignes"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Cr\xe9\xe9"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Th,{children:"Actions"})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Tbody,{children:imports.map(row=>{const issue=firstIssue(row);return/*#__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)(index_mjs_.Badge,{color:FecImportsPanel_statusColor(row.status),variant:"light",children:statusLabel(row.status)})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:2,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",fw:500,children:row.file_name}),issue&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"xs",c:"dimmed",lineClamp:1,children:issue})]})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:formatPeriod(row)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{ta:"right",children:numberFormatter.format(row.line_count)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:FecImportsPanel_formatDate(row.created_at,true)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Table.Td,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(ImportActions,{row:row,selected:selectedImportId===row.id,onSelect:()=>setSelectedImportId(current=>current===row.id?null:row.id),commit:commit,deleteImport:deleteImport})})]},row.id)})})]})}),selectedImportId&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Box,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Divider,{mb:"md"}),/*#__PURE__*/(0,jsx_runtime.jsx)(RowsPreview,{importId:selectedImportId})]})]})})}function useMyRunsQuery(){const api=useApiSynchro();const config=useAppConfigSynchro();return(0,modern_index_js_.useQuery)({queryKey:["synchro","my-runs",config.company],queryFn:()=>api.get(`/synchro/notifications/my-runs?cid=${config.company}`),staleTime:0,refetchInterval:query=>{const runs=query.state.data?.runs??[];const hasActive=runs.some(r=>r.tasks.some(t=>!t.finished));return hasActive?5e3:false},refetchIntervalInBackground:true,refetchOnWindowFocus:true})}const TTL_MS=36e5;function cleanup(){const now=Date.now();for(const key of Object.keys(localStorage)){if(!key.startsWith("notified:"))continue;const ts=Number(localStorage.getItem(key));if(!Number.isFinite(ts)||now-ts>TTL_MS)localStorage.removeItem(key)}}function alreadyNotified(key){cleanup();return null!==localStorage.getItem(key)}function markNotified(key){localStorage.setItem(key,String(Date.now()))}function synchroRunKey(recipeUuid){return`notified:synchro:${recipeUuid}`}function jobRunKey(taskId){return`notified:job:${taskId}`}function tasksAllFinished(run){return run.tasks.every(t=>t.finished)}function errorCount(run){return run.tasks.filter(t=>null!==t.error).length}function emitNotification(run,isSynchroLevel,navigateToSynchro){const errors=errorCount(run);const total=run.tasks.length;let title;let message;let color;if(isSynchroLevel){title=run.recipe_customer_name;if(0===errors){message=`Termin\xe9e — ${total} job${total>1?"s":""} OK`;color="green"}else{message=`Termin\xe9e avec ${errors} erreur${errors>1?"s":""} (${total-errors} OK)`;color="yellow"}}else{const task=run.tasks[0];title=`${run.recipe_customer_name} — ${task.job_name_fr??"Job"}`;if(null===task.error){message="Termin\xe9";color="green"}else{message=`\xc9chec : ${task.error}`;color="red"}}notifications_esm_index_mjs_.notifications.show({title,message,color,variant:"filled",autoClose:8e3,onClick:()=>navigateToSynchro(run.recipe_customer_id),style:{cursor:"pointer"},styles:{title:{color:"var(--mantine-color-white)"},description:{color:"var(--mantine-color-white)"}}});if("undefined"!=typeof Notification&&"granted"===Notification.permission)try{const osNotif=new Notification(title,{body:message,tag:run.recipe_uuid});osNotif.onclick=()=>{window.focus();navigateToSynchro(run.recipe_customer_id);osNotif.close()}}catch{}return 0===errors?"ok":"ko"}function useNotifyOnRunComplete(navigateToSynchro,onTabNotify){const myRunsRes=useMyRunsQuery();const subsRes=useSynchroSubscriptionsQuery();const qc=(0,modern_index_js_.useQueryClient)();const runs=myRunsRes.data?.runs;const subscriptionList=subsRes.data?.subscriptions;(0,index_js_.useEffect)(()=>{if(!runs||!subscriptionList)return;const subscribed=new Set(subscriptionList);for(const run of runs){if(!subscribed.has(run.recipe_customer_id))continue;const isSynchroLevel=run.tasks.length>1;if(isSynchroLevel){const dedupKey=synchroRunKey(run.recipe_uuid);if(alreadyNotified(dedupKey))continue;if(!tasksAllFinished(run))continue;const kind=emitNotification(run,true,navigateToSynchro);onTabNotify?.(kind);markNotified(dedupKey);qc.invalidateQueries({queryKey:["synchro","detail",run.recipe_customer_id]});qc.invalidateQueries({queryKey:["synchro","list"]})}else{const task=run.tasks[0];const dedupKey=jobRunKey(task.id);if(alreadyNotified(dedupKey))continue;if(!task.finished)continue;const kind=emitNotification(run,false,navigateToSynchro);onTabNotify?.(kind);markNotified(dedupKey);qc.invalidateQueries({queryKey:["synchro","detail",run.recipe_customer_id]});qc.invalidateQueries({queryKey:["synchro","list"]})}}},[runs,subscriptionList,navigateToSynchro,onTabNotify,qc])}let originalHref=null;function setFaviconBadge(color){const link=document.querySelector("link[rel~='icon']");if(!link)return;if(null===originalHref)originalHref=link.href;if(null===color){link.href=originalHref;return}const img=new Image;img.crossOrigin="anonymous";img.src=originalHref;img.onload=()=>{const canvas=document.createElement("canvas");canvas.width=32;canvas.height=32;const ctx=canvas.getContext("2d");if(!ctx)return;ctx.drawImage(img,0,0,32,32);ctx.fillStyle="green"===color?"#22c55e":"#ef4444";ctx.beginPath();ctx.arc(24,24,7,0,2*Math.PI);ctx.fill();link.href=canvas.toDataURL("image/png")};img.onerror=()=>{const canvas=document.createElement("canvas");canvas.width=32;canvas.height=32;const ctx=canvas.getContext("2d");if(!ctx)return;ctx.fillStyle="green"===color?"#22c55e":"#ef4444";ctx.beginPath();ctx.arc(16,16,12,0,2*Math.PI);ctx.fill();link.href=canvas.toDataURL("image/png")}}function useTabNotificationIndicator(){const countRef=(0,index_js_.useRef)(0);const lastColorRef=(0,index_js_.useRef)(null);const originalTitleRef=(0,index_js_.useRef)(null);(0,index_js_.useEffect)(()=>{if(null===originalTitleRef.current)originalTitleRef.current=document.title;const onVisibility=()=>{if("visible"===document.visibilityState){countRef.current=0;lastColorRef.current=null;if(originalTitleRef.current)document.title=originalTitleRef.current;setFaviconBadge(null)}};document.addEventListener("visibilitychange",onVisibility);return()=>document.removeEventListener("visibilitychange",onVisibility)},[]);return{notify(kind){if("visible"===document.visibilityState)return;countRef.current+=1;lastColorRef.current="ok"===kind?"green":"red";if(originalTitleRef.current)document.title=`(${countRef.current}) ${originalTitleRef.current}`;setFaviconBadge(lastColorRef.current)}}}const EnableNotificationsBanner_KEY=uid=>`notifications-permission-asked:${uid}`;function EnableNotificationsBanner({userId}){const[hidden,setHidden]=(0,index_js_.useState)(true);(0,index_js_.useEffect)(()=>{if("undefined"==typeof Notification)return;const asked=localStorage.getItem(EnableNotificationsBanner_KEY(userId));if(!asked&&"default"===Notification.permission)setHidden(false)},[userId]);if(hidden)return null;const enable=async()=>{const result=await Notification.requestPermission();localStorage.setItem(EnableNotificationsBanner_KEY(userId),result);setHidden(true)};const dismiss=()=>{localStorage.setItem(EnableNotificationsBanner_KEY(userId),"dismissed");setHidden(true)};return/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Alert,{icon:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconBell,{size:18}),color:"blue",mb:"md",withCloseButton:true,onClose:dismiss,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",children:[/*#__PURE__*/(0,jsx_runtime.jsx)("span",{children:"Activez les notifications pour \xeatre pr\xe9venu de la fin de vos syncros."}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{size:"xs",onClick:enable,children:"Activer"})]})})}function containsFec(value){if(!value)return false;const normalized=value.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase();return/(^|[^a-z0-9])fec([^a-z0-9]|$)/.test(normalized)}function connectorIsFec(connector){return connector?.codename==="fec"||containsFec(connector?.name)}function isFecRecipe(detail){return connectorIsFec(detail.recipe.connector_from)||connectorIsFec(detail.recipe.connector_to)||containsFec(detail.recipe.name)||containsFec(detail.recipe.description)}function SynchroApp(){const config=useAppConfigSynchro();const isMobile=(0,esm_index_mjs_.useMediaQuery)("(max-width: 48em)",false);const{notify}=useTabNotificationIndicator();const[selectedId,setSelectedIdState]=(0,index_js_.useState)(()=>{const param=new URLSearchParams(window.location.search).get("recipeId");const parsed=param?Number(param):NaN;return Number.isInteger(parsed)&&parsed>0?parsed:null});const[configJobSnapshot,setConfigJobSnapshot]=(0,index_js_.useState)(null);const[runsModalJobSnapshot,setRunsModalJobSnapshot]=(0,index_js_.useState)(null);const listRes=useSynchroListQuery();const detailRes=useSynchroDetailQuery(selectedId);const runAll=useSynchroRunMutation();const toggle=useSynchroToggleMutation();const recipes=listRes.data??[];const detail=detailRes.data;const isFecImportRecipe=detail?isFecRecipe(detail):false;const configJob=configJobSnapshot?detail?.jobs.find(j=>j.id===configJobSnapshot.id)??configJobSnapshot:null;const runsModalJob=runsModalJobSnapshot?detail?.jobs.find(j=>j.id===runsModalJobSnapshot.id)??runsModalJobSnapshot:null;const setSelectedId=(0,index_js_.useCallback)(id=>{setSelectedIdState(id);const url=new URL(window.location.href);if(null===id)url.searchParams.delete("recipeId");else url.searchParams.set("recipeId",String(id));window.history.replaceState({},"",url)},[]);useNotifyOnRunComplete(setSelectedId,notify);(0,index_js_.useEffect)(()=>{if(0===recipes.length)return;const exists=null!==selectedId&&recipes.some(r=>r.id===selectedId);if(exists)return;const hasRecipeParam=new URLSearchParams(window.location.search).has("recipeId");if(isMobile&&!hasRecipeParam){if(null!==selectedId)setSelectedId(null);return}setSelectedId(recipes[0].id)},[isMobile,recipes,selectedId,setSelectedId]);if(listRes.isPending)return/*#__PURE__*/(0,jsx_runtime.jsx)(InlineLoader.F,{label:"Chargement des synchronisations..."});const listPanel=/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:5,p:"sm",c:"dimmed",children:"Synchronisations"}),0===recipes.length?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{size:"sm",c:"dimmed",px:"sm",children:"Aucune recette configur\xe9e."}):/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroList,{recipes:recipes,selectedId:selectedId,onSelect:setSelectedId,mobile:isMobile})]});const detailPanel=null===selectedId?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",children:"S\xe9lectionnez une recette."}):detailRes.isPending?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{h:40}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{h:120}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Skeleton,{h:200})]}):detail?/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"lg",children:[/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{justify:"space-between",wrap:"nowrap",align:"flex-start",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:3,children:"Total"===detail.recipe.name||"[Total]"===detail.recipe.name?"Vue d'ensemble":detail.recipe.name}),!isMobile&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{gap:"sm",justify:"flex-end",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroBell,{synchroId:detail.id}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Switch,{checked:detail.active,label:detail.active?"Actif":"Inactif",onChange:()=>toggle.mutate({id:detail.id,active:!detail.active})}),!isFecImportRecipe&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"light",color:"green",loading:runAll.isPending,onClick:()=>runAll.mutate(detail.id),children:"▶ Lancer tout"})]})]}),!isFecImportRecipe&&!("Total"===detail.recipe.name||"[Total]"===detail.recipe.name)&&/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{gap:"xs",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:5,c:"dimmed",children:"D\xe9clencheurs"}),/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroSchedules,{schedules:detail.schedules,jobs:detail.jobs,recipeCustomerId:detail.id})]}),isFecImportRecipe&&/*#__PURE__*/(0,jsx_runtime.jsx)(FecImportsPanel,{}),!isFecImportRecipe&&/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroFunctions,{detail:detail,onConfigJob:setConfigJobSnapshot,onShowRuns:isMobile?()=>void 0:setRunsModalJobSnapshot,mobile:isMobile}),!isFecImportRecipe&&!isMobile&&/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Accordion,{defaultValue:"history",variant:"default",children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Accordion.Item,{value:"history",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Accordion.Control,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Title,{order:5,c:"dimmed",children:"Historique"})}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Accordion.Panel,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroHistory,{tasks:detail.tasks,destinationCodename:detail.recipe.connector_to?.codename??null})})]})})]}):/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Text,{c:"dimmed",children:"Impossible de charger la recette."});return/*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment,{children:[/*#__PURE__*/(0,jsx_runtime.jsx)(EnableNotificationsBanner,{userId:config.owner}),isMobile?null===selectedId?/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{h:"100%",p:"xs",children:listPanel}):/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Stack,{h:"100%",gap:"sm",p:"sm",children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Button,{variant:"subtle",color:"gray",justify:"start",leftSection:/*#__PURE__*/(0,jsx_runtime.jsx)(tabler_icons_react_mjs_.IconArrowLeft,{size:18}),onClick:()=>setSelectedId(null),children:"Toutes les synchros"}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{flex:1,style:{overflowY:"auto",minHeight:0,paddingBottom:"calc(132px + env(safe-area-inset-bottom))"},children:detailPanel})]}):/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.Group,{wrap:"nowrap",h:"100%",align:"flex-start",gap:0,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{w:220,h:"100%",style:{flexShrink:0,borderRight:"1px solid var(--mantine-color-dark-5)"},children:listPanel}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Box,{flex:1,p:"md",style:{overflowY:"auto"},children:detailPanel})]}),/*#__PURE__*/(0,jsx_runtime.jsx)(JobConfigModal,{job:configJob,recipeId:configJob?.recipe_customer_id??selectedId??0,tasks:detail?.tasks,destinationCodename:detail?.recipe.connector_to?.codename??null,companyDestinations:detail?.company_destinations,opened:null!==configJob,onClose:()=>setConfigJobSnapshot(null)}),/*#__PURE__*/(0,jsx_runtime.jsx)(index_mjs_.Modal,{opened:null!==runsModalJob,onClose:()=>setRunsModalJobSnapshot(null),title:runsModalJob?`Historique — ${runsModalJob.task_fr}`:"Historique des ex\xe9cutions",size:"xl",children:runsModalJob&&detail&&/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroHistory,{tasks:detail.tasks.filter(t=>t.job_name_fr===runsModalJob.task_fr),destinationCodename:detail.recipe.connector_to?.codename??null})})]})}var dist_esm_index_mjs_=__webpack_require__(6511);const theme=(0,index_mjs_.createTheme)((0,dist_esm_index_mjs_.assign)(dist_index_js_.theme,{components:{}}));const cssVarResolver=x=>(0,dist_esm_index_mjs_.assign)(dist_index_js_.cssVarResolver(x),{dark:{},light:{},variables:{}});function ProvidersSynchro(props){const{children,config,mantine,tanstack}=props;return/*#__PURE__*/(0,jsx_runtime.jsx)(AppConfigSynchroProvider,{value:config,children:/*#__PURE__*/(0,jsx_runtime.jsx)(modern_index_js_.QueryClientProvider,{client:tanstack?.queryClient??new modern_index_js_.QueryClient,children:/*#__PURE__*/(0,jsx_runtime.jsxs)(index_mjs_.MantineProvider,{theme:theme,cssVariablesResolver:cssVarResolver,defaultColorScheme:mantine?.defaultColorScheme,forceColorScheme:mantine?.forceColorScheme,children:[/*#__PURE__*/(0,jsx_runtime.jsx)(notifications_esm_index_mjs_.Notifications,{}),/*#__PURE__*/(0,jsx_runtime.jsx)(dist_index_js_.RevealTokenProvider,{children:children})]})})})}function Synchronisation(props){return/*#__PURE__*/(0,jsx_runtime.jsx)(index_js_.StrictMode,{children:/*#__PURE__*/(0,jsx_runtime.jsx)(ProvidersSynchro,{...props,children:/*#__PURE__*/(0,jsx_runtime.jsx)(SynchroApp,{})})})}},800:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{F:()=>InlineLoader});var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(4848);var _mantine_core__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(4763);function InlineLoader({label}){return/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Center,{flex:1,h:"100%",children:/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Stack,{align:"center",gap:"md",children:[/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Loader,{size:"md",color:"teal"}),label&&/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx)(_mantine_core__WEBPACK_IMPORTED_MODULE_1__.Text,{fz:"sm",c:"dimmed",children:label})]})})}},1034:function(__unused_webpack_module,__webpack_exports__,__webpack_require__){__webpack_require__.d(__webpack_exports__,{U:()=>connectorLogoUrl});const fec_namespaceObject=__webpack_require__.p+"static/image/fec.png";function connectorLogoUrl(connector){if("fec"===connector.codename)return fec_namespaceObject;return connector.logo_key?`https://img.logo.dev/${connector.logo_key}?token=pk_QvyqAb6uTRGJE2_sDsEb9g&retina=true`:`https://s3.eu-west-3.amazonaws.com/media.airporting/connectors/${connector.codename}.png`}}}]);