@realtek/core-theme 0.0.376 → 0.0.377

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- const e=require("./rolldown-runtime-Chgba0Kb.cjs"),t=require("./authApi-D0LZjLV6.cjs"),n=require("./adminApi-BS2Ci_Le.cjs");let r=require("react"),i=require("antd"),a=require("@ant-design/icons"),o=require("react/jsx-runtime"),s=require("dayjs");s=e.n(s,1);function c({className:e=``,variant:t=`default`,showIcon:n=!0,...r}){return(0,o.jsx)(i.Alert,{className:`app-alert app-alert--${t} ${e}`.trim(),showIcon:n,...r})}var l=new Intl.NumberFormat;function u(e){return e==null||e===``?`–`:typeof e==`number`&&Number.isFinite(e)?l.format(e):String(e)}function d({items:e=[],loading:t=!1,className:n=``,ariaLabel:r=`Summary`}){return t&&e.length===0?(0,o.jsx)(`div`,{className:`cc-stat-strip ${n}`.trim(),"aria-busy":`true`,"aria-label":r,children:[0,1,2,3].map(e=>(0,o.jsx)(`div`,{className:`cc-stat`,children:(0,o.jsx)(i.Skeleton.Button,{active:!0,size:`small`,style:{width:56}})},e))}):e.length===0?null:(0,o.jsx)(`div`,{className:`cc-stat-strip ${n}`.trim(),role:`group`,"aria-label":r,"aria-busy":t||void 0,children:e.map(e=>{let t=(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`span`,{className:`cc-stat__value`,children:u(e.value)}),(0,o.jsx)(`span`,{className:`cc-stat__label`,children:e.label})]});return typeof e.onClick==`function`?(0,o.jsx)(`button`,{type:`button`,className:`cc-stat cc-stat--button${e.active?` is-active`:``}`,onClick:e.onClick,"aria-pressed":e.active?!0:void 0,children:t},e.key):(0,o.jsx)(`div`,{className:`cc-stat`,children:t},e.key)})})}var f=`${t.y}/admin/facebook`;async function p(e,n={}){let r=t.u(),i=await fetch(`${f}${e}`,{...n,headers:{"Content-Type":`application/json`,...t.O({"X-App-Id":String(t.b)}),...r?{Authorization:`Bearer ${r}`}:{},...n.headers||{}}}),a=await i.json().catch(()=>({}));if(!i.ok||a?.status===!1){let e=Error(a?.error||a?.message||a?.reason||`HTTP ${i.status}`);throw e.status=i.status,e}return a?.data??a}var m=()=>p(`/forms`),h=()=>p(`/courses`),g=()=>p(`/course-mappings`),_=(e,t=!1)=>p(t?`/course-mappings/${encodeURIComponent(e.formId)}`:`/course-mappings`,{method:t?`PUT`:`POST`,body:JSON.stringify(e)}),ee=e=>p(`/course-mappings/${encodeURIComponent(e)}`,{method:`DELETE`}),v=`${t.y}/admin/facebook`,y=`Could not connect. Check your internet connection and try again.`,b=`You don't have permission to do this. Ask your administrator for access.`,x=`Something went wrong. Please try again.`;function S(e,t=``){return e===401?`Your session has ended. Please sign in again.`:e===403?b:e===404?`This could not be found. Refresh the page and try again.`:e===409?t||`Someone else changed this. Refresh the page and try again.`:e>=500?`The server could not finish this. Please try again in a moment.`:t||x}function C(e,t=x,{hideServerText:n=!1}={}){if(e?.plain)return e.message;let r=String(e?.message||``);if(typeof e?.status==`number`)return S(e.status,r);let i=/^HTTP (\d{3})$/.exec(r);return i?S(Number(i[1])):e instanceof TypeError||/failed to fetch|networkerror|load failed/i.test(r)?y:/forbidden|permission|not allowed/i.test(r)?b:n?t:r||t}function w(e,t){let n=Error(e===0?y:S(e,t));return n.status=e,n.plain=!0,n.serverMessage=t,n}async function T(e,n={}){let r=t.u();if(!r)throw w(401,``);let i;try{i=await fetch(`${v}${e}`,{...n,headers:{"Content-Type":`application/json`,...t.O({"X-App-Id":String(t.b)}),Authorization:`Bearer ${r}`,...n.headers||{}}})}catch{throw w(0,``)}let a=await i.json().catch(()=>({}));if(!i.ok||a.status===!1)throw w(i.status,a.error||a.message||``);return a.data??a}var E=()=>T(`/distributions`).then(e=>Array.isArray(e)?e:e.distributions||[]);async function D(){let e=[];for(let t=1;t<=1e3;t++){let n=await T(`/counsellors?page=${t}&limit=100`);if(!Array.isArray(n.counsellors))throw Error(`Could not read the list of counsellors. Please try again.`);if(e.push(...n.counsellors),t>=Number(n.totalPages||0)||!n.counsellors.length)return e}throw Error(`The list of counsellors is too long to load. Please contact support.`)}var O=({formId:e,counsellorIds:t,isActive:n,version:r},i)=>T(i?`/distribution/${encodeURIComponent(e)}`:`/distribution`,{method:i?`PUT`:`POST`,body:JSON.stringify({formId:e,counsellorIds:t,isActive:n,...r==null?{}:{version:r}})}),k=(e,{groupBy:t=``,details:n=!1}={})=>{t&&e.set(`groupBy`,t),n&&e.set(`details`,`1`)};function A({page:e=1,limit:t=20,formId:n=``,groupBy:r=``}={}){let i=new URLSearchParams({page:String(e),limit:String(t)});return n&&i.set(`formId`,n),k(i,{groupBy:r}),T(`/distribution-skips?${i}`)}function j({status:e=`unassigned`,page:t=1,limit:n=20,formId:r=``,groupBy:i=``,details:a=!1}={}){let o=new URLSearchParams({status:e,page:String(t),limit:String(n)});return r&&o.set(`formId`,r),k(o,{groupBy:i,details:a}),T(`/unassigned-leads?${o}`)}var M=e=>T(`/distribution/${encodeURIComponent(e)}`,{method:`DELETE`}),te=()=>T(`/distribution-alerts`),ne=()=>T(`/reassign/summary`).then(e=>e.counsellors||[]);function N({fromUserId:e,formId:t=``,page:n=1,limit:r=20}={}){let i=new URLSearchParams({fromUserId:e,page:String(n),limit:String(r)});return t&&i.set(`formId`,t),T(`/reassign/leads?${i}`)}var re=e=>T(`/reassign`,{method:`POST`,body:JSON.stringify(e)});function ie({page:e=1,limit:t=20,formId:n=``,leadId:r=``}={}){let i=new URLSearchParams({page:String(e),limit:String(t)});return n&&i.set(`formId`,n),r&&i.set(`leadId`,r),T(`/reassignments?${i}`)}var ae=()=>T(`/meta`);function oe({page:e=1,limit:t=20,formId:n=``,groupBy:r=``,details:i=!1}={}){let a=new URLSearchParams({page:String(e),limit:String(t)});return n&&a.set(`formId`,n),k(a,{groupBy:r,details:i}),T(`/failed-leads?${a}`)}var se=e=>T(`/failed-leads/${encodeURIComponent(e)}/retry`,{method:`POST`});function P({page:e=1,limit:t=20,formId:n=``}={}){let r=new URLSearchParams({page:String(e),limit:String(t)});return n&&r.set(`formId`,n),T(`/history?${r}`)}var F=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!=null&&n!==``&&t.set(e,String(n))});let n=t.toString();return n?`?${n}`:``},ce=e=>T(`/distribution/overview${F({date:e})}`),I=()=>T(`/distribution/settings`),le=e=>T(`/distribution/settings`,{method:`PUT`,body:JSON.stringify(e)}),ue=(e,t,n=``)=>T(`/distribution/counsellors/${encodeURIComponent(e)}/enabled`,{method:`PUT`,body:JSON.stringify({enabled:t,reason:n})}),L=e=>T(`/distribution/leaves${F({from:e})}`),R=e=>T(`/distribution/leaves`,{method:`POST`,body:JSON.stringify(e)}),z=e=>T(`/distribution/leaves/${encodeURIComponent(e)}`,{method:`DELETE`}),B=e=>T(`/distribution/queue${F(e)}`),V=e=>T(`/distribution/assignments${F(e)}`),{Text:H}=i.Typography,U=e=>e?new Date(e).toLocaleString():`—`,W=(e,t)=>`${e} ${t}${e===1?``:`s`}`,G=[{value:`on_leave`,label:`On leave`},{value:`left_company`,label:`Left the company`},{value:`workload`,label:`Workload balancing`},{value:`other`,label:`Other`}],K={no_active_counsellor:`no active counsellor`,distribution_not_configured:`no counsellors set up for the form`,distribution_disabled:`automatic turns are paused`,default_owner_inactive_or_missing:`default owner inactive`},q={not_open_or_not_assigned_to_counsellor:`no longer open or no longer with this counsellor`,changed_during_reassign:`was updated by the counsellor while moving (run again)`,update_failed:`could not be saved`};function de({canEdit:e=!0,fromId:t,toId:n,movingCount:r,reasonOk:i,minReason:a}){if(!e)return`You don't have permission to move leads.`;let o=[];return t||o.push(`choose who the leads are moving from`),r||o.push(`choose at least one lead`),n||o.push(`choose who gets the leads`),i||o.push(`write a reason of at least ${a} characters`),o.length?`To continue, ${o.join(`, `)}.`:``}function fe({id:e,rows:t=[],value:n,onChange:a,minWidth:s=260}){let c=(0,r.useMemo)(()=>t.map(e=>({value:e.formId,label:e.formName})),[t]);return(0,o.jsx)(i.Select,{id:e,showSearch:!0,optionFilterProp:`label`,allowClear:!0,style:{minWidth:s,maxWidth:`100%`},"aria-label":`Facebook form`,placeholder:`All Facebook forms`,value:n||void 0,onChange:e=>a(e||``),options:c,popupMatchSelectWidth:!1,notFoundContent:`No matching forms`})}function J({refreshKey:e=0,pollMs:t=6e4}={}){let[n,i]=(0,r.useState)({alerts:null,alertsOk:!1,failedCount:null});return(0,r.useEffect)(()=>{let e=!0,n=()=>{typeof document<`u`&&document.hidden||Promise.allSettled([te(),oe({page:1,limit:1})]).then(([t,n])=>{e&&i(e=>({alerts:t.status===`fulfilled`?t.value:e.alerts,alertsOk:t.status===`fulfilled`,failedCount:n.status===`fulfilled`?Number(n.value?.failedCount??n.value?.total??0):null}))})};n();let r=setInterval(n,t);return()=>{e=!1,clearInterval(r)}},[e,t]),n}function pe(e){let t=[...e?.formsWithoutActiveCounsellor||[],...e?.waitingForms||[]].map(e=>String(e.formId)).filter(Boolean);return[...new Set(t)]}function me({alerts:e,failedCount:t=0,onViewLeads:n,onShowForms:r}){let a=Number(e?.unassignedCount||0),s=e?.formsWithoutActiveCounsellor||[],l=Number(t||0),u=pe(e);if(!a&&!s.length&&!l)return null;let d=[];a&&d.push(`${W(a,`lead`)} waiting`),s.length&&d.push(`${W(s.length,`form`)} with no active counsellor`),l&&d.push(`${W(l,`lead`)} failed`);let f=[...new Set([...s,...e?.waitingForms||[]].map(e=>e.formName).filter(Boolean))],p=f.slice(0,2).join(`, `),m=f.length>2?` and ${f.length-2} more`:``;return(0,o.jsx)(c,{className:`fb-attention`,type:`warning`,title:d.join(` · `),description:p?`${p}${m}`:void 0,action:(0,o.jsxs)(`div`,{className:`fb-attention-actions`,children:[(a>0||l>0)&&n&&(0,o.jsx)(i.Button,{size:`small`,onClick:n,children:`View leads`}),u.length>0&&r&&(0,o.jsx)(i.Button,{size:`small`,onClick:()=>r(u),children:`Show these forms`})]})})}function he({rows:e=[],eligibleCounsellors:t=[],onChanged:n,limits:s,reasonTypes:c,canEdit:l=!0,refreshKey:u=0}){let[d,f]=(0,r.useState)([]),[p,m]=(0,r.useState)(!1),[h,g]=(0,r.useState)(``),[_,ee]=(0,r.useState)(``),[v,y]=(0,r.useState)({leads:[],total:0}),[b,x]=(0,r.useState)(!1),[S,C]=(0,r.useState)(1),[w,T]=(0,r.useState)([]),[E,D]=(0,r.useState)(!1),[O,k]=(0,r.useState)(``),[A,j]=(0,r.useState)(`on_leave`),[M,te]=(0,r.useState)(``),[ae,oe]=(0,r.useState)(!1),[se,P]=(0,r.useState)(``),[F,ce]=(0,r.useState)({reassignments:[],total:0}),[I,le]=(0,r.useState)(1),[ue,L]=(0,r.useState)(!1),R=Number(s?.minReason)||5,z=Number(s?.maxReason)||500,B=Number(s?.maxPerRun)||500,V=c?.length?c:G,W=Object.fromEntries(V.map(e=>[e.value,e.label])),K=W[A]?A:V[0]?.value,J=(0,r.useCallback)(async()=>{m(!0);try{f(await ne()),P(``)}catch(e){P(e.message)}finally{m(!1)}},[]),pe=(0,r.useCallback)(async()=>{if(!h){y({leads:[],total:0});return}x(!0);try{y(await N({fromUserId:h,formId:_,page:S,limit:20})),P(``)}catch(e){P(e.message),y({leads:[],total:0})}finally{x(!1)}},[h,_,S]),me=(0,r.useCallback)(async()=>{L(!0);try{ce(await ie({page:I,limit:10}))}catch(e){P(e.message)}finally{L(!1)}},[I]);(0,r.useEffect)(()=>{J()},[J,u]),(0,r.useEffect)(()=>{pe()},[pe,u]),(0,r.useEffect)(()=>{me()},[me,u]);let he=d.find(e=>e.userId===h),Y=Number(v.total||0),X=E?Math.min(Y,B):w.length,ge=(0,r.useMemo)(()=>t.filter(e=>e.userId!==h&&e.isActive!==!1).map(e=>({value:e.userId,label:e.name||e.email||e.userId})),[t,h]),Z=ge.find(e=>e.value===O)?.label||``,_e=M.trim().length>=R,ve=de({canEdit:l,fromId:h,toId:O,movingCount:X,reasonOk:_e,minReason:R}),ye=!ve&&!ae,be=e=>{g(e),C(1),T([]),D(!1),k(``)},xe=e=>{ee(e),C(1),T([]),D(!1)},Se=async()=>{oe(!0);try{let e=await re({fromUserId:h,toUserId:O,reasonType:K,reason:M.trim(),..._?{formId:_}:{},...E?{allOpen:!0}:{leadIds:w}}),t=e.skipped||[];if(i.message.success(`${e.moved} lead${e.moved===1?``:`s`} moved to ${e.to?.name||Z}`),t.length){let e=t.reduce((e,t)=>({...e,[t.reason]:(e[t.reason]||0)+1}),{});i.Modal.warning({title:`${t.length} lead${t.length===1?` was`:`s were`} not moved`,content:(0,o.jsx)(`ul`,{style:{paddingLeft:18},children:Object.entries(e).map(([e,t])=>(0,o.jsxs)(`li`,{children:[t,` — `,q[e]||e]},e))})})}e.auditSaved===!1&&i.message.warning(`Leads were moved, but the history row could not be saved. Each lead still has its own activity entry.`),e.remaining>0&&i.message.info(`${e.remaining} open lead${e.remaining===1?``:`s`} still with ${e.from?.name||`this counsellor`}. Run again to move them.`),T([]),D(!1),te(``),await Promise.all([J(),pe(),me()]),n&&n()}catch(e){i.message.error(e.message||`Could not reassign leads`)}finally{oe(!1)}},Ce=()=>i.Modal.confirm({title:`Move ${X} lead${X===1?``:`s`} to ${Z}?`,okText:`Reassign`,width:520,content:(0,o.jsxs)(`div`,{children:[(0,o.jsxs)(`p`,{style:{marginBottom:6},children:[`From `,(0,o.jsx)(`strong`,{children:he?.name||`selected counsellor`}),` to `,(0,o.jsx)(`strong`,{children:Z}),`.`]}),(0,o.jsxs)(`p`,{style:{marginBottom:6},children:[`Reason: `,(0,o.jsx)(`strong`,{children:W[K]}),` — `,M.trim()]}),(0,o.jsx)(H,{type:`secondary`,children:`Each lead gets an activity entry and a history row. The previous counsellor stops seeing these leads. Pending follow-up reminders are not moved.`})]}),onOk:Se}),we=[{title:`Lead`,dataIndex:`name`,render:(e,t)=>(0,o.jsxs)(`div`,{children:[(0,o.jsx)(H,{strong:!0,children:e||t.leadCode||t.facebookLeadId}),(0,o.jsx)(`div`,{children:(0,o.jsx)(H,{type:`secondary`,className:`fb-small`,children:t.leadCode||t.facebookLeadId})})]})},{title:`Facebook form`,dataIndex:`formName`,render:e=>e||`Unknown form`},{title:`Status`,dataIndex:`status`,render:e=>(0,o.jsx)(i.Tag,{children:e||`New Lead`})},{title:`Received`,dataIndex:`createdAt`,render:U}],Te=[{title:`When`,dataIndex:`reassignedAt`,render:U},{title:`Lead`,dataIndex:`leadCode`,render:(e,t)=>e||t.facebookLeadId||`—`},{title:`From → To`,render:(e,t)=>(0,o.jsxs)(`span`,{children:[t.fromName,` `,(0,o.jsx)(a.SwapOutlined,{}),` `,t.toName]})},{title:`Reason`,render:(e,t)=>(0,o.jsxs)(`div`,{children:[(0,o.jsx)(i.Tag,{children:W[t.reasonType]||`Other`}),(0,o.jsx)(`div`,{style:{fontSize:12},children:t.reason})]})},{title:`By`,dataIndex:`performedByName`}];return(0,o.jsxs)(`div`,{className:`fb-tab-body`,children:[(0,o.jsx)(H,{type:`secondary`,className:`fb-tab-intro`,children:`Automatic turns keep sending leads to a counsellor who is on leave. Move their open leads to someone else here.`}),se&&(0,o.jsx)(i.Alert,{type:`error`,showIcon:!0,title:`Could not load everything for this tab`,description:se,className:`fb-block`}),(0,o.jsxs)(`div`,{className:`fb-field-row`,children:[(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-reassign-from`,children:`From`}),(0,o.jsx)(i.Select,{id:`fb-reassign-from`,showSearch:!0,optionFilterProp:`label`,placeholder:`Choose a counsellor`,value:h||void 0,onChange:be,loading:p,notFoundContent:`No counsellor has open Facebook leads`,options:d.map(e=>({value:e.userId,label:`${e.name} — ${e.openLeads} open${e.isActive?``:` (inactive)`}`}))})]}),(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-reassign-form`,children:`Form`}),(0,o.jsx)(fe,{id:`fb-reassign-form`,rows:e,value:_,onChange:xe,minWidth:0})]})]}),h&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(`div`,{className:`fb-block`,children:[(0,o.jsxs)(i.Radio.Group,{value:E?`all`:`pick`,onChange:e=>{D(e.target.value===`all`),e.target.value===`all`&&T([])},children:[(0,o.jsx)(i.Radio.Button,{value:`pick`,children:`Choose leads`}),(0,o.jsxs)(i.Radio.Button,{value:`all`,children:[`All `,Y,` open lead`,Y===1?``:`s`]})]}),E&&Y>B&&(0,o.jsxs)(H,{type:`secondary`,className:`fb-hint-inline`,children:[`Moves `,B,` per run. Run again for the rest.`]})]}),(0,o.jsx)(i.Table,{size:`small`,rowKey:`id`,loading:b,columns:we,dataSource:v.leads,rowSelection:E?void 0:{selectedRowKeys:w,preserveSelectedRowKeys:!0,onChange:e=>T(e)},pagination:{current:S,pageSize:20,total:Y,showSizeChanger:!1,onChange:C},locale:{emptyText:`No open Facebook leads for this counsellor`},scroll:{x:640}}),(0,o.jsxs)(`div`,{className:`fb-reassign-fields`,children:[(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-reassign-to`,children:`To`}),(0,o.jsx)(i.Select,{id:`fb-reassign-to`,showSearch:!0,optionFilterProp:`label`,placeholder:`Choose an active counsellor`,value:O||void 0,onChange:k,options:ge,notFoundContent:`No other active counsellor available`})]}),(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-reassign-type`,children:`Reason type`}),(0,o.jsx)(i.Select,{id:`fb-reassign-type`,value:K,onChange:j,options:V})]}),(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-reassign-reason`,children:`Reason`}),(0,o.jsx)(i.Input.TextArea,{id:`fb-reassign-reason`,rows:2,maxLength:z,showCount:!0,value:M,onChange:e=>te(e.target.value),placeholder:`For example, on leave 3–7 Nov`,"aria-describedby":`fb-reassign-reason-hint`,status:M&&!_e?`error`:void 0}),!_e&&(0,o.jsxs)(`div`,{id:`fb-reassign-reason-hint`,className:`fb-hint`,children:[`At least `,R,` characters`]})]}),(0,o.jsxs)(`div`,{children:[(0,o.jsx)(i.Button,{type:`primary`,icon:(0,o.jsx)(a.SwapOutlined,{}),disabled:!ye,loading:ae,onClick:Ce,children:X?`Reassign ${X} lead${X===1?``:`s`}`:`Reassign`}),ve&&(0,o.jsx)(`div`,{className:`fb-hint`,role:`status`,children:ve})]})]})]}),(0,o.jsx)(i.Collapse,{ghost:!0,className:`fb-history-collapse`,items:[{key:`history`,label:`Reassignment history`,children:(0,o.jsx)(i.Table,{size:`small`,rowKey:`id`,loading:ue,columns:Te,dataSource:F.reassignments,pagination:{current:I,pageSize:10,total:Number(F.total||0),showSizeChanger:!1,onChange:le},locale:{emptyText:`No leads have been reassigned yet`},scroll:{x:720}})}]})]})}var{Text:Y}=i.Typography,X=e=>String(e?.userId||``),ge=50,Z=e=>{let t=e?new Date(e):null;return t&&!Number.isNaN(t.getTime())?t.toLocaleString():`—`},_e=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),ve={ready:{label:`Ready`,tone:`good`},needs_setup:{label:`Needs setup`,tone:`warn`},paused:{label:`Paused`,tone:`muted`},no_active:{label:`No active counsellor`,tone:`bad`},unknown_form:{label:`Unknown form`,tone:`muted`}},ye={inactive:`Inactive`,locked:`Account locked`,deleted:`Deleted`,not_counsellor:`No longer a counsellor`,unavailable:`Unavailable`,logged_out:`Not logged in`,on_leave:`On leave`,admin_disabled:`Switched off by admin`,at_cap:`At the open-lead limit`},be=e=>ye[e]||`Unavailable`,xe={meta_fetch:`Could not read the lead from Facebook`,lms_create:`Could not create the lead`,invalid_lead_fields:`The lead had unreadable details`,course_mapping:`Could not read the course for this form`,contact_lookup:`Could not check for a duplicate`,database_lookup:`Could not check for a duplicate`,distribution_lookup:`Could not find the counsellor list`,configuration_disabled:`Facebook import was switched off`,unassigned_audit:`Could not add the lead to the waiting list`,meta_forms:`Could not read the forms from Facebook`,mismatched_page_or_form:`The lead came from a different Facebook page or form`,mismatched_meta_form:`The lead came from a different Facebook page or form`},Se=e=>xe[e]||`Failed`,Ce=e=>_e(K[e])||`Waiting for setup`,we=e=>{if(!e||typeof e!=`object`)return null;let t=e.counsellorIds||e.counsellors;return Array.isArray(t)?t.map(e=>String(e?.userId??e?.legacyUserId??e)):null};function Te(e){let{area:t,action:n,before:r,after:i}=e||{},a=String(t||``).toLowerCase(),o=String(n||``).toLowerCase(),s=/delete|remove/.test(o),c=/create|add/.test(o)||!r;if(/retry/.test(o)||/failed/.test(a))return`Retried failed lead`;if(/mapping|course/.test(a)){if(s)return`Course removed`;let e=i?.courseName,t=(r?.courseId??r?.courseName)!==(i?.courseId??i?.courseName);return e&&(c||t)?`Course ${c?`set to`:`changed to`} ${e}`:typeof r?.isActive==`boolean`&&typeof i?.isActive==`boolean`&&r.isActive!==i.isActive?i.isActive?`Course turned on`:`Course turned off`:`Course changed`}if(/distribution|counsellor/.test(a)){if(s)return`Counsellors removed`;if(c)return`Counsellors set up`;if(typeof r?.isActive==`boolean`&&typeof i?.isActive==`boolean`&&r.isActive!==i.isActive)return i.isActive?`Resumed`:`Paused`;let e=we(r),t=we(i);return e&&t&&e.length===t.length&&[...e].sort().join()===[...t].sort().join()?`Order changed`:`Counsellors changed`}return`Setup changed`}function Ee({mapping:e,distribution:t,inFormsList:n=!0},r={}){let{forms:i=!0,mappings:a=!0,distributions:o=!0}=r;if(!a||!o)return null;if(i&&!n)return`unknown_form`;let s=t?.counsellors||[];return!e||!e.isActive||!t||!s.length?`needs_setup`:t.isActive===!1?`paused`:s.some(e=>e.isActive!==!1)?`ready`:`no_active`}function De(e){let t=e?.counsellors||[];if(!t.length)return``;let n=Math.max(t.findIndex(t=>X(t)===String(e.nextUserId||``)),0);return[...t.slice(n),...t.slice(0,n)].find(e=>e.isActive!==!1)?.name||``}function Oe(e,t,n){if(t===n||t<0||n<0||t>=e.length||n>=e.length)return e;let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}function ke(e,t){if(!t.length)return``;let n=(e?.counsellors||[]).map(X).filter(Boolean),r=String(e?.nextUserId||``);if(n.length===t.length&&n.every((e,n)=>e===t[n])&&t.includes(r))return r;let i=String(e?.lastAssignedUserId||``);if(!i&&n.includes(r)&&(i=n[(n.indexOf(r)-1+n.length)%n.length]),t.includes(i))return t[(t.indexOf(i)+1)%t.length];if(n.includes(i)){let e=n.indexOf(i);for(let r=1;r<=n.length;r++){let i=n[(e+r)%n.length];if(t.includes(i))return i}}return t.includes(r)?r:t[0]}async function Ae({mapping:e,distribution:t,saveMapping:n,saveDistribution:r}){let i={mappingSaved:!1,distributionSaved:!1,failedPart:``,error:null};if(e)try{await n(e.input,e.isEdit),i.mappingSaved=!0}catch(e){return{...i,failedPart:`mapping`,error:e}}if(t)try{await r(t.input,t.isEdit),i.distributionSaved=!0}catch(e){return{...i,failedPart:`distribution`,error:e}}return i}var je=e=>e.length<2?e[0]||``:`${e.slice(0,-1).join(`, `)} and ${e[e.length-1]}`;function Me(e){return e.length?e.length===1?`${e[0]} is inactive and will be skipped. Remove them or keep the place for when they return.`:`${je(e)} are inactive and will be skipped. Remove them or keep their places for when they return.`:``}function Ne({status:e}){let t=ve[e];return t?(0,o.jsxs)(i.Tag,{className:`fb-status fb-status--${t.tone}`,children:[(0,o.jsx)(`span`,{className:`fb-status-dot`,"aria-hidden":`true`}),t.label]}):(0,o.jsx)(Y,{type:`secondary`,children:`—`})}function Pe({number:e,title:t,aside:n}){return(0,o.jsxs)(`div`,{className:`fb-setup-heading`,children:[(0,o.jsxs)(`h3`,{children:[(0,o.jsx)(`span`,{className:`fb-setup-number`,"aria-hidden":`true`,children:e}),t]}),n&&(0,o.jsx)(`span`,{className:`fb-setup-aside`,children:n})]})}var Fe=(e,t)=>({base:{mapping:e||null,current:t||null},courseId:e?.courseId||void 0,mappingActive:e?.isActive??!0,orderedIds:(t?.counsellors||[]).map(X).filter(Boolean),enabled:t?.isActive!==!1});function Ie({open:e,row:t,mapping:n,current:s,courses:c=[],counsellors:l=[],limits:u,permissions:d={},section:f=`course`,onClose:p,onSaved:m,onReload:h,onAfterClose:g}){let[ee]=(0,r.useState)(()=>Fe(n,s)),[v,y]=(0,r.useState)(ee.base),[b,x]=(0,r.useState)(ee.courseId),[S,w]=(0,r.useState)(ee.mappingActive),[T,E]=(0,r.useState)(ee.orderedIds),[D,k]=(0,r.useState)(ee.enabled),[A,j]=(0,r.useState)(``),[M,te]=(0,r.useState)(!1),[ne,N]=(0,r.useState)(``),[re,ie]=(0,r.useState)(``),[ae,oe]=(0,r.useState)(null),[se,P]=(0,r.useState)(null),F=(0,r.useRef)(null),ce=(0,r.useRef)(null),I=(0,r.useRef)(null),le=(0,r.useRef)(!1),{canAdd:ue=!0,canEdit:L=!0}=d,R=v.mapping?L:ue,z=v.current?L:ue,B=!R&&!z,V=Number(u?.maxCounsellors)||ge,H=v.current?.counsellors,U=v.mapping,W=(0,r.useMemo)(()=>{let e=new Map(l.map(e=>[X(e),{...e,isActive:!0}]));return(H||[]).forEach(t=>{let n=X(t);e.has(n)||e.set(n,{...t,isActive:!1})}),e},[l,H]),G=(0,r.useCallback)(e=>W.get(e)?.name||`Unnamed counsellor`,[W]),K=(0,r.useMemo)(()=>new Set(T),[T]),q=T.map(e=>W.get(e)).filter(Boolean),de=[...l].filter(e=>!K.has(X(e))).sort((e,t)=>String(e.name).localeCompare(String(t.name))),fe=[...q,...de].filter(e=>`${e.name||``} ${e.email||``}`.toLowerCase().includes(A.trim().toLowerCase())),J=q.filter(e=>!e.isActive),pe=q.length-J.length,me=(v.current?.counsellors||[]).map(X).filter(Boolean),he=me.length!==T.length||me.some((e,t)=>e!==T[t]),Z=v.current?he||D!==(v.current.isActive!==!1):T.length>0,_e=v.mapping?String(b)!==String(v.mapping.courseId)||S!==v.mapping.isActive:!!b,ve=_e||Z,ye=ke(v.current,T),be=T.indexOf(ye),xe=(be<0?T:[...T.slice(be),...T.slice(0,be)]).find(e=>W.get(e)?.isActive)||``,Se=W.get(xe)?.name||`No one yet`,Ce=(0,r.useMemo)(()=>{let e=c.map(e=>({value:e.courseId,label:e.courseName}));return U?.courseId&&!e.some(e=>e.value===U.courseId)&&e.unshift({value:U.courseId,label:U.courseName||`Course no longer available`}),e},[c,U]),we=(e,t)=>{let n=Fe(e,t);y(n.base),x(n.courseId),w(n.mappingActive),E(n.orderedIds),k(n.enabled)},Te=(e,t)=>{E(n=>t?[...n.filter(t=>t!==e),e]:n.filter(t=>t!==e)),ie(t?`${G(e)} added to the list`:`${G(e)} removed from the list`)},Ee=(e,t)=>{let n=T.indexOf(e),r=n+(t===`up`?-1:1);n<0||r<0||r>=T.length||(I.current={id:e,direction:t},E(e=>Oe(e,n,r)),ie(`${G(e)} moved to place ${r+1} of ${T.length}`))};(0,r.useLayoutEffect)(()=>{let e=I.current;if(!e)return;I.current=null;let t=[...F.current?.querySelectorAll(`[data-move-id]`)||[]].filter(t=>t.dataset.moveId===e.id&&!t.disabled);(t.find(t=>t.dataset.moveDirection===e.direction)||t[0])?.focus()},[T]);let De=(e,t)=>{P(t),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t)},je=(e,t,n)=>{!n||!se||se===t||(e.preventDefault(),oe(t))},Ne=()=>{P(null),oe(null)},Ie=e=>{let t=se;Ne(),!(!K.has(t)||!K.has(e)||t===e)&&(E(n=>Oe(n,n.indexOf(t),n.indexOf(e))),ie(`${G(t)} moved`))},Q=()=>{if(!M){if(!ve){p();return}le.current||(le.current=!0,i.Modal.confirm({title:`Discard your changes?`,content:`Your changes to this form have not been saved.`,okText:`Discard changes`,okType:`danger`,cancelText:`Keep editing`,autoFocusButton:`cancel`,onOk:()=>{le.current=!1,p()},onCancel:()=>{le.current=!1}}))}},$=(0,o.jsxs)(`div`,{className:`fb-setup-footer`,children:[ne&&(0,o.jsx)(i.Alert,{type:`error`,showIcon:!0,title:ne,className:`fb-setup-problem`}),(0,o.jsxs)(`div`,{className:`fb-setup-footer-actions`,children:[(0,o.jsx)(i.Button,{onClick:Q,disabled:M,children:B?`Close`:`Cancel`}),!B&&(0,o.jsx)(i.Button,{type:`primary`,loading:M,disabled:!ve,onClick:async()=>{if(N(``),Z&&!T.length){N(`Choose at least one counsellor. To stop using counsellors on this form, use Remove distribution in the form menu.`);return}if(Z&&T.length>V){N(`You can choose up to ${V} counsellors. You have chosen ${T.length}.`);return}te(!0);let e=await Ae({mapping:_e?{input:{formId:t.formId,courseId:b,isActive:S},isEdit:!!v.mapping}:null,distribution:Z?{input:{formId:t.formId,counsellorIds:T,isActive:D,version:v.current?.version??0},isEdit:!!v.current}:null,saveMapping:_,saveDistribution:O});if(!e.error){te(!1),i.message.success(`Form setup saved`),m?.(),p();return}let n=e.mappingSaved?`The course was saved. `:``;if(e.failedPart===`mapping`)N(`Nothing was saved. The course could not be saved: ${C(e.error)}`);else if(e.error?.status===409)try{let e=await h();we(e?.mapping,e?.current),N(`${n}Someone else changed these counsellors while you were editing, so yours were not saved. The latest list is now showing. Check it and save again.`)}catch{N(`${n}Someone else changed these counsellors while you were editing, so yours were not saved. The latest list could not be loaded. Close this panel and open it again.`)}else e.mappingSaved&&y(e=>({...e,mapping:{...e.mapping||{},formId:t.formId,courseId:b,isActive:S,courseName:Ce.find(e=>e.value===b)?.label||e.mapping?.courseName||``}})),N(`${n}The counsellors were not saved: ${C(e.error)}`);e.mappingSaved&&m?.(),te(!1)},children:`Save`})]})]}),Le=!!(v.mapping||v.current);return(0,o.jsxs)(i.Drawer,{open:e,size:560,rootClassName:`fb-setup-drawer`,keyboard:!0,mask:{closable:!0},title:(0,o.jsxs)(`span`,{className:`fb-setup-title`,children:[Le?`Edit`:`Set up`,` form`]}),onClose:Q,footer:$,afterOpenChange:e=>{e&&f===`counsellors`&&ce.current?.scrollIntoView?.({block:`start`}),e||g?.()},children:[(0,o.jsxs)(`div`,{className:`fb-setup-form-name`,children:[(0,o.jsx)(Y,{strong:!0,children:t?.formName}),(0,o.jsxs)(Y,{type:`secondary`,className:`fb-small`,copyable:{text:t?.formId,tooltips:[`Copy Form ID`,`Copied`]},children:[`Form ID: `,t?.formId]})]}),B&&(0,o.jsx)(i.Alert,{type:`info`,showIcon:!0,title:`You can view this setup, but your role cannot change it.`,className:`fb-block`}),(0,o.jsxs)(`section`,{className:`fb-setup-section`,"aria-label":`Course`,children:[(0,o.jsx)(Pe,{number:`1`,title:`Course`}),(0,o.jsx)(i.Select,{className:`fb-setup-select`,showSearch:!0,optionFilterProp:`label`,"aria-label":`Course`,placeholder:`Choose a course`,value:b,onChange:x,options:Ce,disabled:!R||M,notFoundContent:`No matching courses`}),b?(0,o.jsxs)(`label`,{className:`fb-setup-toggle`,children:[(0,o.jsxs)(`span`,{children:[(0,o.jsx)(`span`,{className:`fb-setup-toggle-title`,children:`Use this course for new leads`}),(0,o.jsx)(`span`,{className:`fb-hint`,children:`When off, new leads still come in, but without a course.`})]}),(0,o.jsx)(i.Switch,{"aria-label":`Use this course for new leads`,checked:S,onChange:w,disabled:!R||M})]}):(0,o.jsx)(`div`,{className:`fb-hint`,children:`No course yet. You can still choose counsellors, and leads will arrive without a course until you pick one.`})]}),(0,o.jsxs)(`section`,{className:`fb-setup-section`,"aria-label":`Counsellors and order`,ref:ce,children:[(0,o.jsx)(Pe,{number:`2`,title:`Counsellors and order`,aside:`${pe} active${J.length?`, ${J.length} inactive`:``}`}),J.length>0&&(0,o.jsx)(i.Alert,{type:`warning`,showIcon:!0,className:`fb-block`,title:Me(J.map(e=>e.name||`Unnamed counsellor`)),description:z&&(0,o.jsx)(`div`,{className:`fb-inactive-actions`,children:J.map(e=>(0,o.jsxs)(i.Button,{size:`small`,disabled:M,onClick:()=>Te(X(e),!1),children:[`Remove `,e.name||`Unnamed counsellor`]},X(e)))})}),(0,o.jsx)(i.Input,{allowClear:!0,value:A,prefix:(0,o.jsx)(a.SearchOutlined,{"aria-hidden":`true`}),className:`fb-block`,placeholder:`Search counsellors`,"aria-label":`Search counsellors`,onChange:e=>j(e.target.value)}),(0,o.jsx)(`div`,{className:`fb-dist-draggable-list`,ref:F,children:fe.length===0?(0,o.jsx)(i.Empty,{description:l.length||T.length?`No matching counsellors`:`No active counsellors to choose from`}):fe.map(e=>{let t=X(e),n=e.name||`Unnamed counsellor`,r=K.has(t),s=T.indexOf(t);return(0,o.jsxs)(`div`,{"data-person-row":t,className:`fb-dist-unified-row ${r?`selected`:``} ${ae===t?`drag-over`:``}`,draggable:r&&!M&&z,onDragStart:e=>De(e,t),onDragOver:e=>je(e,t,r),onDrop:e=>{e.preventDefault(),Ie(t)},onDragEnd:Ne,children:[(0,o.jsx)(`span`,{className:`fb-dist-check`,children:(0,o.jsx)(i.Checkbox,{"aria-label":`Include ${n}`,checked:r,disabled:M||!z,onChange:e=>Te(t,e.target.checked)})}),(0,o.jsx)(`span`,{className:`fb-dist-grip ${r?``:`placeholder`}`,"aria-hidden":`true`,children:(0,o.jsx)(a.DragOutlined,{})}),(0,o.jsx)(`span`,{className:`fb-dist-rank`,"aria-hidden":!r,children:r?s+1:``}),(0,o.jsxs)(`div`,{className:`fb-dist-person-name`,children:[(0,o.jsx)(Y,{strong:r,children:n}),e.email&&(0,o.jsx)(Y,{type:`secondary`,className:`fb-small`,ellipsis:!0,children:e.email})]}),!e.isActive&&(0,o.jsxs)(i.Tag,{className:`fb-status fb-status--bad`,children:[(0,o.jsx)(`span`,{className:`fb-status-dot`,"aria-hidden":`true`}),`Inactive`]}),r&&(0,o.jsxs)(`span`,{className:`fb-dist-order-buttons`,children:[(0,o.jsx)(i.Tooltip,{title:`Move ${n} up`,children:(0,o.jsx)(i.Button,{type:`text`,icon:(0,o.jsx)(a.ArrowUpOutlined,{"aria-hidden":`true`}),"aria-label":`Move ${n} up`,"data-move-id":t,"data-move-direction":`up`,disabled:s<=0||M||!z,onClick:()=>Ee(t,`up`)})}),(0,o.jsx)(i.Tooltip,{title:`Move ${n} down`,children:(0,o.jsx)(i.Button,{type:`text`,icon:(0,o.jsx)(a.ArrowDownOutlined,{"aria-hidden":`true`}),"aria-label":`Move ${n} down`,"data-move-id":t,"data-move-direction":`down`,disabled:s>=T.length-1||M||!z,onClick:()=>Ee(t,`down`)})})]})]},t)})}),(0,o.jsx)(`div`,{className:`fb-sr-only`,"aria-live":`polite`,children:re}),(0,o.jsxs)(`div`,{className:`fb-dist-next-line`,children:[(0,o.jsx)(a.CheckCircleOutlined,{"aria-hidden":`true`}),(0,o.jsxs)(`span`,{children:[he?`Next after save`:`Next in saved order`,`: `,(0,o.jsx)(`strong`,{children:Se})]})]}),(0,o.jsx)(`div`,{className:`fb-hint`,children:`Changes apply to future leads only. Turns carry on from the last person who got a lead, and leads people already have stay with them.`})]}),(0,o.jsxs)(`section`,{className:`fb-setup-section`,"aria-label":`Automatic turns`,children:[(0,o.jsx)(Pe,{number:`3`,title:`Automatic turns`}),(0,o.jsxs)(`label`,{className:`fb-setup-toggle`,children:[(0,o.jsxs)(`span`,{children:[(0,o.jsx)(`span`,{className:`fb-setup-toggle-title`,children:`Send leads to this form automatically`}),(0,o.jsx)(`span`,{className:`fb-hint`,children:`When paused, new leads wait until you turn this back on.`})]}),(0,o.jsx)(i.Switch,{"aria-label":`Send leads to this form automatically`,checked:D,onChange:k,checkedChildren:`On`,unCheckedChildren:`Paused`,disabled:!z||M})]})]})]})}function Q(e,t){let[n,i]=(0,r.useState)(0),[a,o]=(0,r.useState)({data:null,error:``,settled:null}),s=(0,r.useMemo)(()=>({load:e,refreshKey:t,tick:n}),[e,t,n]);(0,r.useEffect)(()=>{let e=!0;return s.load().then(t=>{e&&o({data:t,error:``,settled:s})}).catch(t=>{e&&o(e=>({...e,error:C(t),settled:s}))}),()=>{e=!1}},[s]);let c=(0,r.useCallback)(()=>i(e=>e+1),[]),l=a.settled!==s;return{data:a.data,loading:l,error:l?``:a.error,reload:c}}function $({title:e,resource:t}){return t.error?(0,o.jsx)(i.Alert,{type:`error`,showIcon:!0,className:`fb-block`,title:e,description:`${t.error}${t.data?` Showing the last information we could load.`:``}`,action:(0,o.jsx)(i.Button,{size:`small`,onClick:t.reload,children:`Try again`})}):null}var Le=(e,t)=>t.formName||e.find(e=>e.formId===String(t.formId))?.formName||`Unknown form`,Re=(e,t)=>e.find(e=>e.formId===String(t))?.mapping?.courseName||``;function ze({lead:e,details:t}){let n=t?.[e.facebookLeadId];return(0,o.jsxs)(`span`,{className:`fb-lead-cell`,children:[(0,o.jsx)(`span`,{className:`fb-lead-cell__name`,children:n?.name||(n?.error?`Details unavailable`:`—`)}),(0,o.jsxs)(`span`,{className:`fb-lead-cell__id`,children:[`Lead `,e.facebookLeadId]})]})}var Be=e=>[{title:`Phone`,key:`phone`,render:(t,n)=>e?.[n.facebookLeadId]?.phone||`—`},{title:`Email`,key:`email`,render:(t,n)=>e?.[n.facebookLeadId]?.email||`—`},{title:`City`,key:`city`,render:(t,n)=>e?.[n.facebookLeadId]?.city||`—`}];function Ve({rows:e,resource:t,unit:n,describe:r,renderBody:a,emptyText:s,fallback:c}){let l=t.data?.groups;return Array.isArray(l)?l.length?(0,o.jsx)(i.Collapse,{accordion:!0,className:`fb-groups`,expandIconPlacement:`end`,items:l.map(t=>{let s=t.formName||Le(e,t),c=Re(e,t.formId);return{key:String(t.formId),label:(0,o.jsxs)(`span`,{className:`fb-group__head`,children:[(0,o.jsx)(`span`,{className:`fb-group__title`,children:s}),(0,o.jsx)(`span`,{className:`fb-group__course`,children:c?`Course: ${c}`:`No course mapped`})]}),extra:(0,o.jsxs)(`span`,{className:`fb-group__meta`,children:[r(t),(0,o.jsxs)(i.Tag,{className:`fb-group__count`,"aria-label":`${t.count} ${n}`,children:[t.count,` `,n]})]}),children:a(t)}})}):(0,o.jsx)(i.Empty,{image:i.Empty.PRESENTED_IMAGE_SIMPLE,description:t.loading?` `:s}):t.loading&&!t.data?(0,o.jsx)(i.Table,{size:`small`,loading:!0,dataSource:[],columns:[]}):c}function He({rows:e,formId:t,status:n,refreshKey:a,showForm:s}){let[c,l]=(0,r.useState)(1),u=Q((0,r.useCallback)(()=>j({status:n,page:c,limit:20,formId:t,details:!0}),[n,c,t]),a),d=u.data?.details,f=[...s?[{title:`Form`,dataIndex:`formName`,render:(t,n)=>Le(e,n)}]:[],{title:`Lead`,dataIndex:`facebookLeadId`,render:(e,t)=>(0,o.jsx)(ze,{lead:t,details:d})},...Be(d),{title:`Why it is waiting`,dataIndex:`reason`,render:Ce},{title:`Status`,dataIndex:`status`,render:e=>e===`unassigned`?`Waiting`:e===`resolved`?`Sorted`:`—`},{title:`First seen`,dataIndex:`firstSeenAt`,render:Z},...n===`unassigned`?[]:[{title:`Sorted at`,dataIndex:`resolvedAt`,render:Z}]];return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)($,{title:`Could not load waiting leads`,resource:u}),(0,o.jsx)(i.Table,{size:`small`,rowKey:e=>String(e.id||`${e.facebookLeadId}-${e.formId}`),loading:u.loading,dataSource:u.data?.leads||[],columns:f,scroll:{x:900},locale:{emptyText:u.loading||u.error?` `:`No leads are waiting.`},pagination:{current:c,pageSize:20,total:Number(u.data?.total||0),showSizeChanger:!1,hideOnSinglePage:!0,onChange:l}})]})}function Ue({rows:e,formId:t,refreshKey:n,showForm:a,canEdit:s,onChanged:c}){let[l,u]=(0,r.useState)(1),d=Q((0,r.useCallback)(()=>oe({page:l,limit:20,formId:t,details:!0}),[l,t]),n),f=d.reload,p=d.data?.details,m=t=>{i.Modal.confirm({title:`Try this lead again?`,content:(0,o.jsxs)(`span`,{children:[`We will try to bring in lead `,(0,o.jsx)(`strong`,{children:t.facebookLeadId}),` from `,(0,o.jsx)(`strong`,{children:Le(e,t)}),` again.`]}),okText:`Retry`,cancelText:`Cancel`,autoFocusButton:`cancel`,onOk:async()=>{try{await se(t.facebookLeadId),i.message.success(`This lead will be tried again`)}catch(e){i.message.error(e?.status===409?`This lead is no longer failed. The list has been updated.`:C(e))}f(),c?.()}})},h=[...a?[{title:`Form`,dataIndex:`formName`,render:(t,n)=>Le(e,n)}]:[],{title:`Lead`,dataIndex:`facebookLeadId`,render:(e,t)=>(0,o.jsx)(ze,{lead:t,details:p})},...Be(p).slice(0,2),{title:`What went wrong`,dataIndex:`reason`,render:Se},{title:`Tries`,dataIndex:`attempts`,width:72,render:e=>e??`—`},{title:`When`,dataIndex:`lastFailedAt`,render:(e,t)=>Z(e||t.firstSeenAt)},{title:``,key:`retry`,width:96,render:(e,t)=>(0,o.jsx)(i.Tooltip,{title:s?``:`You don't have permission to retry leads`,children:(0,o.jsx)(`span`,{children:(0,o.jsx)(i.Button,{size:`small`,className:`fb-inline-btn`,disabled:!s,"aria-label":`Retry lead ${t.facebookLeadId}`,onClick:()=>m(t),children:`Retry`})})})}];return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)($,{title:`Could not load failed leads`,resource:d}),(0,o.jsx)(i.Table,{size:`small`,rowKey:e=>String(e.facebookLeadId),loading:d.loading,dataSource:d.data?.leads||[],columns:h,scroll:{x:860},locale:{emptyText:d.loading||d.error?` `:`No failed leads.`},pagination:{current:l,pageSize:20,total:Number(d.data?.total||0),showSizeChanger:!1,hideOnSinglePage:!0,onChange:u}})]})}var We=(e,t)=>Object.entries(e||{}).map(([e,n])=>(0,o.jsxs)(i.Tag,{className:`fb-group__reason`,children:[t(e),n>1?` · ${n}`:``]},e));function Ge({rows:e=[],canEdit:t=!0,refreshKey:n=0,onChanged:a}){let[s,c]=(0,r.useState)(``),[l,u]=(0,r.useState)(`unassigned`),d=(0,r.useCallback)(()=>j({status:l,formId:s,groupBy:`form`}),[l,s]),f=(0,r.useCallback)(()=>oe({formId:s,groupBy:`form`}),[s]),p=Q(d,n),m=Q(f,n),h=(e,t)=>Array.isArray(e.data?.groups)?e.data.groups.reduce((e,t)=>e+Number(t.count||0),0):e.data?.[t],g=h(p,l===`unassigned`?`unassignedCount`:`total`),_=h(m,`failedCount`)??m.data?.total;return(0,o.jsxs)(`div`,{className:`fb-tab-body`,children:[(0,o.jsx)(`div`,{className:`fb-toolbar`,children:(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-attention-form`,children:`Form`}),(0,o.jsx)(fe,{id:`fb-attention-form`,rows:e,value:s,onChange:c})]})}),(0,o.jsxs)(`div`,{className:`fb-subhead`,children:[(0,o.jsxs)(`h4`,{children:[`Waiting leads`,g===void 0?``:` (${g})`]}),(0,o.jsx)(i.Select,{"aria-label":`Show waiting leads`,value:l,className:`fb-subhead-select`,onChange:u,options:[{value:`unassigned`,label:`Waiting`},{value:`resolved`,label:`Sorted`},{value:`all`,label:`All`}]})]}),(0,o.jsx)($,{title:`Could not load waiting leads`,resource:p}),(0,o.jsx)(Ve,{rows:e,resource:p,unit:l===`unassigned`?`waiting`:`leads`,emptyText:`No leads are waiting.`,describe:e=>(0,o.jsxs)(o.Fragment,{children:[We(e.reasons,Ce),e.latest?(0,o.jsxs)(`span`,{className:`fb-group__latest`,children:[`Latest `,Z(e.latest)]}):null]}),renderBody:t=>(0,o.jsx)(He,{rows:e,formId:String(t.formId),status:l,refreshKey:n}),fallback:(0,o.jsx)(He,{rows:e,formId:s,status:l,refreshKey:n,showForm:!0})}),(0,o.jsx)(`div`,{className:`fb-subhead`,children:(0,o.jsxs)(`h4`,{children:[`Failed leads`,_===void 0?``:` (${_})`]})}),(0,o.jsx)($,{title:`Could not load failed leads`,resource:m}),(0,o.jsx)(Ve,{rows:e,resource:m,unit:`failed`,emptyText:`No failed leads.`,describe:e=>(0,o.jsxs)(o.Fragment,{children:[We(e.reasons,Se),e.latest?(0,o.jsxs)(`span`,{className:`fb-group__latest`,children:[`Latest `,Z(e.latest)]}):null]}),renderBody:r=>(0,o.jsx)(Ue,{rows:e,formId:String(r.formId),refreshKey:n,canEdit:t,onChanged:a}),fallback:(0,o.jsx)(Ue,{rows:e,formId:s,refreshKey:n,canEdit:t,onChanged:a,showForm:!0})})]})}function Ke({rows:e,formId:t,refreshKey:n,showForm:a}){let[s,c]=(0,r.useState)(1),l=Q((0,r.useCallback)(()=>A({page:s,limit:20,formId:t}),[s,t]),n),u=[...a?[{title:`Form`,dataIndex:`formName`,render:(t,n)=>Le(e,n)}]:[],{title:`Lead ID`,dataIndex:`facebookLeadId`},{title:`Skipped counsellor`,dataIndex:`skippedCounsellorName`,render:e=>e||`Unknown counsellor`},{title:`Reason`,dataIndex:`reason`,render:be},{title:`Went to`,dataIndex:`assignedToName`,render:e=>e||`—`},{title:`When`,dataIndex:`skippedAt`,render:Z}];return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)($,{title:`Could not load skipped counsellors`,resource:l}),(0,o.jsx)(i.Table,{size:`small`,rowKey:e=>String(e.id||`${e.facebookLeadId}-${e.skippedCounsellorLegacyId}`),loading:l.loading,dataSource:l.data?.skips||[],columns:u,scroll:{x:860},locale:{emptyText:l.loading||l.error?` `:`No one has been skipped yet.`},pagination:{current:s,pageSize:20,total:Number(l.data?.total||0),showSizeChanger:!1,hideOnSinglePage:!0,onChange:c}})]})}function qe({rows:e=[],refreshKey:t=0}){let[n,i]=(0,r.useState)(``),a=Q((0,r.useCallback)(()=>A({formId:n,groupBy:`form`}),[n]),t);return(0,o.jsxs)(`div`,{className:`fb-tab-body`,children:[(0,o.jsx)(`div`,{className:`fb-toolbar`,children:(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-skips-form`,children:`Form`}),(0,o.jsx)(fe,{id:`fb-skips-form`,rows:e,value:n,onChange:i})]})}),(0,o.jsx)($,{title:`Could not load skipped counsellors`,resource:a}),(0,o.jsx)(Ve,{rows:e,resource:a,unit:`skips`,emptyText:`No one has been skipped yet.`,describe:e=>(0,o.jsxs)(o.Fragment,{children:[e.people?.length?(0,o.jsxs)(`span`,{className:`fb-group__people`,children:[`Skipped: `,e.people.join(`, `)]}):null,We(e.reasons,be)]}),renderBody:n=>(0,o.jsx)(Ke,{rows:e,formId:String(n.formId),refreshKey:t}),fallback:(0,o.jsx)(Ke,{rows:e,formId:n,refreshKey:t,showForm:!0})})]})}function Je({rows:e=[],refreshKey:t=0}){let[n,a]=(0,r.useState)(``),[s,c]=(0,r.useState)(1),l=Q((0,r.useCallback)(()=>P({page:s,limit:20,formId:n}),[s,n]),t),u=[{title:`When`,dataIndex:`at`,width:190,render:Z},{title:`Form`,dataIndex:`formName`,render:(t,n)=>Le(e,n)},{title:`What changed`,key:`change`,render:(e,t)=>Te(t)},{title:`By`,dataIndex:`performedByName`,render:e=>e||`—`}];return(0,o.jsxs)(`div`,{className:`fb-tab-body`,children:[(0,o.jsx)(`div`,{className:`fb-toolbar`,children:(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-history-form`,children:`Form`}),(0,o.jsx)(fe,{id:`fb-history-form`,rows:e,value:n,onChange:e=>{a(e),c(1)}})]})}),(0,o.jsx)($,{title:`Could not load history`,resource:l}),(0,o.jsx)(i.Table,{size:`small`,rowKey:e=>String(e.id||`${e.formId}-${e.at}`),loading:l.loading,dataSource:l.data?.history||[],columns:u,scroll:{x:720},locale:{emptyText:l.loading||l.error?` `:`No setup changes yet. They will appear here when someone changes a form.`},pagination:{current:s,pageSize:20,total:Number(l.data?.total||0),showSizeChanger:!1,hideOnSinglePage:!0,onChange:c}})]})}var{Title:Ye,Text:Xe}=i.Typography;function Ze({icon:e,title:t,subtitle:n,actions:r,crumbs:a=[],onHome:s}){return(0,o.jsxs)(`div`,{className:`cc-settings-header`,children:[s?(0,o.jsx)(i.Breadcrumb,{className:`cc-settings-crumbs`,items:[{title:(0,o.jsx)(`a`,{onClick:e=>{e.preventDefault(),s()},href:`?`,children:`Settings`})},...a.map(e=>({title:e})),{title:t}]}):null,(0,o.jsxs)(`div`,{className:`cc-settings-header__row`,children:[(0,o.jsxs)(`div`,{className:`cc-settings-header__who`,children:[e?(0,o.jsx)(`span`,{className:`cc-settings-icon-tile`,"aria-hidden":`true`,children:e}):null,(0,o.jsxs)(`div`,{style:{minWidth:0},children:[(0,o.jsx)(Ye,{level:3,className:`cc-settings-header__title`,children:t}),n?(0,o.jsx)(Xe,{type:`secondary`,className:`cc-settings-header__sub`,children:n}):null]})]}),r?(0,o.jsx)(i.Space,{wrap:!0,className:`cc-settings-header__actions`,children:r}):null]})]})}function Qe({items:e}){return(0,o.jsx)(`div`,{className:`cc-settings-tiles`,children:e.filter(Boolean).map(e=>(0,o.jsxs)(`div`,{className:`cc-settings-tile is-${e.tone||`pink`}`,children:[e.icon?(0,o.jsx)(`span`,{className:`cc-settings-tile__icon`,"aria-hidden":`true`,children:e.icon}):null,(0,o.jsxs)(`div`,{style:{minWidth:0},children:[(0,o.jsx)(`div`,{className:`cc-settings-tile__label`,children:e.label}),(0,o.jsx)(`div`,{className:`cc-settings-tile__value`,children:e.value??`–`}),e.sub?(0,o.jsx)(`div`,{className:`cc-settings-tile__sub`,children:e.sub}):null]})]},e.key))})}function $e({tone:e=`grey`,icon:t,children:n}){return(0,o.jsxs)(`span`,{className:`cc-settings-pill is-${e}`,children:[t,n]})}function et({name:e}){let t=String(e||``).trim().split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0].toUpperCase()).join(``)||`?`;return(0,o.jsx)(`span`,{className:`cc-settings-initials`,"aria-hidden":`true`,children:t})}function tt(e,t){let n=Number(e)||0,r=Number(t);return n<=0||!Number.isFinite(r)?0:Math.floor(n*Math.min(1,Math.max(0,r)))}function nt(e){if(e==null||e===``)return e;let t=Number(e);return Number.isFinite(t)?Math.round(t*100):e}function rt(e){if(e==null||e===``)return e;let t=Number(e);return Number.isFinite(t)?Math.round(t)/100:e}function it(e={},t={}){let n=Number(e.cap??t.openLeadCap??0)||0,r=Number(e.untouched??0)||0,i=e.refillAt??tt(n,t.refillAtRatio??.5);if(n<=0)return{text:String(r),percent:0,tone:`grey`,hint:`No limit`,cap:n,untouched:r,refillAt:i,room:null};let a=Math.min(100,Math.round(r/n*100)),o=`${r} / ${n}`;return r>=n?{text:o,percent:a,tone:`red`,hint:`Full · refills at ${i}`,cap:n,untouched:r,refillAt:i,room:0}:e.waitingForRefill?{text:o,percent:a,tone:`amber`,hint:`Waiting · refills at ${i}`,cap:n,untouched:r,refillAt:i,room:0}:{text:o,percent:a,tone:`green`,hint:`Can take ${n-r} more`,cap:n,untouched:r,refillAt:i,room:n-r}}var at={assigned:{label:`Lead assigned`,tone:`blue`},capped:{label:`Reached limit`,tone:`amber`},reset:{label:`Quota refilled (reset)`,tone:`green`}};function ot(e={}){let t=Number(e.cap)||0,n=Number(e.untouchedBefore)||0,r=t>0?` of ${t}`:``;switch(e.event){case`assigned`:return`${e.formName?`${e.formName} · `:``}untouched ${n} → ${n+1}${r}`;case`capped`:return t>0?`Holds ${n}${r} untouched · gets no new lead until ${e.refillAt??0} or fewer`:`Holds ${n} untouched`;case`reset`:return t>0?`Untouched fell to ${n}${r} · can take ${Math.max(0,t-n)} more`:`Untouched fell to ${n}`;default:return`–`}}var{Text:st,Paragraph:ct}=i.Typography,lt={eligible:{label:`Active – Eligible`,color:`green`},logged_out:{label:`Logged Out – Not Eligible`,color:`default`},waiting_for_login:{label:`Waiting for Login`,color:`blue`},on_leave:{label:`On Leave – Skipped`,color:`orange`},admin_disabled:{label:`Admin Disabled – Skipped`,color:`red`},at_cap:{label:`At open-lead limit – Skipped`,color:`gold`},inactive:{label:`Inactive user – Skipped`,color:`red`},past_day:{label:`Past day`,color:`default`}},ut={awaiting_cutoff:`Waiting for cut-off`,no_active_counsellor:`Waiting for a counsellor who is online and under the open-lead limit`,distribution_not_configured:`Form has no counsellor list`,distribution_disabled:`Form distribution is switched off`},dt=e=>e?(0,s.default)(e).format(`h:mm A`):`–`,ft=e=>e?(0,s.default)(e).format(`D MMM, h:mm A`):`–`,pt=e=>{if(!e)return`–`;let t=Math.max(0,(0,s.default)().diff((0,s.default)(e),`minute`));return t<60?`${t} min`:`${Math.floor(t/60)} h ${t%60} min`};function mt(e,t){let[n,i]=(0,r.useState)({loading:!0}),[a,o]=(0,r.useState)(0);return(0,r.useEffect)(()=>{let t=!0;return e().then(e=>t&&i({loading:!1,data:e}),e=>t&&i({loading:!1,error:C(e,`This could not be loaded.`)})),()=>{t=!1}},[a,...t]),[n,()=>{i(e=>({...e,loading:!0})),o(e=>e+1)}]}var ht=({text:e,onRetry:t})=>(0,o.jsx)(i.Alert,{type:`error`,showIcon:!0,message:e,action:(0,o.jsx)(i.Button,{size:`small`,onClick:t,children:`Try again`})});function gt({canEdit:e=!1}){let[t,n]=(0,r.useState)(null),[c,l]=mt(()=>ce(t?t.format(`YYYY-MM-DD`):``),[t]),[u,d]=(0,r.useState)(null),[f,p]=(0,r.useState)(``),m=c.data??{},h=m.summary??{},g=!t||m.day===m.today,_=Number(m.settings?.openLeadCap??0)||0,ee=h.refillAt??tt(_,m.settings?.refillAtRatio??.5),v=async(e,t)=>{p(`t${e.legacyUserId}`);try{await ue(e.legacyUserId,t,t?``:`Disabled by admin`),i.message.success(`${e.name} ${t?`will receive new leads again`:`will not receive new leads`}`),l()}catch(e){i.message.error(C(e))}finally{p(``)}},y=[{title:`Counsellor`,key:`name`,render:(e,t)=>(0,o.jsxs)(i.Space,{direction:`vertical`,size:0,children:[(0,o.jsx)(st,{strong:!0,children:t.name}),(0,o.jsx)(st,{type:`secondary`,style:{fontSize:12},children:(t.forms??[]).join(`, `)})]})},{title:`First login`,dataIndex:`firstLoginAt`,render:dt,sorter:(e,t)=>String(e.firstLoginAt??``).localeCompare(String(t.firstLoginAt??``))},{title:`Last seen / logout`,key:`seen`,render:(e,t)=>t.loggedOutAt&&(!t.lastSeenAt||t.loggedOutAt>t.lastSeenAt)?`Logged out ${dt(t.loggedOutAt)}`:dt(t.lastSeenAt)},{title:`Status`,dataIndex:`status`,render:e=>(0,o.jsx)(i.Tag,{color:lt[e]?.color,children:lt[e]?.label??e}),filters:Object.entries(lt).map(([e,t])=>({value:e,text:t.label})),onFilter:(e,t)=>t.status===e},{title:`Untouched now`,dataIndex:`untouched`,sorter:(e,t)=>(e.untouched??0)-(t.untouched??0),render:(e,t)=>{let n=it(t,m.settings);return(0,o.jsx)(i.Tooltip,{title:`Untouched leads this counsellor holds / the most one counsellor may hold`,children:(0,o.jsxs)(`div`,{className:`ld-quota`,children:[(0,o.jsx)(`span`,{className:`ld-quota__text is-${n.tone}`,children:n.text}),n.cap>0?(0,o.jsx)(i.Progress,{percent:n.percent,size:`small`,showInfo:!1,strokeColor:`var(--ld-tone-${n.tone})`}):null,(0,o.jsx)(`span`,{className:`ld-quota__hint`,children:n.hint})]})})}},{title:`Assigned today`,dataIndex:`assigned`,align:`right`,sorter:(e,t)=>e.assigned-t.assigned,render:e=>(0,o.jsx)(`span`,{className:`ld-num`,children:e??0})},{title:`Resets today`,dataIndex:`resetsToday`,align:`right`,sorter:(e,t)=>(e.resetsToday??0)-(t.resetsToday??0),render:e=>e?(0,o.jsx)($e,{tone:`green`,icon:(0,o.jsx)(a.SyncOutlined,{}),children:e}):(0,o.jsx)(`span`,{className:`ld-muted`,children:`0`})},{title:`Total since start`,dataIndex:`totalAssignedSinceStart`,align:`right`,sorter:(e,t)=>(e.totalAssignedSinceStart??0)-(t.totalAssignedSinceStart??0),render:e=>e==null?`–`:(0,o.jsx)(`span`,{className:`ld-num`,children:e})},{title:`Target`,dataIndex:`target`,align:`right`},{title:`Progress`,key:`progress`,width:140,render:(e,t)=>(0,o.jsx)(i.Progress,{percent:t.target?Math.min(100,Math.round(t.assigned/t.target*100)):0,size:`small`,showInfo:!1})},{title:`Difference`,dataIndex:`difference`,align:`right`,render:(e,t)=>t.status===`eligible`&&e>0?(0,o.jsxs)(st,{type:`warning`,children:[e,` behind`]}):t.status===`eligible`?`On target`:`–`},...e&&g?[{title:``,key:`act`,width:210,render:(e,t)=>t.status===`inactive`?null:(0,o.jsxs)(i.Space,{children:[t.status===`admin_disabled`?(0,o.jsx)(i.Button,{size:`small`,loading:f===`t${t.legacyUserId}`,onClick:()=>v(t,!0),children:`Enable`}):(0,o.jsx)(i.Popconfirm,{title:`Stop new leads for ${t.name}?`,description:`Leads they already have stay with them.`,okText:`Disable`,okButtonProps:{danger:!0},onConfirm:()=>v(t,!1),children:(0,o.jsx)(i.Button,{size:`small`,danger:!0,loading:f===`t${t.legacyUserId}`,children:`Disable`})}),(0,o.jsx)(i.Button,{size:`small`,onClick:()=>d(t),children:`Leave`})]})}]:[]];return(0,o.jsxs)(`div`,{className:`ld-today ld-panel`,children:[(0,o.jsxs)(i.Space,{wrap:!0,style:{marginBottom:12,width:`100%`,justifyContent:`space-between`},children:[(0,o.jsxs)(i.Space,{wrap:!0,children:[(0,o.jsx)(i.DatePicker,{value:t,onChange:n,allowClear:!0,placeholder:`Today`,disabledDate:e=>e&&e.isAfter((0,s.default)(),`day`)}),m.settings?(0,o.jsx)(i.Tag,{color:m.settings.mode===`equal_daily`?`magenta`:`default`,children:m.settings.mode===`equal_daily`?`Equal daily distribution`:`Round-robin (earlier behaviour)`}):null]}),(0,o.jsx)(i.Button,{icon:(0,o.jsx)(a.ReloadOutlined,{}),onClick:l,children:`Refresh`})]}),c.loading&&!c.data?(0,o.jsx)(i.Skeleton,{active:!0}):c.error?(0,o.jsx)(ht,{text:c.error,onRetry:l}):(0,o.jsxs)(o.Fragment,{children:[m.settings?.mode===`equal_daily`&&g?(0,o.jsx)(i.Alert,{style:{marginBottom:12},showIcon:!0,type:m.holding?`info`:`success`,message:m.holding?`Leads received until ${dt(m.cutoffAt)} wait, then they are shared equally among counsellors who are online at ${dt(m.cutoffAt)}.`:`Cut-off ${dt(m.cutoffAt)} has passed: each new lead goes to the online counsellor with the fewest leads today.`}):null,(0,o.jsx)(Qe,{items:[{key:`received`,label:`Received`,value:h.received??0,tone:`blue`,icon:(0,o.jsx)(a.InboxOutlined,{})},{key:`assigned`,label:`Assigned`,value:h.assigned??0,tone:`green`,icon:(0,o.jsx)(a.CheckCircleOutlined,{})},{key:`left`,label:`Left to assign`,value:h.pending??0,tone:`violet`,icon:(0,o.jsx)(a.ClockCircleOutlined,{}),sub:`Waiting for all counsellors`},{key:`eligible`,label:`Eligible now`,value:h.eligible??0,tone:`pink`,icon:(0,o.jsx)(a.TeamOutlined,{})},{key:`atCap`,label:`At open-lead limit`,value:h.atCap??0,tone:`amber`,icon:(0,o.jsx)(a.WarningOutlined,{})},{key:`resets`,label:`Resets today`,value:h.resetsToday??0,tone:`green`,icon:(0,o.jsx)(a.SyncOutlined,{}),sub:`Quota refills`},{key:`unavailable`,label:`Unavailable`,value:h.unavailable??0,tone:`grey`,icon:(0,o.jsx)(a.UserOutlined,{})},{key:`target`,label:`Target each`,value:h.target??0,tone:`blue`,icon:(0,o.jsx)(a.ThunderboltOutlined,{})},{key:`balance`,label:`Balance`,tone:h.balance===`balanced`?`green`:`amber`,icon:(0,o.jsx)(a.BarChartOutlined,{}),value:(0,o.jsx)(`span`,{className:`ld-balance`,children:h.balance===`balanced`?`Balanced`:`Catching up (gap ${h.spread})`})}]}),_>0?(0,o.jsxs)(`div`,{className:`ld-explain`,children:[(0,o.jsx)(a.InfoCircleOutlined,{}),(0,o.jsxs)(`div`,{children:[(0,o.jsx)(`strong`,{children:`How the numbers work.`}),` "Untouched `,`x / ${_}`,`" is per counsellor: one counsellor holds at most `,_,` untouched leads at a time.`,` `,`When their untouched leads fall to `,ee,` or fewer, their quota refills (a `,(0,o.jsx)(`em`,{children:`reset`}),`) and they get leads again up to `,_,`.`,` `,`So "Assigned today" can be well above `,_,`. "Left to assign" is the queue for everyone together, not for one counsellor.`]})]}):null,h.balance!==`balanced`&&(h.spread??0)>1?(0,o.jsx)(ct,{type:`secondary`,style:{fontSize:12},children:`Counsellors who joined later get new leads first until they catch up. Leads already assigned are never moved, so an exact match is not always possible.`}):null,(0,o.jsx)(i.Table,{rowKey:`legacyUserId`,size:`small`,columns:y,dataSource:m.counsellors??[],pagination:!1,scroll:{x:`max-content`},loading:c.loading,locale:{emptyText:(0,o.jsx)(i.Empty,{description:`No counsellor is on any form's list yet. Add counsellors in the Forms tab.`})}})]}),u?(0,o.jsx)(_t,{counsellor:u,onClose:e=>{d(null),e&&l()}}):null]})}function _t({counsellor:e,onClose:t}){let[n]=i.Form.useForm(),[a,c]=mt(()=>L((0,s.default)().format(`YYYY-MM-DD`)),[]),[l,u]=(0,r.useState)(!1),[d,f]=(0,r.useState)(!1),p=(Array.isArray(a.data)?a.data:[]).filter(t=>Number(t.legacyUserId)===Number(e.legacyUserId)),m=async()=>{let t=await n.validateFields();u(!0);try{await R({legacyUserId:e.legacyUserId,from:t.range[0].format(`YYYY-MM-DD`),to:t.range[1].format(`YYYY-MM-DD`),reason:t.reason??``}),i.message.success(`Leave saved: no new leads on those days`),n.resetFields(),f(!0),c()}catch(e){i.message.error(C(e))}finally{u(!1)}},h=async e=>{try{await z(e),i.message.success(`Leave removed`),f(!0),c()}catch(e){i.message.error(C(e))}};return(0,o.jsxs)(i.Modal,{open:!0,title:`Leave · ${e.name}`,onCancel:()=>t(d),footer:(0,o.jsx)(i.Button,{onClick:()=>t(d),children:`Close`}),children:[(0,o.jsxs)(i.Form,{form:n,layout:`vertical`,children:[(0,o.jsx)(i.Form.Item,{name:`range`,label:`Days on leave`,rules:[{required:!0,message:`Choose the days`}],children:(0,o.jsx)(i.DatePicker.RangePicker,{style:{width:`100%`},disabledDate:e=>e&&e.isBefore((0,s.default)(),`day`)})}),(0,o.jsx)(i.Form.Item,{name:`reason`,label:`Reason (optional)`,children:(0,o.jsx)(i.Input,{maxLength:300})}),(0,o.jsx)(i.Button,{type:`primary`,loading:l,onClick:m,children:`Add leave`})]}),(0,o.jsx)(ct,{type:`secondary`,style:{margin:`12px 0 4px`},children:`Upcoming leave`}),a.loading?(0,o.jsx)(i.Skeleton,{active:!0,paragraph:{rows:1}}):a.error?(0,o.jsx)(ht,{text:a.error,onRetry:c}):p.length?(0,o.jsx)(i.Space,{direction:`vertical`,style:{width:`100%`},children:p.map(e=>(0,o.jsxs)(i.Space,{style:{justifyContent:`space-between`,width:`100%`},children:[(0,o.jsxs)(st,{children:[(0,s.default)(e.from).format(`D MMM`),` – `,(0,s.default)(e.to).format(`D MMM YYYY`),e.reason?` · ${e.reason}`:``]}),(0,o.jsx)(i.Popconfirm,{title:`Remove this leave?`,okText:`Remove`,onConfirm:()=>h(String(e._id)),children:(0,o.jsx)(i.Button,{size:`small`,type:`link`,danger:!0,children:`Remove`})})]},String(e._id)))}):(0,o.jsx)(st,{type:`secondary`,children:`None.`})]})}function vt({rows:e=[]}){let[t,n]=(0,r.useState)(`waiting`),[s,c]=(0,r.useState)(``),[l,u]=(0,r.useState)(1),[d,f]=mt(()=>B({status:t===`waiting`?``:t,formId:s,page:l,limit:25}),[t,s,l]),p=[{title:`Lead reference`,dataIndex:`facebookLeadId`},{title:`Form`,dataIndex:`facebookFormId`,render:t=>e.find(e=>e.formId===t)?.formName??`Form ${t}`},{title:`Received`,dataIndex:`createdAt`,render:ft},{title:`Waiting`,dataIndex:`createdAt`,key:`waited`,render:(e,t)=>t.status===`dead`?`–`:pt(e)},{title:`Status`,dataIndex:`status`,render:(e,t)=>e===`dead`?(0,o.jsx)(i.Tag,{color:`red`,children:`Assignment Failed`}):e===`processing`?(0,o.jsx)(i.Tag,{color:`blue`,children:`Assigning…`}):(0,o.jsx)(i.Tag,{color:t.lastResult===`awaiting_cutoff`?`purple`:`gold`,children:ut[t.lastResult]??`Pending Assignment`})},{title:`Next try`,dataIndex:`nextAttemptAt`,render:(e,t)=>t.status===`dead`?`–`:ft(e)},{title:`Detail`,key:`detail`,render:(e,t)=>t.lastErrorCode||(ut[t.lastResult]?``:t.lastResult)||`–`}];return(0,o.jsxs)(`div`,{className:`ld-queue`,children:[(0,o.jsxs)(i.Space,{wrap:!0,style:{marginBottom:12},children:[(0,o.jsx)(i.Segmented,{value:t,onChange:e=>{n(e),u(1)},options:[{value:`waiting`,label:`Waiting`},{value:`failed`,label:`Failed`},{value:`all`,label:`All`}]}),(0,o.jsx)(i.Select,{style:{minWidth:220},value:s,onChange:e=>{c(e),u(1)},options:[{value:``,label:`All forms`},...e.map(e=>({value:e.formId,label:e.formName??e.formId}))]}),(0,o.jsx)(i.Button,{icon:(0,o.jsx)(a.ReloadOutlined,{}),onClick:f,children:`Refresh`})]}),(0,o.jsx)(ct,{type:`secondary`,style:{fontSize:12},children:`Leads stay here safely until a counsellor can take them; nothing is lost when nobody is logged in. A lead becomes an LMS lead when it is assigned.`}),d.error?(0,o.jsx)(ht,{text:d.error,onRetry:f}):(0,o.jsx)(i.Table,{rowKey:e=>String(e._id??e.facebookLeadId),size:`small`,loading:d.loading,columns:p,dataSource:d.data?.rows??[],scroll:{x:`max-content`},pagination:{current:l,pageSize:25,total:d.data?.total??0,onChange:u,showSizeChanger:!1},locale:{emptyText:(0,o.jsx)(i.Empty,{description:t===`failed`?`No failed leads.`:`No leads are waiting.`})}})]})}var yt=[{value:`report`,label:`Report`},{value:`log`,label:`Log`},{value:`assignments`,label:`Assignments`}],bt=e=>e?{from:e[0].format(`YYYY-MM-DD`),to:e[1].format(`YYYY-MM-DD`)}:{};function xt(){let[e,t]=(0,r.useState)(`report`),[a,c]=(0,r.useState)(``),[l,u]=(0,r.useState)(null),[d,f]=mt(()=>n.H(bt(l)),[l]),p=(Array.isArray(d.data?.rows)?d.data.rows:[]).map(e=>({value:String(e.legacyUserId),label:e.name}));return(0,o.jsxs)(`div`,{className:`ld-history ld-panel`,children:[(0,o.jsxs)(`div`,{className:`ld-toolbar`,children:[(0,o.jsx)(i.Segmented,{value:e,onChange:t,options:yt}),e===`assignments`?null:(0,o.jsxs)(i.Space,{wrap:!0,children:[(0,o.jsx)(i.Select,{style:{minWidth:200},value:a,onChange:c,"aria-label":`Counsellor`,options:[{value:``,label:`All counsellors`},...p],showSearch:!0,optionFilterProp:`label`}),(0,o.jsx)(i.DatePicker.RangePicker,{value:l,onChange:u,allowEmpty:[!1,!1],disabledDate:e=>e&&e.isAfter((0,s.default)(),`day`)})]})]}),e===`report`?(0,o.jsx)(St,{state:d,reload:f,counsellor:a}):null,e===`log`?(0,o.jsx)(Ct,{counsellor:a,range:l},`${a}|${JSON.stringify(bt(l))}`):null,e===`assignments`?(0,o.jsx)(wt,{}):null]})}function St({state:e,reload:t,counsellor:n}){let r=Array.isArray(e.data?.rows)?e.data.rows:[],c=n?r.filter(e=>String(e.legacyUserId)===n):r,l=n?{...e.data?.summary,counsellors:c.length,leadsReceived:c.reduce((e,t)=>e+(t.leadsReceived??0),0),resets:c.reduce((e,t)=>e+(t.resets??0),0)}:e.data?.summary??{},u=Math.max(1,...c.map(e=>e.leadsReceived??0)),d=[{title:`Counsellor`,dataIndex:`name`,render:e=>(0,o.jsx)(st,{strong:!0,children:e}),sorter:(e,t)=>String(e.name).localeCompare(String(t.name))},{title:`Leads received`,dataIndex:`leadsReceived`,width:220,sorter:(e,t)=>e.leadsReceived-t.leadsReceived,defaultSortOrder:`descend`,render:e=>(0,o.jsxs)(`div`,{className:`ld-bar`,children:[(0,o.jsx)(`span`,{className:`ld-num`,children:e??0}),(0,o.jsx)(i.Progress,{percent:Math.round((e??0)/u*100),size:`small`,showInfo:!1,strokeColor:`var(--cc-s-accent)`})]})},{title:`Resets`,dataIndex:`resets`,align:`right`,sorter:(e,t)=>e.resets-t.resets,render:e=>e?(0,o.jsx)($e,{tone:`green`,icon:(0,o.jsx)(a.SyncOutlined,{}),children:e}):(0,o.jsx)(`span`,{className:`ld-muted`,children:`0`})},{title:`Reached limit`,dataIndex:`timesCapped`,align:`right`,sorter:(e,t)=>e.timesCapped-t.timesCapped,render:e=>e?(0,o.jsx)($e,{tone:`amber`,children:e}):(0,o.jsx)(`span`,{className:`ld-muted`,children:`0`})},{title:`Last reset`,dataIndex:`lastResetAt`,render:e=>e?ft(e):`Never`},{title:`First lead`,dataIndex:`firstAssignedAt`,render:ft},{title:`Last lead`,dataIndex:`lastAssignedAt`,render:ft}];return e.error?(0,o.jsx)(ht,{text:e.error,onRetry:t}):(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(Qe,{items:[{key:`people`,label:`Counsellors`,value:l.counsellors??0,tone:`blue`,icon:(0,o.jsx)(a.TeamOutlined,{})},{key:`leads`,label:`Leads received`,value:l.leadsReceived??0,tone:`pink`,icon:(0,o.jsx)(a.InboxOutlined,{})},{key:`resets`,label:`Resets`,value:l.resets??0,tone:`green`,icon:(0,o.jsx)(a.SyncOutlined,{}),sub:`Quota refills`},{key:`since`,label:`Resets tracked since`,value:l.logSince?(0,s.default)(l.logSince).format(`D MMM YYYY`):`No reset yet`,tone:`violet`,icon:(0,o.jsx)(a.ClockCircleOutlined,{})}]}),(0,o.jsx)(ct,{type:`secondary`,style:{fontSize:12},children:`Leads received count every automatic assignment in equal daily mode. A reset is when a counsellor who reached the open-lead limit worked enough leads for their quota to refill.`}),(0,o.jsx)(i.Table,{rowKey:`legacyUserId`,size:`small`,loading:e.loading,columns:d,dataSource:c,pagination:!1,scroll:{x:`max-content`},locale:{emptyText:(0,o.jsx)(i.Empty,{description:`Nothing recorded for these filters yet.`})}})]})}function Ct({counsellor:e,range:t}){let[s,c]=(0,r.useState)(``),[l,u]=(0,r.useState)(1),[d,f]=mt(()=>n.lt({legacyUserId:e,event:s,page:l,limit:25,...bt(t)}),[e,t,s,l]),p=[{title:`When`,dataIndex:`at`,render:ft},{title:`Counsellor`,dataIndex:`counsellorName`,render:(e,t)=>e||`Counsellor #${t.counsellorId}`},{title:`Event`,dataIndex:`event`,render:e=>(0,o.jsx)($e,{tone:at[e]?.tone??`grey`,children:at[e]?.label??e})},{title:`Detail`,key:`detail`,render:(e,t)=>ot(t)}];return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(i.Space,{wrap:!0,style:{marginBottom:12},children:[(0,o.jsx)(i.Segmented,{value:s,onChange:e=>{c(e),u(1)},options:[{value:``,label:`All events`},...Object.entries(at).map(([e,t])=>({value:e,label:t.label}))]}),(0,o.jsx)(i.Button,{icon:(0,o.jsx)(a.ReloadOutlined,{}),onClick:f,children:`Refresh`})]}),d.error?(0,o.jsx)(ht,{text:d.error,onRetry:f}):(0,o.jsx)(i.Table,{rowKey:e=>String(e._id),size:`small`,loading:d.loading,columns:p,dataSource:d.data?.rows??[],scroll:{x:`max-content`},pagination:{current:l,pageSize:25,total:d.data?.total??0,onChange:u,showSizeChanger:!1},locale:{emptyText:(0,o.jsx)(i.Empty,{description:`No events for these filters yet.`})}})]})}function wt(){let[e,t]=(0,r.useState)((0,s.default)()),[n,c]=(0,r.useState)(1),[l,u]=mt(()=>V({date:e?e.format(`YYYY-MM-DD`):``,page:n,limit:25}),[e,n]),d=[{title:`Lead reference`,dataIndex:`facebookLeadId`},{title:`Form`,dataIndex:`formName`},{title:`Received`,dataIndex:`receivedAt`,render:ft},{title:`Assigned`,dataIndex:`assignedAt`,render:ft},{title:`Counsellor`,dataIndex:`counsellorName`},{title:`Their leads that day`,dataIndex:`countAtAssignment`,align:`right`},{title:`Skipped`,dataIndex:`skipped`,render:e=>Array.isArray(e)&&e.length?(0,o.jsx)(i.Tooltip,{title:e.map(e=>`${e.name||`#${e.legacyUserId}`}: ${lt[e.reason]?.label??e.reason}`).join(`
2
- `),children:(0,o.jsxs)(i.Tag,{children:[e.length,` skipped`]})}):`–`}];return(0,o.jsxs)(`div`,{className:`ld-assignments`,children:[(0,o.jsxs)(i.Space,{wrap:!0,style:{marginBottom:12},children:[(0,o.jsx)(i.DatePicker,{value:e,onChange:e=>{t(e),c(1)},allowClear:!0,placeholder:`All days`}),(0,o.jsx)(i.Button,{icon:(0,o.jsx)(a.ReloadOutlined,{}),onClick:u,children:`Refresh`})]}),(0,o.jsx)(ct,{type:`secondary`,style:{fontSize:12},children:`Every automatic assignment in equal daily mode. Manual reassignments are in the Reassign leads tab and History.`}),l.error?(0,o.jsx)(ht,{text:l.error,onRetry:u}):(0,o.jsx)(i.Table,{rowKey:e=>String(e._id),size:`small`,loading:l.loading,columns:d,dataSource:l.data?.rows??[],scroll:{x:`max-content`},pagination:{current:n,pageSize:25,total:l.data?.total??0,onChange:c,showSizeChanger:!1},locale:{emptyText:(0,o.jsx)(i.Empty,{description:`No assignments for this day yet.`})}})]})}var Tt=[`Asia/Kolkata`,`Asia/Dubai`,`Asia/Singapore`,`Europe/London`,`America/New_York`,`UTC`];function Et({canEdit:e=!1}){let[t]=i.Form.useForm(),[n,c]=mt(()=>I(),[]),[l,u]=(0,r.useState)(!1),d=n.data?.settings;(0,r.useEffect)(()=>{d&&t.setFieldsValue({openLeadCap:15,capWindowDays:0,refillAtRatio:.5,...d,startTime:(0,s.default)(d.startTime,`HH:mm`),cutoffTime:(0,s.default)(d.cutoffTime,`HH:mm`),resetTime:(0,s.default)(d.resetTime,`HH:mm`)})},[d,t]);let f=i.Form.useWatch(`mode`,t),p=i.Form.useWatch(`openLeadCap`,t),m=i.Form.useWatch(`refillAtRatio`,t),h=async()=>{let e=await t.validateFields(),n={...e,startTime:e.startTime.format(`HH:mm`),cutoffTime:e.cutoffTime.format(`HH:mm`),resetTime:e.resetTime.format(`HH:mm`)};i.Modal.confirm({title:`Save distribution settings?`,content:n.mode===`equal_daily`?`New leads will go to the online counsellor with the fewest leads today. Leads already assigned do not move.`:`New leads will go back to plain round-robin.`,okText:`Save`,onOk:async()=>{u(!0);try{await le(n),i.message.success(`Distribution settings saved`),c()}catch(e){i.message.error(C(e))}finally{u(!1)}}})};if(n.loading&&!n.data)return(0,o.jsx)(i.Skeleton,{active:!0});if(n.error)return(0,o.jsx)(ht,{text:n.error,onRetry:c});let g=tt(p,m);return(0,o.jsxs)(i.Form,{form:t,layout:`vertical`,disabled:!e,className:`ld-settings ld-panel`,style:{maxWidth:820},children:[(0,o.jsxs)(`section`,{className:`ld-card`,children:[(0,o.jsxs)(`div`,{className:`ld-card__title`,children:[(0,o.jsx)(a.TeamOutlined,{}),` Who gets leads`]}),(0,o.jsx)(i.Form.Item,{name:`mode`,label:`Only give leads to counsellors who are logged in`,valuePropName:`checked`,getValueProps:e=>({checked:e===`equal_daily`}),normalize:e=>e?`equal_daily`:`round_robin`,children:(0,o.jsx)(i.Switch,{checkedChildren:`On`,unCheckedChildren:`Off`})}),(0,o.jsx)(ct,{type:`secondary`,style:{marginBottom:0},children:f===`equal_daily`?`Only counsellors who are logged in right now, enabled, not on leave and under the open-lead limit get leads. Each lead goes to the one with the fewest leads today; equal counts take turns (round robin). A lead nobody can take waits and is offered again every 2 minutes.`:`Off: round robin as before. Leads take turns through each form's counsellor list, skipping only inactive users. Login, leave and the open-lead limit are not checked, and nothing waits for a login.`})]}),(0,o.jsxs)(`section`,{className:`ld-card ld-settings-group`,hidden:f!==`equal_daily`,children:[(0,o.jsxs)(`div`,{className:`ld-card__title`,children:[(0,o.jsx)(a.WarningOutlined,{}),` `,(0,o.jsx)(st,{strong:!0,children:`Open-lead limit`})]}),(0,o.jsx)(ct,{type:`secondary`,style:{margin:`4px 0 12px`,fontSize:13},children:`A counsellor who has this many untouched leads gets no new lead until they work some (a call, a follow-up, a status change or a save). Their leads are never moved. 0 = no limit.`}),(0,o.jsxs)(i.Row,{gutter:12,children:[(0,o.jsx)(i.Col,{xs:24,md:8,children:(0,o.jsx)(i.Form.Item,{name:`openLeadCap`,label:`Untouched leads per counsellor`,rules:[{required:!0}],children:(0,o.jsx)(i.InputNumber,{min:0,max:500,addonAfter:`leads`,style:{width:`100%`}})})}),(0,o.jsx)(i.Col,{xs:24,md:8,children:(0,o.jsx)(i.Form.Item,{name:`refillAtRatio`,label:`Refill when untouched falls to`,rules:[{required:!0,message:`Enter 0 to 100`}],getValueProps:e=>({value:nt(e)}),normalize:rt,children:(0,o.jsx)(i.InputNumber,{min:0,max:100,step:5,precision:0,addonAfter:`% of the limit`,style:{width:`100%`}})})}),(0,o.jsx)(i.Col,{xs:24,md:8,children:(0,o.jsx)(i.Form.Item,{name:`capWindowDays`,label:`Count untouched leads from`,rules:[{required:!0}],children:(0,o.jsx)(i.Select,{options:[{value:0,label:`Today`},{value:1,label:`Today and yesterday`},{value:2,label:`The last 3 days`},{value:6,label:`The last 7 days`}]})})})]}),Number(p)>0?(0,o.jsxs)(`div`,{className:`ld-explain`,children:[(0,o.jsx)(a.SyncOutlined,{}),(0,o.jsxs)(`div`,{children:[`A counsellor receives up to `,(0,o.jsx)(`strong`,{children:p}),` untouched leads. After reaching `,p,`, they get new leads again once their untouched leads fall to `,(0,o.jsx)(`strong`,{children:g}),` or fewer, then up to `,p,` again. Each refill is counted as a `,(0,o.jsx)(`em`,{children:`reset`}),` in History.`,Number(m)===0?` 0% = they wait until every lead is worked.`:``,Number(m)===1?` 100% = one lead at a time, as soon as they are under the limit.`:``]})]}):null]}),(0,o.jsxs)(`section`,{className:`ld-card`,hidden:f!==`equal_daily`,children:[(0,o.jsxs)(`div`,{className:`ld-card__title`,children:[(0,o.jsx)(a.ClockCircleOutlined,{}),` Daily timing`]}),(0,o.jsxs)(i.Row,{gutter:12,children:[(0,o.jsx)(i.Col,{xs:12,md:6,children:(0,o.jsx)(i.Form.Item,{name:`startTime`,label:`Day starts`,rules:[{required:!0}],children:(0,o.jsx)(i.TimePicker,{format:`HH:mm`,minuteStep:5,style:{width:`100%`}})})}),(0,o.jsx)(i.Col,{xs:12,md:6,children:(0,o.jsx)(i.Form.Item,{name:`cutoffTime`,label:`Initial cut-off`,rules:[{required:!0}],extra:`Morning leads wait until this time.`,children:(0,o.jsx)(i.TimePicker,{format:`HH:mm`,minuteStep:5,style:{width:`100%`}})})}),(0,o.jsx)(i.Col,{xs:12,md:6,children:(0,o.jsx)(i.Form.Item,{name:`resetTime`,label:`Daily reset`,rules:[{required:!0}],children:(0,o.jsx)(i.TimePicker,{format:`HH:mm`,minuteStep:5,style:{width:`100%`}})})}),(0,o.jsx)(i.Col,{xs:12,md:6,children:(0,o.jsx)(i.Form.Item,{name:`timezone`,label:`Time zone`,rules:[{required:!0}],children:(0,o.jsx)(i.Select,{options:Tt.map(e=>({value:e,label:e}))})})}),(0,o.jsx)(i.Col,{xs:24,md:12,children:(0,o.jsx)(i.Form.Item,{name:`holdUntilCutoff`,label:`Hold morning leads until the cut-off`,valuePropName:`checked`,extra:`Off (recommended): leads go to whoever is online as they arrive; the open-lead limit spreads the morning backlog.`,children:(0,o.jsx)(i.Switch,{})})}),(0,o.jsx)(i.Col,{xs:24,md:12,children:(0,o.jsx)(i.Form.Item,{name:`onlineWindowMinutes`,label:`Offline after no activity for`,rules:[{required:!0}],children:(0,o.jsx)(i.InputNumber,{min:2,max:120,addonAfter:`minutes`,style:{width:`100%`}})})})]})]}),(0,o.jsx)(`div`,{className:`ld-settings__actions`,children:e?(0,o.jsx)(i.Button,{type:`primary`,size:`large`,loading:l,onClick:h,children:`Save settings`}):(0,o.jsx)(st,{type:`secondary`,children:`Only users who can edit lead mapping can change these settings.`})})]})}var Dt=e.t({default:()=>Bt}),{Text:Ot,Title:kt}=i.Typography,At=10,jt=`—`,Mt=`You don't have permission to do this.`,Nt=`This could not be loaded. Press Try again first.`;function Pt(e,t){return Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[]}var Ft={forms:{load:m,read:e=>Pt(e,`forms`),label:`Facebook forms`},courses:{load:h,read:e=>Pt(e,`courses`),label:`courses`},mappings:{load:g,read:e=>Pt(e,`mappings`),label:`chosen courses`},distributions:{load:E,read:e=>Pt(e,`distributions`),label:`counsellor lists`},counsellors:{load:D,read:e=>Pt(e,`counsellors`),label:`active counsellors`}},It=Object.keys(Ft),Lt=Object.fromEntries(It.map(e=>[e,[]])),Rt=Object.fromEntries(It.map(e=>[e,{loaded:!1,ok:!1,error:``}]));function zt({distribution:e}){let t=e?.counsellors||[];if(!t.length)return(0,o.jsx)(Ot,{type:`secondary`,children:`Not set up`});let n=t.map(e=>e.name||`Unnamed counsellor`),r=De(e);return(0,o.jsxs)(`div`,{className:`fb-who`,children:[(0,o.jsx)(i.Tooltip,{title:n.join(`, `),trigger:[`hover`,`focus`],children:(0,o.jsxs)(`span`,{className:`fb-avatars`,role:`group`,tabIndex:0,"aria-label":`Gets leads: ${n.join(`, `)}`,children:[n.slice(0,3).map((e,t)=>(0,o.jsx)(`span`,{className:`fb-avatar`,"aria-hidden":`true`,children:(Array.from(e)[0]||`?`).toUpperCase()},`${e}-${t}`)),n.length>3&&(0,o.jsxs)(`span`,{className:`fb-avatar fb-avatar--more`,"aria-hidden":`true`,children:[`+`,n.length-3]})]})}),(0,o.jsxs)(`span`,{className:`fb-next`,children:[`Next: `,r||`No one active`]})]})}function Bt(){let[e,t]=(0,r.useState)(Lt),[n,s]=(0,r.useState)(Rt),[l,u]=(0,r.useState)(!0),[f,p]=(0,r.useState)(null),[m,_]=(0,r.useState)(`forms`),[v,y]=(0,r.useState)(``),[b,x]=(0,r.useState)(`all`),[S,w]=(0,r.useState)(null),[T,O]=(0,r.useState)(1),[k,A]=(0,r.useState)(``),[j,te]=(0,r.useState)(null),[ne,N]=(0,r.useState)(!1),[re,ie]=(0,r.useState)(0),oe=(0,r.useRef)(0),se=(0,r.useRef)(0),P=(0,r.useRef)({element:null,formId:``}),F=(0,r.useRef)(null),ce=(0,r.useCallback)(async()=>{let e=++oe.current;u(!0);let n=await Promise.allSettled(It.map(e=>Ft[e].load()));e===oe.current&&(t(e=>{let t={...e};return n.forEach((e,n)=>{e.status===`fulfilled`&&(t[It[n]]=Ft[It[n]].read(e.value))}),t}),s(e=>{let t={...e};return n.forEach((n,r)=>{let i=It[r];t[i]=n.status===`fulfilled`?{loaded:!0,ok:!0,error:``}:{loaded:e[i].loaded,ok:!1,error:C(n.reason,`Please try again.`,{hideServerText:!0})}}),t}),u(!1))},[]),I=(0,r.useCallback)(()=>(ie(e=>e+1),ce()),[ce]);(0,r.useEffect)(()=>{ce()},[ce]),(0,r.useEffect)(()=>{let e=!0;return ae().then(t=>{e&&p(t)}).catch(()=>{}),()=>{e=!1}},[]);let{alerts:le,alertsOk:ue,failedCount:L}=J({refreshKey:re}),R={add:f?.permissions?.canAdd!==!1,edit:f?.permissions?.canEdit!==!1,remove:f?.permissions?.canDelete!==!1},{forms:z,courses:B,mappings:V,distributions:H,counsellors:U}=e,W=n.forms.loaded,G=n.mappings.loaded,K=n.distributions.loaded,q=!W||!G||!K,de=l&&!It.some(e=>n[e].loaded),fe=(0,r.useMemo)(()=>new Map(H.map(e=>[String(e.formId),e])),[H]),pe=(0,r.useMemo)(()=>new Map(V.map(e=>[String(e.formId),e])),[V]),Y=(0,r.useMemo)(()=>new Map(B.map(e=>[String(e.courseId),e.courseName])),[B]),X=(0,r.useMemo)(()=>{let e=z.map(e=>({formId:String(e.id),formName:e.name||`Unnamed form`,inFormsList:!0})),t=new Set(e.map(e=>e.formId));return[...V,...H].forEach(n=>{let r=String(n.formId);t.has(r)||(t.add(r),e.push({formId:r,formName:n.formName||`Unnamed form`,inFormsList:!1}))}),e.map(e=>{let t=pe.get(e.formId),n=fe.get(e.formId);return{...e,key:e.formId,mapping:t,distribution:n,courseName:t&&(Y.get(String(t.courseId))||t.courseName)||``,status:Ee({mapping:t,distribution:n,inFormsList:e.inFormsList},{forms:W,mappings:G,distributions:K})}})},[z,V,H,pe,fe,Y,W,G,K]),ge=(0,r.useMemo)(()=>{let e=v.trim().toLowerCase();return X.filter(t=>S&&!S.includes(t.formId)||b!==`all`&&t.status!==b?!1:`${t.formName} ${t.formId} ${t.courseName}`.toLowerCase().includes(e))},[X,S,b,v]),Z=!!v.trim()||b!==`all`||!!S,_e=Math.min(T,Math.max(1,Math.ceil(ge.length/At))),ye=()=>{y(``),x(`all`),w(null),O(1)},be=e=>{y(``),x(`all`),w(e),O(1),_(`forms`)},xe=e=>{y(``),w(null),x(e),O(1),_(`forms`)},Se=n.forms.ok&&n.mappings.ok&&n.distributions.ok,Ce=e=>X.filter(t=>t.status===e).length,we=ue?Number(le?.unassignedCount||0):null,Te=we===null||L===null?null:we+L,De=[{key:`ready`,label:`forms ready`,value:Se?Ce(`ready`):jt,onClick:Se?()=>xe(`ready`):void 0},{key:`setup`,label:`need setup`,value:Se?Ce(`needs_setup`):jt,onClick:Se?()=>xe(`needs_setup`):void 0},{key:`waiting`,label:`leads waiting`,value:we??jt,onClick:we===null?void 0:()=>_(`attention`)},{key:`failed`,label:`failed leads`,value:L??jt,onClick:L===null?void 0:()=>_(`attention`)},{key:`counsellors`,label:`active counsellors`,value:n.counsellors.ok?U.length:jt}],Oe=e=>{t(t=>({...t,...e})),s(t=>{let n={...t};return Object.keys(e).forEach(e=>{n[e]={loaded:!0,ok:!0,error:``}}),n})},ke=async()=>{let[e,t,n,r]=await Promise.all([h(),g(),E(),D()]),i={courses:Pt(e,`courses`),mappings:Pt(t,`mappings`),distributions:Pt(n,`distributions`),counsellors:Pt(r,`counsellors`)};return Oe(i),i},Ae=async(e,t,n=null)=>{if(!q){P.current={element:n,formId:e.formId},A(e.formId);try{await ke(),se.current+=1,te({token:se.current,row:e,section:t}),N(!0)}catch(e){i.message.error(C(e,`Could not open this form. Please try again.`))}finally{A(``)}}},je=()=>{let{element:e,formId:t}=P.current;if(e?.isConnected){e.focus();return}[...F.current?.querySelectorAll(`[data-form-menu]`)||[]].find(e=>e.dataset.formMenu===t)?.focus()},Me=()=>{ie(e=>e+1),ce()},Pe=e=>{i.Modal.confirm({title:`Remove course mapping?`,content:(0,o.jsxs)(`span`,{children:[`Remove the course mapping for `,(0,o.jsx)(`strong`,{children:e.formName}),`? Existing lead courses remain unchanged. `,e.distribution?`This form has saved counsellors. They stay in place unless you remove them separately.`:`Future leads from this form will arrive without a course.`]}),okText:`Remove mapping`,okType:`danger`,cancelText:`Cancel`,autoFocusButton:`cancel`,onOk:async()=>{A(e.formId);try{await ee(e.formId),i.message.success(`Course mapping removed`),Me()}catch(e){throw i.message.error(C(e,`Could not remove the mapping. Please try again.`)),e}finally{A(``)}}})},Fe=e=>{i.Modal.confirm({title:`Remove counsellor distribution?`,content:(0,o.jsxs)(`span`,{children:[`Remove the saved counsellors and whose turn is next for `,(0,o.jsx)(`strong`,{children:e.formName}),`? Leads already given out will not change. New leads from this form will wait until counsellors are set up again. Its course mapping stays as it is.`]}),okText:`Remove distribution`,okType:`danger`,cancelText:`Cancel`,autoFocusButton:`cancel`,onOk:async()=>{A(e.formId);try{if((await M(e.formId))?.deleted===!1)throw Error(`This has already been removed. Refresh and try again.`);i.message.success(`Counsellor distribution removed`),Me()}catch(e){throw i.message.error(C(e,`Could not remove the distribution. Please try again.`)),e}finally{A(``)}}})},Q=e=>{let t=e=>q?Nt:e?``:Mt,n=t(e.mapping?R.edit:R.add),r=t(e.distribution?R.edit:R.add);return{items:[{key:`mapping`,icon:e.mapping?(0,o.jsx)(a.EditOutlined,{}):(0,o.jsx)(a.PlusOutlined,{}),label:e.mapping?`Edit mapping`:`Set up mapping`,disabled:!!n,title:n},...e.mapping&&R.remove?[{key:`removeMapping`,icon:(0,o.jsx)(a.DeleteOutlined,{}),label:`Remove mapping`,danger:!0,disabled:q}]:[],{type:`divider`},{key:`distribution`,icon:(0,o.jsx)(a.TeamOutlined,{}),label:e.distribution?`Edit distribution`:`Set up distribution`,disabled:!!r,title:r},...e.distribution&&R.remove?[{key:`removeDistribution`,icon:(0,o.jsx)(a.DeleteOutlined,{}),label:`Remove distribution`,danger:!0,disabled:q}]:[]],onClick:({key:t})=>{t===`mapping`?Ae(e,`course`):t===`distribution`?Ae(e,`counsellors`):t===`removeMapping`?Pe(e):t===`removeDistribution`&&Fe(e)}}},$=e=>e.stopPropagation(),Le=[{title:`Form`,dataIndex:`formName`,key:`form`,render:(e,t)=>(0,o.jsxs)(`div`,{children:[(0,o.jsx)(`button`,{type:`button`,className:`fb-form-name`,disabled:q,onClick:e=>{$(e),Ae(t,`course`,e.currentTarget)},children:e}),(0,o.jsx)(`div`,{children:(0,o.jsxs)(Ot,{type:`secondary`,className:`fb-small`,children:[`Form ID: `,t.formId]})})]})},{title:`Course`,key:`course`,render:(e,t)=>G?t.mapping?(0,o.jsxs)(`span`,{className:`fb-course`,children:[t.courseName||`Course no longer available`,!t.mapping.isActive&&(0,o.jsx)(Ot,{type:`secondary`,children:` (off)`})]}):R.add?(0,o.jsx)(i.Button,{size:`small`,className:`fb-inline-btn`,disabled:q,loading:k===t.formId,onClick:e=>{$(e),Ae(t,`course`,e.currentTarget)},"aria-label":`Map course for ${t.formName}`,children:`Map course`}):(0,o.jsx)(Ot,{type:`secondary`,children:`No course yet`}):(0,o.jsx)(Ot,{type:`secondary`,children:jt})},{title:`Who gets leads`,key:`who`,render:(e,t)=>K?(0,o.jsx)(zt,{distribution:t.distribution}):(0,o.jsx)(Ot,{type:`secondary`,children:jt})},{title:`Status`,dataIndex:`status`,key:`status`,width:170,render:e=>(0,o.jsx)(Ne,{status:e})},{title:(0,o.jsx)(`span`,{className:`fb-sr-only`,children:`Actions`}),key:`actions`,width:56,align:`center`,render:(e,t)=>(0,o.jsx)(`span`,{onClick:$,children:(0,o.jsx)(i.Dropdown,{menu:Q(t),trigger:[`click`],placement:`bottomRight`,children:(0,o.jsx)(i.Button,{size:`small`,className:`fb-form-actions-trigger`,"aria-label":`Actions for ${t.formName}`,"data-form-menu":t.formId,loading:k===t.formId,icon:(0,o.jsx)(a.MoreOutlined,{})})})})}],Re=()=>l?` `:q?(0,o.jsx)(i.Empty,{description:`Forms can't be shown right now.`}):Z?(0,o.jsx)(i.Empty,{description:`No forms match these filters.`,children:(0,o.jsx)(i.Button,{onClick:ye,children:`Clear filters`})}):(0,o.jsx)(i.Empty,{description:`No Facebook forms yet. Create a lead form on Facebook, then refresh.`,children:(0,o.jsx)(i.Button,{onClick:I,children:`Refresh`})}),ze=It.filter(e=>!n[e].ok&&n[e].error),Be=ze.every(e=>n[e].loaded),Ve=()=>`Could not load ${ze.map(e=>Ft[e].label).join(`, `)}. ${[...new Set(ze.map(e=>n[e].error))].join(` `)}`,He=(0,o.jsxs)(`div`,{className:`fb-tab-body`,children:[(0,o.jsxs)(`div`,{className:`fb-toolbar`,children:[(0,o.jsxs)(`div`,{className:`fb-field fb-field--grow`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-forms-search`,children:`Search forms`}),(0,o.jsx)(i.Input,{id:`fb-forms-search`,allowClear:!0,prefix:(0,o.jsx)(a.SearchOutlined,{"aria-hidden":`true`}),placeholder:`Form or course name`,value:v,onChange:e=>{y(e.target.value),O(1)}})]}),(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-forms-show`,children:`Show`}),(0,o.jsx)(i.Select,{id:`fb-forms-show`,className:`fb-show-select`,value:b,disabled:!G||!K,onChange:e=>{x(e),O(1)},options:[{value:`all`,label:`All forms`},...Object.entries(ve).map(([e,t])=>({value:e,label:t.label}))]})]})]}),S&&(0,o.jsxs)(`div`,{className:`fb-filter-note`,role:`status`,children:[(0,o.jsx)(`span`,{children:S.length===1?`Showing 1 form that needs attention.`:`Showing ${S.length} forms that need attention.`}),(0,o.jsx)(i.Button,{size:`small`,type:`link`,onClick:()=>{w(null),O(1)},children:`Show all forms`})]}),de?(0,o.jsx)(i.Skeleton,{active:!0,title:!1,paragraph:{rows:6}}):(0,o.jsx)(i.Table,{rowKey:`formId`,className:`fb-forms-table${q?``:` fb-forms-table--open`}`,columns:Le,dataSource:ge,loading:l,size:`middle`,scroll:{x:860},onRow:e=>({onClick:()=>Ae(e,`course`)}),pagination:{current:_e,pageSize:At,showSizeChanger:!1,onChange:O,showTotal:e=>`${e} Facebook form${e===1?``:`s`}`},locale:{emptyText:Re()}}),(0,o.jsx)(Ot,{type:`secondary`,className:`fb-small`,children:`Changing a form affects future leads only. Leads you already have keep their course and counsellor.`})]}),Ue={rows:X,refreshKey:re},We=[{key:`forms`,label:`Forms`,children:He},{key:`attention`,label:`Needs attention${Te===null?``:` (${Te})`}`,children:(0,o.jsx)(Ge,{...Ue,canEdit:R.edit,onChanged:()=>ie(e=>e+1)})},{key:`skips`,label:`Skipped counsellors`,children:(0,o.jsx)(qe,{...Ue})},{key:`reassign`,label:`Reassign leads`,children:(0,o.jsx)(he,{...Ue,eligibleCounsellors:U,limits:f?.limits,reasonTypes:f?.reasonTypes,canEdit:R.edit,onChanged:()=>ie(e=>e+1)})},{key:`history`,label:`History`,children:(0,o.jsx)(Je,{...Ue})},{key:`today`,label:`Today`,children:(0,o.jsx)(gt,{canEdit:R.edit})},{key:`queue`,label:`Pending queue`,children:(0,o.jsx)(vt,{rows:X})},{key:`assignments`,label:`Assignment history`,children:(0,o.jsx)(xt,{})},{key:`distributionSettings`,label:`Distribution settings`,children:(0,o.jsx)(Et,{canEdit:R.edit})}],Ke=j?X.find(e=>e.formId===j.row.formId)||j.row:null;return(0,o.jsxs)(`div`,{className:`facebook-course-mapping`,ref:F,children:[(0,o.jsxs)(`div`,{className:`admin-section-head fb-head`,children:[(0,o.jsxs)(`div`,{children:[(0,o.jsx)(kt,{level:4,children:`Facebook Leads`}),(0,o.jsx)(Ot,{type:`secondary`,children:`Choose the course and counsellors for each Facebook form.`})]}),(0,o.jsx)(i.Button,{icon:(0,o.jsx)(a.ReloadOutlined,{"aria-hidden":`true`}),onClick:I,loading:l,children:`Refresh`})]}),(0,o.jsx)(d,{items:De,className:`fb-health`,ariaLabel:`Facebook leads health`}),ze.length>0&&!l&&(0,o.jsx)(c,{className:`fb-load-problem`,type:Be?`warning`:`error`,title:Be?`Showing the last information we could load`:`Some information didn't load`,description:Ve(),action:(0,o.jsx)(i.Button,{size:`small`,onClick:I,children:`Try again`})}),f&&(!R.add||!R.edit||!R.remove)&&(0,o.jsx)(c,{className:`fb-load-problem`,type:`info`,title:`Your role can't make some changes here, so those actions are turned off.`}),(0,o.jsx)(me,{alerts:le,failedCount:L??0,onViewLeads:()=>_(`attention`),onShowForms:be}),(0,o.jsx)(i.Tabs,{size:`small`,activeKey:m,onChange:_,items:We,className:`fb-tabs`}),j&&(0,o.jsx)(Ie,{open:ne,row:Ke,section:j.section,mapping:pe.get(j.row.formId),current:fe.get(j.row.formId),courses:B,counsellors:U,limits:f?.limits,permissions:{canAdd:R.add,canEdit:R.edit},onClose:()=>N(!1),onSaved:Me,onAfterClose:je,onReload:async()=>{let e=await ke(),t=j.row.formId;return{mapping:e.mappings.find(e=>String(e.formId)===t),current:e.distributions.find(e=>String(e.formId)===t)}}},j.token)]})}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return Qe}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return Ze}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Dt}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return $e}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return et}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Bt}});
3
- //# sourceMappingURL=FacebookCourseMappingsSection-7b-UVe60.cjs.map
1
+ const e=require("./rolldown-runtime-Chgba0Kb.cjs"),t=require("./authApi-D0LZjLV6.cjs"),n=require("./adminApi-BS2Ci_Le.cjs");let r=require("react"),i=require("antd"),a=require("@ant-design/icons"),o=require("react/jsx-runtime"),s=require("dayjs");s=e.n(s,1);function c({className:e=``,variant:t=`default`,showIcon:n=!0,...r}){return(0,o.jsx)(i.Alert,{className:`app-alert app-alert--${t} ${e}`.trim(),showIcon:n,...r})}var l=new Intl.NumberFormat;function u(e){return e==null||e===``?`–`:typeof e==`number`&&Number.isFinite(e)?l.format(e):String(e)}function d({items:e=[],loading:t=!1,className:n=``,ariaLabel:r=`Summary`}){return t&&e.length===0?(0,o.jsx)(`div`,{className:`cc-stat-strip ${n}`.trim(),"aria-busy":`true`,"aria-label":r,children:[0,1,2,3].map(e=>(0,o.jsx)(`div`,{className:`cc-stat`,children:(0,o.jsx)(i.Skeleton.Button,{active:!0,size:`small`,style:{width:56}})},e))}):e.length===0?null:(0,o.jsx)(`div`,{className:`cc-stat-strip ${n}`.trim(),role:`group`,"aria-label":r,"aria-busy":t||void 0,children:e.map(e=>{let t=(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`span`,{className:`cc-stat__value`,children:u(e.value)}),(0,o.jsx)(`span`,{className:`cc-stat__label`,children:e.label})]});return typeof e.onClick==`function`?(0,o.jsx)(`button`,{type:`button`,className:`cc-stat cc-stat--button${e.active?` is-active`:``}`,onClick:e.onClick,"aria-pressed":e.active?!0:void 0,children:t},e.key):(0,o.jsx)(`div`,{className:`cc-stat`,children:t},e.key)})})}var f=`${t.y}/admin/facebook`;async function p(e,n={}){let r=t.u(),i=await fetch(`${f}${e}`,{...n,headers:{"Content-Type":`application/json`,...t.O({"X-App-Id":String(t.b)}),...r?{Authorization:`Bearer ${r}`}:{},...n.headers||{}}}),a=await i.json().catch(()=>({}));if(!i.ok||a?.status===!1){let e=Error(a?.error||a?.message||a?.reason||`HTTP ${i.status}`);throw e.status=i.status,e}return a?.data??a}var m=()=>p(`/forms`),h=()=>p(`/courses`),g=()=>p(`/course-mappings`),_=(e,t=!1)=>p(t?`/course-mappings/${encodeURIComponent(e.formId)}`:`/course-mappings`,{method:t?`PUT`:`POST`,body:JSON.stringify(e)}),ee=e=>p(`/course-mappings/${encodeURIComponent(e)}`,{method:`DELETE`}),v=`${t.y}/admin/facebook`,y=`Could not connect. Check your internet connection and try again.`,b=`You don't have permission to do this. Ask your administrator for access.`,x=`Something went wrong. Please try again.`;function S(e,t=``){return e===401?`Your session has ended. Please sign in again.`:e===403?b:e===404?`This could not be found. Refresh the page and try again.`:e===409?t||`Someone else changed this. Refresh the page and try again.`:e>=500?`The server could not finish this. Please try again in a moment.`:t||x}function C(e,t=x,{hideServerText:n=!1}={}){if(e?.plain)return e.message;let r=String(e?.message||``);if(typeof e?.status==`number`)return S(e.status,r);let i=/^HTTP (\d{3})$/.exec(r);return i?S(Number(i[1])):e instanceof TypeError||/failed to fetch|networkerror|load failed/i.test(r)?y:/forbidden|permission|not allowed/i.test(r)?b:n?t:r||t}function w(e,t){let n=Error(e===0?y:S(e,t));return n.status=e,n.plain=!0,n.serverMessage=t,n}async function T(e,n={}){let r=t.u();if(!r)throw w(401,``);let i;try{i=await fetch(`${v}${e}`,{...n,headers:{"Content-Type":`application/json`,...t.O({"X-App-Id":String(t.b)}),Authorization:`Bearer ${r}`,...n.headers||{}}})}catch{throw w(0,``)}let a=await i.json().catch(()=>({}));if(!i.ok||a.status===!1)throw w(i.status,a.error||a.message||``);return a.data??a}var E=()=>T(`/distributions`).then(e=>Array.isArray(e)?e:e.distributions||[]);async function D(){let e=[];for(let t=1;t<=1e3;t++){let n=await T(`/counsellors?page=${t}&limit=100`);if(!Array.isArray(n.counsellors))throw Error(`Could not read the list of counsellors. Please try again.`);if(e.push(...n.counsellors),t>=Number(n.totalPages||0)||!n.counsellors.length)return e}throw Error(`The list of counsellors is too long to load. Please contact support.`)}var O=({formId:e,counsellorIds:t,isActive:n,version:r},i)=>T(i?`/distribution/${encodeURIComponent(e)}`:`/distribution`,{method:i?`PUT`:`POST`,body:JSON.stringify({formId:e,counsellorIds:t,isActive:n,...r==null?{}:{version:r}})}),k=(e,{groupBy:t=``,details:n=!1}={})=>{t&&e.set(`groupBy`,t),n&&e.set(`details`,`1`)};function A({page:e=1,limit:t=20,formId:n=``,groupBy:r=``}={}){let i=new URLSearchParams({page:String(e),limit:String(t)});return n&&i.set(`formId`,n),k(i,{groupBy:r}),T(`/distribution-skips?${i}`)}function j({status:e=`unassigned`,page:t=1,limit:n=20,formId:r=``,groupBy:i=``,details:a=!1}={}){let o=new URLSearchParams({status:e,page:String(t),limit:String(n)});return r&&o.set(`formId`,r),k(o,{groupBy:i,details:a}),T(`/unassigned-leads?${o}`)}var M=e=>T(`/distribution/${encodeURIComponent(e)}`,{method:`DELETE`}),te=()=>T(`/distribution-alerts`),ne=()=>T(`/reassign/summary`).then(e=>e.counsellors||[]);function N({fromUserId:e,formId:t=``,page:n=1,limit:r=20}={}){let i=new URLSearchParams({fromUserId:e,page:String(n),limit:String(r)});return t&&i.set(`formId`,t),T(`/reassign/leads?${i}`)}var re=e=>T(`/reassign`,{method:`POST`,body:JSON.stringify(e)});function ie({page:e=1,limit:t=20,formId:n=``,leadId:r=``}={}){let i=new URLSearchParams({page:String(e),limit:String(t)});return n&&i.set(`formId`,n),r&&i.set(`leadId`,r),T(`/reassignments?${i}`)}var ae=()=>T(`/meta`);function oe({page:e=1,limit:t=20,formId:n=``,groupBy:r=``,details:i=!1}={}){let a=new URLSearchParams({page:String(e),limit:String(t)});return n&&a.set(`formId`,n),k(a,{groupBy:r,details:i}),T(`/failed-leads?${a}`)}var se=e=>T(`/failed-leads/${encodeURIComponent(e)}/retry`,{method:`POST`});function P({page:e=1,limit:t=20,formId:n=``}={}){let r=new URLSearchParams({page:String(e),limit:String(t)});return n&&r.set(`formId`,n),T(`/history?${r}`)}var F=e=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([e,n])=>{n!=null&&n!==``&&t.set(e,String(n))});let n=t.toString();return n?`?${n}`:``},ce=e=>T(`/distribution/overview${F({date:e})}`),I=()=>T(`/distribution/settings`),le=e=>T(`/distribution/settings`,{method:`PUT`,body:JSON.stringify(e)}),ue=(e,t,n=``)=>T(`/distribution/counsellors/${encodeURIComponent(e)}/enabled`,{method:`PUT`,body:JSON.stringify({enabled:t,reason:n})}),L=e=>T(`/distribution/leaves${F({from:e})}`),R=e=>T(`/distribution/leaves`,{method:`POST`,body:JSON.stringify(e)}),z=e=>T(`/distribution/leaves/${encodeURIComponent(e)}`,{method:`DELETE`}),B=e=>T(`/distribution/queue${F(e)}`),V=e=>T(`/distribution/assignments${F(e)}`),{Text:H}=i.Typography,U=e=>e?new Date(e).toLocaleString():`—`,W=(e,t)=>`${e} ${t}${e===1?``:`s`}`,G=[{value:`on_leave`,label:`On leave`},{value:`left_company`,label:`Left the company`},{value:`workload`,label:`Workload balancing`},{value:`other`,label:`Other`}],K={no_active_counsellor:`no active counsellor`,distribution_not_configured:`no counsellors set up for the form`,distribution_disabled:`automatic turns are paused`,default_owner_inactive_or_missing:`default owner inactive`},q={not_open_or_not_assigned_to_counsellor:`no longer open or no longer with this counsellor`,changed_during_reassign:`was updated by the counsellor while moving (run again)`,update_failed:`could not be saved`};function de({canEdit:e=!0,fromId:t,toId:n,movingCount:r,reasonOk:i,minReason:a}){if(!e)return`You don't have permission to move leads.`;let o=[];return t||o.push(`choose who the leads are moving from`),r||o.push(`choose at least one lead`),n||o.push(`choose who gets the leads`),i||o.push(`write a reason of at least ${a} characters`),o.length?`To continue, ${o.join(`, `)}.`:``}function fe({id:e,rows:t=[],value:n,onChange:a,minWidth:s=260}){let c=(0,r.useMemo)(()=>t.map(e=>({value:e.formId,label:e.formName})),[t]);return(0,o.jsx)(i.Select,{id:e,showSearch:!0,optionFilterProp:`label`,allowClear:!0,style:{minWidth:s,maxWidth:`100%`},"aria-label":`Facebook form`,placeholder:`All Facebook forms`,value:n||void 0,onChange:e=>a(e||``),options:c,popupMatchSelectWidth:!1,notFoundContent:`No matching forms`})}function J({refreshKey:e=0,pollMs:t=6e4}={}){let[n,i]=(0,r.useState)({alerts:null,alertsOk:!1,failedCount:null});return(0,r.useEffect)(()=>{let e=!0,n=()=>{typeof document<`u`&&document.hidden||Promise.allSettled([te(),oe({page:1,limit:1})]).then(([t,n])=>{e&&i(e=>({alerts:t.status===`fulfilled`?t.value:e.alerts,alertsOk:t.status===`fulfilled`,failedCount:n.status===`fulfilled`?Number(n.value?.failedCount??n.value?.total??0):null}))})};n();let r=setInterval(n,t);return()=>{e=!1,clearInterval(r)}},[e,t]),n}function pe(e){let t=[...e?.formsWithoutActiveCounsellor||[],...e?.waitingForms||[]].map(e=>String(e.formId)).filter(Boolean);return[...new Set(t)]}function me({alerts:e,failedCount:t=0,onViewLeads:n,onShowForms:r}){let a=Number(e?.unassignedCount||0),s=e?.formsWithoutActiveCounsellor||[],l=Number(t||0),u=pe(e);if(!a&&!s.length&&!l)return null;let d=[];a&&d.push(`${W(a,`lead`)} waiting`),s.length&&d.push(`${W(s.length,`form`)} with no active counsellor`),l&&d.push(`${W(l,`lead`)} failed`);let f=[...new Set([...s,...e?.waitingForms||[]].map(e=>e.formName).filter(Boolean))],p=f.slice(0,2).join(`, `),m=f.length>2?` and ${f.length-2} more`:``;return(0,o.jsx)(c,{className:`fb-attention`,type:`warning`,title:d.join(` · `),description:p?`${p}${m}`:void 0,action:(0,o.jsxs)(`div`,{className:`fb-attention-actions`,children:[(a>0||l>0)&&n&&(0,o.jsx)(i.Button,{size:`small`,onClick:n,children:`View leads`}),u.length>0&&r&&(0,o.jsx)(i.Button,{size:`small`,onClick:()=>r(u),children:`Show these forms`})]})})}function he({rows:e=[],eligibleCounsellors:t=[],onChanged:n,limits:s,reasonTypes:c,canEdit:l=!0,refreshKey:u=0}){let[d,f]=(0,r.useState)([]),[p,m]=(0,r.useState)(!1),[h,g]=(0,r.useState)(``),[_,ee]=(0,r.useState)(``),[v,y]=(0,r.useState)({leads:[],total:0}),[b,x]=(0,r.useState)(!1),[S,C]=(0,r.useState)(1),[w,T]=(0,r.useState)([]),[E,D]=(0,r.useState)(!1),[O,k]=(0,r.useState)(``),[A,j]=(0,r.useState)(`on_leave`),[M,te]=(0,r.useState)(``),[ae,oe]=(0,r.useState)(!1),[se,P]=(0,r.useState)(``),[F,ce]=(0,r.useState)({reassignments:[],total:0}),[I,le]=(0,r.useState)(1),[ue,L]=(0,r.useState)(!1),R=Number(s?.minReason)||5,z=Number(s?.maxReason)||500,B=Number(s?.maxPerRun)||500,V=c?.length?c:G,W=Object.fromEntries(V.map(e=>[e.value,e.label])),K=W[A]?A:V[0]?.value,J=(0,r.useCallback)(async()=>{m(!0);try{f(await ne()),P(``)}catch(e){P(e.message)}finally{m(!1)}},[]),pe=(0,r.useCallback)(async()=>{if(!h){y({leads:[],total:0});return}x(!0);try{y(await N({fromUserId:h,formId:_,page:S,limit:20})),P(``)}catch(e){P(e.message),y({leads:[],total:0})}finally{x(!1)}},[h,_,S]),me=(0,r.useCallback)(async()=>{L(!0);try{ce(await ie({page:I,limit:10}))}catch(e){P(e.message)}finally{L(!1)}},[I]);(0,r.useEffect)(()=>{J()},[J,u]),(0,r.useEffect)(()=>{pe()},[pe,u]),(0,r.useEffect)(()=>{me()},[me,u]);let he=d.find(e=>e.userId===h),Y=Number(v.total||0),X=E?Math.min(Y,B):w.length,ge=(0,r.useMemo)(()=>t.filter(e=>e.userId!==h&&e.isActive!==!1).map(e=>({value:e.userId,label:e.name||e.email||e.userId})),[t,h]),Z=ge.find(e=>e.value===O)?.label||``,_e=M.trim().length>=R,ve=de({canEdit:l,fromId:h,toId:O,movingCount:X,reasonOk:_e,minReason:R}),ye=!ve&&!ae,be=e=>{g(e),C(1),T([]),D(!1),k(``)},xe=e=>{ee(e),C(1),T([]),D(!1)},Se=async()=>{oe(!0);try{let e=await re({fromUserId:h,toUserId:O,reasonType:K,reason:M.trim(),..._?{formId:_}:{},...E?{allOpen:!0}:{leadIds:w}}),t=e.skipped||[];if(i.message.success(`${e.moved} lead${e.moved===1?``:`s`} moved to ${e.to?.name||Z}`),t.length){let e=t.reduce((e,t)=>({...e,[t.reason]:(e[t.reason]||0)+1}),{});i.Modal.warning({title:`${t.length} lead${t.length===1?` was`:`s were`} not moved`,content:(0,o.jsx)(`ul`,{style:{paddingLeft:18},children:Object.entries(e).map(([e,t])=>(0,o.jsxs)(`li`,{children:[t,` — `,q[e]||e]},e))})})}e.auditSaved===!1&&i.message.warning(`Leads were moved, but the history row could not be saved. Each lead still has its own activity entry.`),e.remaining>0&&i.message.info(`${e.remaining} open lead${e.remaining===1?``:`s`} still with ${e.from?.name||`this counsellor`}. Run again to move them.`),T([]),D(!1),te(``),await Promise.all([J(),pe(),me()]),n&&n()}catch(e){i.message.error(e.message||`Could not reassign leads`)}finally{oe(!1)}},Ce=()=>i.Modal.confirm({title:`Move ${X} lead${X===1?``:`s`} to ${Z}?`,okText:`Reassign`,width:520,content:(0,o.jsxs)(`div`,{children:[(0,o.jsxs)(`p`,{style:{marginBottom:6},children:[`From `,(0,o.jsx)(`strong`,{children:he?.name||`selected counsellor`}),` to `,(0,o.jsx)(`strong`,{children:Z}),`.`]}),(0,o.jsxs)(`p`,{style:{marginBottom:6},children:[`Reason: `,(0,o.jsx)(`strong`,{children:W[K]}),` — `,M.trim()]}),(0,o.jsx)(H,{type:`secondary`,children:`Each lead gets an activity entry and a history row. The previous counsellor stops seeing these leads. Pending follow-up reminders are not moved.`})]}),onOk:Se}),we=[{title:`Lead`,dataIndex:`name`,render:(e,t)=>(0,o.jsxs)(`div`,{children:[(0,o.jsx)(H,{strong:!0,children:e||t.leadCode||t.facebookLeadId}),(0,o.jsx)(`div`,{children:(0,o.jsx)(H,{type:`secondary`,className:`fb-small`,children:t.leadCode||t.facebookLeadId})})]})},{title:`Facebook form`,dataIndex:`formName`,render:e=>e||`Unknown form`},{title:`Status`,dataIndex:`status`,render:e=>(0,o.jsx)(i.Tag,{children:e||`New Lead`})},{title:`Received`,dataIndex:`createdAt`,render:U}],Te=[{title:`When`,dataIndex:`reassignedAt`,render:U},{title:`Lead`,dataIndex:`leadCode`,render:(e,t)=>e||t.facebookLeadId||`—`},{title:`From → To`,render:(e,t)=>(0,o.jsxs)(`span`,{children:[t.fromName,` `,(0,o.jsx)(a.SwapOutlined,{}),` `,t.toName]})},{title:`Reason`,render:(e,t)=>(0,o.jsxs)(`div`,{children:[(0,o.jsx)(i.Tag,{children:W[t.reasonType]||`Other`}),(0,o.jsx)(`div`,{style:{fontSize:12},children:t.reason})]})},{title:`By`,dataIndex:`performedByName`}];return(0,o.jsxs)(`div`,{className:`fb-tab-body`,children:[(0,o.jsx)(H,{type:`secondary`,className:`fb-tab-intro`,children:`Automatic turns keep sending leads to a counsellor who is on leave. Move their open leads to someone else here.`}),se&&(0,o.jsx)(i.Alert,{type:`error`,showIcon:!0,title:`Could not load everything for this tab`,description:se,className:`fb-block`}),(0,o.jsxs)(`div`,{className:`fb-field-row`,children:[(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-reassign-from`,children:`From`}),(0,o.jsx)(i.Select,{id:`fb-reassign-from`,showSearch:!0,optionFilterProp:`label`,placeholder:`Choose a counsellor`,value:h||void 0,onChange:be,loading:p,notFoundContent:`No counsellor has open Facebook leads`,options:d.map(e=>({value:e.userId,label:`${e.name} — ${e.openLeads} open${e.isActive?``:` (inactive)`}`}))})]}),(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-reassign-form`,children:`Form`}),(0,o.jsx)(fe,{id:`fb-reassign-form`,rows:e,value:_,onChange:xe,minWidth:0})]})]}),h&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(`div`,{className:`fb-block`,children:[(0,o.jsxs)(i.Radio.Group,{value:E?`all`:`pick`,onChange:e=>{D(e.target.value===`all`),e.target.value===`all`&&T([])},children:[(0,o.jsx)(i.Radio.Button,{value:`pick`,children:`Choose leads`}),(0,o.jsxs)(i.Radio.Button,{value:`all`,children:[`All `,Y,` open lead`,Y===1?``:`s`]})]}),E&&Y>B&&(0,o.jsxs)(H,{type:`secondary`,className:`fb-hint-inline`,children:[`Moves `,B,` per run. Run again for the rest.`]})]}),(0,o.jsx)(i.Table,{size:`small`,rowKey:`id`,loading:b,columns:we,dataSource:v.leads,rowSelection:E?void 0:{selectedRowKeys:w,preserveSelectedRowKeys:!0,onChange:e=>T(e)},pagination:{current:S,pageSize:20,total:Y,showSizeChanger:!1,onChange:C},locale:{emptyText:`No open Facebook leads for this counsellor`},scroll:{x:640}}),(0,o.jsxs)(`div`,{className:`fb-reassign-fields`,children:[(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-reassign-to`,children:`To`}),(0,o.jsx)(i.Select,{id:`fb-reassign-to`,showSearch:!0,optionFilterProp:`label`,placeholder:`Choose an active counsellor`,value:O||void 0,onChange:k,options:ge,notFoundContent:`No other active counsellor available`})]}),(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-reassign-type`,children:`Reason type`}),(0,o.jsx)(i.Select,{id:`fb-reassign-type`,value:K,onChange:j,options:V})]}),(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-reassign-reason`,children:`Reason`}),(0,o.jsx)(i.Input.TextArea,{id:`fb-reassign-reason`,rows:2,maxLength:z,showCount:!0,value:M,onChange:e=>te(e.target.value),placeholder:`For example, on leave 3–7 Nov`,"aria-describedby":`fb-reassign-reason-hint`,status:M&&!_e?`error`:void 0}),!_e&&(0,o.jsxs)(`div`,{id:`fb-reassign-reason-hint`,className:`fb-hint`,children:[`At least `,R,` characters`]})]}),(0,o.jsxs)(`div`,{children:[(0,o.jsx)(i.Button,{type:`primary`,icon:(0,o.jsx)(a.SwapOutlined,{}),disabled:!ye,loading:ae,onClick:Ce,children:X?`Reassign ${X} lead${X===1?``:`s`}`:`Reassign`}),ve&&(0,o.jsx)(`div`,{className:`fb-hint`,role:`status`,children:ve})]})]})]}),(0,o.jsx)(i.Collapse,{ghost:!0,className:`fb-history-collapse`,items:[{key:`history`,label:`Reassignment history`,children:(0,o.jsx)(i.Table,{size:`small`,rowKey:`id`,loading:ue,columns:Te,dataSource:F.reassignments,pagination:{current:I,pageSize:10,total:Number(F.total||0),showSizeChanger:!1,onChange:le},locale:{emptyText:`No leads have been reassigned yet`},scroll:{x:720}})}]})]})}var{Text:Y}=i.Typography,X=e=>String(e?.userId||``),ge=50,Z=e=>{let t=e?new Date(e):null;return t&&!Number.isNaN(t.getTime())?t.toLocaleString():`—`},_e=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),ve={ready:{label:`Ready`,tone:`good`},needs_setup:{label:`Needs setup`,tone:`warn`},paused:{label:`Paused`,tone:`muted`},no_active:{label:`No active counsellor`,tone:`bad`},unknown_form:{label:`Unknown form`,tone:`muted`}},ye={inactive:`Inactive`,locked:`Account locked`,deleted:`Deleted`,not_counsellor:`No longer a counsellor`,unavailable:`Unavailable`,logged_out:`Not logged in`,on_leave:`On leave`,admin_disabled:`Switched off by admin`,at_cap:`At the open-lead limit`},be=e=>ye[e]||`Unavailable`,xe={meta_fetch:`Could not read the lead from Facebook`,lms_create:`Could not create the lead`,invalid_lead_fields:`The lead had unreadable details`,course_mapping:`Could not read the course for this form`,contact_lookup:`Could not check for a duplicate`,database_lookup:`Could not check for a duplicate`,distribution_lookup:`Could not find the counsellor list`,configuration_disabled:`Facebook import was switched off`,unassigned_audit:`Could not add the lead to the waiting list`,meta_forms:`Could not read the forms from Facebook`,mismatched_page_or_form:`The lead came from a different Facebook page or form`,mismatched_meta_form:`The lead came from a different Facebook page or form`},Se=e=>xe[e]||`Failed`,Ce=e=>_e(K[e])||`Waiting for setup`,we=e=>{if(!e||typeof e!=`object`)return null;let t=e.counsellorIds||e.counsellors;return Array.isArray(t)?t.map(e=>String(e?.userId??e?.legacyUserId??e)):null};function Te(e){let{area:t,action:n,before:r,after:i}=e||{},a=String(t||``).toLowerCase(),o=String(n||``).toLowerCase(),s=/delete|remove/.test(o),c=/create|add/.test(o)||!r;if(/retry/.test(o)||/failed/.test(a))return`Retried failed lead`;if(/mapping|course/.test(a)){if(s)return`Course removed`;let e=i?.courseName,t=(r?.courseId??r?.courseName)!==(i?.courseId??i?.courseName);return e&&(c||t)?`Course ${c?`set to`:`changed to`} ${e}`:typeof r?.isActive==`boolean`&&typeof i?.isActive==`boolean`&&r.isActive!==i.isActive?i.isActive?`Course turned on`:`Course turned off`:`Course changed`}if(/distribution|counsellor/.test(a)){if(s)return`Counsellors removed`;if(c)return`Counsellors set up`;if(typeof r?.isActive==`boolean`&&typeof i?.isActive==`boolean`&&r.isActive!==i.isActive)return i.isActive?`Resumed`:`Paused`;let e=we(r),t=we(i);return e&&t&&e.length===t.length&&[...e].sort().join()===[...t].sort().join()?`Order changed`:`Counsellors changed`}return`Setup changed`}function Ee({mapping:e,distribution:t,inFormsList:n=!0},r={}){let{forms:i=!0,mappings:a=!0,distributions:o=!0}=r;if(!a||!o)return null;if(i&&!n)return`unknown_form`;let s=t?.counsellors||[];return!e||!e.isActive||!t||!s.length?`needs_setup`:t.isActive===!1?`paused`:s.some(e=>e.isActive!==!1)?`ready`:`no_active`}function De(e){let t=e?.counsellors||[];if(!t.length)return``;let n=Math.max(t.findIndex(t=>X(t)===String(e.nextUserId||``)),0);return[...t.slice(n),...t.slice(0,n)].find(e=>e.isActive!==!1)?.name||``}function Oe(e,t,n){if(t===n||t<0||n<0||t>=e.length||n>=e.length)return e;let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}function ke(e,t){if(!t.length)return``;let n=(e?.counsellors||[]).map(X).filter(Boolean),r=String(e?.nextUserId||``);if(n.length===t.length&&n.every((e,n)=>e===t[n])&&t.includes(r))return r;let i=String(e?.lastAssignedUserId||``);if(!i&&n.includes(r)&&(i=n[(n.indexOf(r)-1+n.length)%n.length]),t.includes(i))return t[(t.indexOf(i)+1)%t.length];if(n.includes(i)){let e=n.indexOf(i);for(let r=1;r<=n.length;r++){let i=n[(e+r)%n.length];if(t.includes(i))return i}}return t.includes(r)?r:t[0]}async function Ae({mapping:e,distribution:t,saveMapping:n,saveDistribution:r}){let i={mappingSaved:!1,distributionSaved:!1,failedPart:``,error:null};if(e)try{await n(e.input,e.isEdit),i.mappingSaved=!0}catch(e){return{...i,failedPart:`mapping`,error:e}}if(t)try{await r(t.input,t.isEdit),i.distributionSaved=!0}catch(e){return{...i,failedPart:`distribution`,error:e}}return i}var je=e=>e.length<2?e[0]||``:`${e.slice(0,-1).join(`, `)} and ${e[e.length-1]}`;function Me(e){return e.length?e.length===1?`${e[0]} is inactive and will be skipped. Remove them or keep the place for when they return.`:`${je(e)} are inactive and will be skipped. Remove them or keep their places for when they return.`:``}function Ne({status:e}){let t=ve[e];return t?(0,o.jsxs)(i.Tag,{className:`fb-status fb-status--${t.tone}`,children:[(0,o.jsx)(`span`,{className:`fb-status-dot`,"aria-hidden":`true`}),t.label]}):(0,o.jsx)(Y,{type:`secondary`,children:`—`})}function Pe({number:e,title:t,aside:n}){return(0,o.jsxs)(`div`,{className:`fb-setup-heading`,children:[(0,o.jsxs)(`h3`,{children:[(0,o.jsx)(`span`,{className:`fb-setup-number`,"aria-hidden":`true`,children:e}),t]}),n&&(0,o.jsx)(`span`,{className:`fb-setup-aside`,children:n})]})}var Fe=(e,t)=>({base:{mapping:e||null,current:t||null},courseId:e?.courseId||void 0,mappingActive:e?.isActive??!0,orderedIds:(t?.counsellors||[]).map(X).filter(Boolean),enabled:t?.isActive!==!1});function Ie({open:e,row:t,mapping:n,current:s,courses:c=[],counsellors:l=[],limits:u,permissions:d={},section:f=`course`,onClose:p,onSaved:m,onReload:h,onAfterClose:g}){let[ee]=(0,r.useState)(()=>Fe(n,s)),[v,y]=(0,r.useState)(ee.base),[b,x]=(0,r.useState)(ee.courseId),[S,w]=(0,r.useState)(ee.mappingActive),[T,E]=(0,r.useState)(ee.orderedIds),[D,k]=(0,r.useState)(ee.enabled),[A,j]=(0,r.useState)(``),[M,te]=(0,r.useState)(!1),[ne,N]=(0,r.useState)(``),[re,ie]=(0,r.useState)(``),[ae,oe]=(0,r.useState)(null),[se,P]=(0,r.useState)(null),F=(0,r.useRef)(null),ce=(0,r.useRef)(null),I=(0,r.useRef)(null),le=(0,r.useRef)(!1),{canAdd:ue=!0,canEdit:L=!0}=d,R=v.mapping?L:ue,z=v.current?L:ue,B=!R&&!z,V=Number(u?.maxCounsellors)||ge,H=v.current?.counsellors,U=v.mapping,W=(0,r.useMemo)(()=>{let e=new Map(l.map(e=>[X(e),{...e,isActive:!0}]));return(H||[]).forEach(t=>{let n=X(t);e.has(n)||e.set(n,{...t,isActive:!1})}),e},[l,H]),G=(0,r.useCallback)(e=>W.get(e)?.name||`Unnamed counsellor`,[W]),K=(0,r.useMemo)(()=>new Set(T),[T]),q=T.map(e=>W.get(e)).filter(Boolean),de=[...l].filter(e=>!K.has(X(e))).sort((e,t)=>String(e.name).localeCompare(String(t.name))),fe=[...q,...de].filter(e=>`${e.name||``} ${e.email||``}`.toLowerCase().includes(A.trim().toLowerCase())),J=q.filter(e=>!e.isActive),pe=q.length-J.length,me=(v.current?.counsellors||[]).map(X).filter(Boolean),he=me.length!==T.length||me.some((e,t)=>e!==T[t]),Z=v.current?he||D!==(v.current.isActive!==!1):T.length>0,_e=v.mapping?String(b)!==String(v.mapping.courseId)||S!==v.mapping.isActive:!!b,ve=_e||Z,ye=ke(v.current,T),be=T.indexOf(ye),xe=(be<0?T:[...T.slice(be),...T.slice(0,be)]).find(e=>W.get(e)?.isActive)||``,Se=W.get(xe)?.name||`No one yet`,Ce=(0,r.useMemo)(()=>{let e=c.map(e=>({value:e.courseId,label:e.courseName}));return U?.courseId&&!e.some(e=>e.value===U.courseId)&&e.unshift({value:U.courseId,label:U.courseName||`Course no longer available`}),e},[c,U]),we=(e,t)=>{let n=Fe(e,t);y(n.base),x(n.courseId),w(n.mappingActive),E(n.orderedIds),k(n.enabled)},Te=(e,t)=>{E(n=>t?[...n.filter(t=>t!==e),e]:n.filter(t=>t!==e)),ie(t?`${G(e)} added to the list`:`${G(e)} removed from the list`)},Ee=(e,t)=>{let n=T.indexOf(e),r=n+(t===`up`?-1:1);n<0||r<0||r>=T.length||(I.current={id:e,direction:t},E(e=>Oe(e,n,r)),ie(`${G(e)} moved to place ${r+1} of ${T.length}`))};(0,r.useLayoutEffect)(()=>{let e=I.current;if(!e)return;I.current=null;let t=[...F.current?.querySelectorAll(`[data-move-id]`)||[]].filter(t=>t.dataset.moveId===e.id&&!t.disabled);(t.find(t=>t.dataset.moveDirection===e.direction)||t[0])?.focus()},[T]);let De=(e,t)=>{P(t),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t)},je=(e,t,n)=>{!n||!se||se===t||(e.preventDefault(),oe(t))},Ne=()=>{P(null),oe(null)},Ie=e=>{let t=se;Ne(),!(!K.has(t)||!K.has(e)||t===e)&&(E(n=>Oe(n,n.indexOf(t),n.indexOf(e))),ie(`${G(t)} moved`))},Q=()=>{if(!M){if(!ve){p();return}le.current||(le.current=!0,i.Modal.confirm({title:`Discard your changes?`,content:`Your changes to this form have not been saved.`,okText:`Discard changes`,okType:`danger`,cancelText:`Keep editing`,autoFocusButton:`cancel`,onOk:()=>{le.current=!1,p()},onCancel:()=>{le.current=!1}}))}},$=(0,o.jsxs)(`div`,{className:`fb-setup-footer`,children:[ne&&(0,o.jsx)(i.Alert,{type:`error`,showIcon:!0,title:ne,className:`fb-setup-problem`}),(0,o.jsxs)(`div`,{className:`fb-setup-footer-actions`,children:[(0,o.jsx)(i.Button,{onClick:Q,disabled:M,children:B?`Close`:`Cancel`}),!B&&(0,o.jsx)(i.Button,{type:`primary`,loading:M,disabled:!ve,onClick:async()=>{if(N(``),Z&&!T.length){N(`Choose at least one counsellor. To stop using counsellors on this form, use Remove distribution in the form menu.`);return}if(Z&&T.length>V){N(`You can choose up to ${V} counsellors. You have chosen ${T.length}.`);return}te(!0);let e=await Ae({mapping:_e?{input:{formId:t.formId,courseId:b,isActive:S},isEdit:!!v.mapping}:null,distribution:Z?{input:{formId:t.formId,counsellorIds:T,isActive:D,version:v.current?.version??0},isEdit:!!v.current}:null,saveMapping:_,saveDistribution:O});if(!e.error){te(!1),i.message.success(`Form setup saved`),m?.(),p();return}let n=e.mappingSaved?`The course was saved. `:``;if(e.failedPart===`mapping`)N(`Nothing was saved. The course could not be saved: ${C(e.error)}`);else if(e.error?.status===409)try{let e=await h();we(e?.mapping,e?.current),N(`${n}Someone else changed these counsellors while you were editing, so yours were not saved. The latest list is now showing. Check it and save again.`)}catch{N(`${n}Someone else changed these counsellors while you were editing, so yours were not saved. The latest list could not be loaded. Close this panel and open it again.`)}else e.mappingSaved&&y(e=>({...e,mapping:{...e.mapping||{},formId:t.formId,courseId:b,isActive:S,courseName:Ce.find(e=>e.value===b)?.label||e.mapping?.courseName||``}})),N(`${n}The counsellors were not saved: ${C(e.error)}`);e.mappingSaved&&m?.(),te(!1)},children:`Save`})]})]}),Le=!!(v.mapping||v.current);return(0,o.jsxs)(i.Drawer,{open:e,size:560,rootClassName:`fb-setup-drawer`,keyboard:!0,mask:{closable:!0},title:(0,o.jsxs)(`span`,{className:`fb-setup-title`,children:[Le?`Edit`:`Set up`,` form`]}),onClose:Q,footer:$,afterOpenChange:e=>{e&&f===`counsellors`&&ce.current?.scrollIntoView?.({block:`start`}),e||g?.()},children:[(0,o.jsxs)(`div`,{className:`fb-setup-form-name`,children:[(0,o.jsx)(Y,{strong:!0,children:t?.formName}),(0,o.jsxs)(Y,{type:`secondary`,className:`fb-small`,copyable:{text:t?.formId,tooltips:[`Copy Form ID`,`Copied`]},children:[`Form ID: `,t?.formId]})]}),B&&(0,o.jsx)(i.Alert,{type:`info`,showIcon:!0,title:`You can view this setup, but your role cannot change it.`,className:`fb-block`}),(0,o.jsxs)(`section`,{className:`fb-setup-section`,"aria-label":`Course`,children:[(0,o.jsx)(Pe,{number:`1`,title:`Course`}),(0,o.jsx)(i.Select,{className:`fb-setup-select`,showSearch:!0,optionFilterProp:`label`,"aria-label":`Course`,placeholder:`Choose a course`,value:b,onChange:x,options:Ce,disabled:!R||M,notFoundContent:`No matching courses`}),b?(0,o.jsxs)(`label`,{className:`fb-setup-toggle`,children:[(0,o.jsxs)(`span`,{children:[(0,o.jsx)(`span`,{className:`fb-setup-toggle-title`,children:`Use this course for new leads`}),(0,o.jsx)(`span`,{className:`fb-hint`,children:`When off, new leads still come in, but without a course.`})]}),(0,o.jsx)(i.Switch,{"aria-label":`Use this course for new leads`,checked:S,onChange:w,disabled:!R||M})]}):(0,o.jsx)(`div`,{className:`fb-hint`,children:`No course yet. You can still choose counsellors, and leads will arrive without a course until you pick one.`})]}),(0,o.jsxs)(`section`,{className:`fb-setup-section`,"aria-label":`Counsellors and order`,ref:ce,children:[(0,o.jsx)(Pe,{number:`2`,title:`Counsellors and order`,aside:`${pe} active${J.length?`, ${J.length} inactive`:``}`}),J.length>0&&(0,o.jsx)(i.Alert,{type:`warning`,showIcon:!0,className:`fb-block`,title:Me(J.map(e=>e.name||`Unnamed counsellor`)),description:z&&(0,o.jsx)(`div`,{className:`fb-inactive-actions`,children:J.map(e=>(0,o.jsxs)(i.Button,{size:`small`,disabled:M,onClick:()=>Te(X(e),!1),children:[`Remove `,e.name||`Unnamed counsellor`]},X(e)))})}),(0,o.jsx)(i.Input,{allowClear:!0,value:A,prefix:(0,o.jsx)(a.SearchOutlined,{"aria-hidden":`true`}),className:`fb-block`,placeholder:`Search counsellors`,"aria-label":`Search counsellors`,onChange:e=>j(e.target.value)}),(0,o.jsx)(`div`,{className:`fb-dist-draggable-list`,ref:F,children:fe.length===0?(0,o.jsx)(i.Empty,{description:l.length||T.length?`No matching counsellors`:`No active counsellors to choose from`}):fe.map(e=>{let t=X(e),n=e.name||`Unnamed counsellor`,r=K.has(t),s=T.indexOf(t);return(0,o.jsxs)(`div`,{"data-person-row":t,className:`fb-dist-unified-row ${r?`selected`:``} ${ae===t?`drag-over`:``}`,draggable:r&&!M&&z,onDragStart:e=>De(e,t),onDragOver:e=>je(e,t,r),onDrop:e=>{e.preventDefault(),Ie(t)},onDragEnd:Ne,children:[(0,o.jsx)(`span`,{className:`fb-dist-check`,children:(0,o.jsx)(i.Checkbox,{"aria-label":`Include ${n}`,checked:r,disabled:M||!z,onChange:e=>Te(t,e.target.checked)})}),(0,o.jsx)(`span`,{className:`fb-dist-grip ${r?``:`placeholder`}`,"aria-hidden":`true`,children:(0,o.jsx)(a.DragOutlined,{})}),(0,o.jsx)(`span`,{className:`fb-dist-rank`,"aria-hidden":!r,children:r?s+1:``}),(0,o.jsxs)(`div`,{className:`fb-dist-person-name`,children:[(0,o.jsx)(Y,{strong:r,children:n}),e.email&&(0,o.jsx)(Y,{type:`secondary`,className:`fb-small`,ellipsis:!0,children:e.email})]}),!e.isActive&&(0,o.jsxs)(i.Tag,{className:`fb-status fb-status--bad`,children:[(0,o.jsx)(`span`,{className:`fb-status-dot`,"aria-hidden":`true`}),`Inactive`]}),r&&(0,o.jsxs)(`span`,{className:`fb-dist-order-buttons`,children:[(0,o.jsx)(i.Tooltip,{title:`Move ${n} up`,children:(0,o.jsx)(i.Button,{type:`text`,icon:(0,o.jsx)(a.ArrowUpOutlined,{"aria-hidden":`true`}),"aria-label":`Move ${n} up`,"data-move-id":t,"data-move-direction":`up`,disabled:s<=0||M||!z,onClick:()=>Ee(t,`up`)})}),(0,o.jsx)(i.Tooltip,{title:`Move ${n} down`,children:(0,o.jsx)(i.Button,{type:`text`,icon:(0,o.jsx)(a.ArrowDownOutlined,{"aria-hidden":`true`}),"aria-label":`Move ${n} down`,"data-move-id":t,"data-move-direction":`down`,disabled:s>=T.length-1||M||!z,onClick:()=>Ee(t,`down`)})})]})]},t)})}),(0,o.jsx)(`div`,{className:`fb-sr-only`,"aria-live":`polite`,children:re}),(0,o.jsxs)(`div`,{className:`fb-dist-next-line`,children:[(0,o.jsx)(a.CheckCircleOutlined,{"aria-hidden":`true`}),(0,o.jsxs)(`span`,{children:[he?`Next after save`:`Next in saved order`,`: `,(0,o.jsx)(`strong`,{children:Se})]})]}),(0,o.jsx)(`div`,{className:`fb-hint`,children:`Changes apply to future leads only. Turns carry on from the last person who got a lead, and leads people already have stay with them.`})]}),(0,o.jsxs)(`section`,{className:`fb-setup-section`,"aria-label":`Automatic turns`,children:[(0,o.jsx)(Pe,{number:`3`,title:`Automatic turns`}),(0,o.jsxs)(`label`,{className:`fb-setup-toggle`,children:[(0,o.jsxs)(`span`,{children:[(0,o.jsx)(`span`,{className:`fb-setup-toggle-title`,children:`Send leads to this form automatically`}),(0,o.jsx)(`span`,{className:`fb-hint`,children:`When paused, new leads wait until you turn this back on.`})]}),(0,o.jsx)(i.Switch,{"aria-label":`Send leads to this form automatically`,checked:D,onChange:k,checkedChildren:`On`,unCheckedChildren:`Paused`,disabled:!z||M})]})]})]})}function Q(e,t){let[n,i]=(0,r.useState)(0),[a,o]=(0,r.useState)({data:null,error:``,settled:null}),s=(0,r.useMemo)(()=>({load:e,refreshKey:t,tick:n}),[e,t,n]);(0,r.useEffect)(()=>{let e=!0;return s.load().then(t=>{e&&o({data:t,error:``,settled:s})}).catch(t=>{e&&o(e=>({...e,error:C(t),settled:s}))}),()=>{e=!1}},[s]);let c=(0,r.useCallback)(()=>i(e=>e+1),[]),l=a.settled!==s;return{data:a.data,loading:l,error:l?``:a.error,reload:c}}function $({title:e,resource:t}){return t.error?(0,o.jsx)(i.Alert,{type:`error`,showIcon:!0,className:`fb-block`,title:e,description:`${t.error}${t.data?` Showing the last information we could load.`:``}`,action:(0,o.jsx)(i.Button,{size:`small`,onClick:t.reload,children:`Try again`})}):null}var Le=(e,t)=>t.formName||e.find(e=>e.formId===String(t.formId))?.formName||`Unknown form`,Re=(e,t)=>e.find(e=>e.formId===String(t))?.mapping?.courseName||``;function ze({lead:e,details:t}){let n=t?.[e.facebookLeadId];return(0,o.jsxs)(`span`,{className:`fb-lead-cell`,children:[(0,o.jsx)(`span`,{className:`fb-lead-cell__name`,children:n?.name||(n?.error?`Details unavailable`:`—`)}),(0,o.jsxs)(`span`,{className:`fb-lead-cell__id`,children:[`Lead `,e.facebookLeadId]})]})}var Be=e=>[{title:`Phone`,key:`phone`,render:(t,n)=>e?.[n.facebookLeadId]?.phone||`—`},{title:`Email`,key:`email`,render:(t,n)=>e?.[n.facebookLeadId]?.email||`—`},{title:`City`,key:`city`,render:(t,n)=>e?.[n.facebookLeadId]?.city||`—`}];function Ve({rows:e,resource:t,unit:n,describe:r,renderBody:a,emptyText:s,fallback:c}){let l=t.data?.groups;return Array.isArray(l)?l.length?(0,o.jsx)(i.Collapse,{accordion:!0,className:`fb-groups`,expandIconPlacement:`end`,items:l.map(t=>{let s=t.formName||Le(e,t),c=Re(e,t.formId);return{key:String(t.formId),label:(0,o.jsxs)(`span`,{className:`fb-group__head`,children:[(0,o.jsx)(`span`,{className:`fb-group__title`,children:s}),(0,o.jsx)(`span`,{className:`fb-group__course`,children:c?`Course: ${c}`:`No course mapped`})]}),extra:(0,o.jsxs)(`span`,{className:`fb-group__meta`,children:[r(t),(0,o.jsxs)(i.Tag,{className:`fb-group__count`,"aria-label":`${t.count} ${n}`,children:[t.count,` `,n]})]}),children:a(t)}})}):(0,o.jsx)(i.Empty,{image:i.Empty.PRESENTED_IMAGE_SIMPLE,description:t.loading?` `:s}):t.loading&&!t.data?(0,o.jsx)(i.Table,{size:`small`,loading:!0,dataSource:[],columns:[]}):c}function He({rows:e,formId:t,status:n,refreshKey:a,showForm:s}){let[c,l]=(0,r.useState)(1),u=Q((0,r.useCallback)(()=>j({status:n,page:c,limit:20,formId:t,details:!0}),[n,c,t]),a),d=u.data?.details,f=[...s?[{title:`Form`,dataIndex:`formName`,render:(t,n)=>Le(e,n)}]:[],{title:`Lead`,dataIndex:`facebookLeadId`,render:(e,t)=>(0,o.jsx)(ze,{lead:t,details:d})},...Be(d),{title:`Why it is waiting`,dataIndex:`reason`,render:Ce},{title:`Status`,dataIndex:`status`,render:e=>e===`unassigned`?`Waiting`:e===`resolved`?`Sorted`:`—`},{title:`First seen`,dataIndex:`firstSeenAt`,render:Z},...n===`unassigned`?[]:[{title:`Sorted at`,dataIndex:`resolvedAt`,render:Z}]];return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)($,{title:`Could not load waiting leads`,resource:u}),(0,o.jsx)(i.Table,{size:`small`,rowKey:e=>String(e.id||`${e.facebookLeadId}-${e.formId}`),loading:u.loading,dataSource:u.data?.leads||[],columns:f,scroll:{x:900},locale:{emptyText:u.loading||u.error?` `:`No leads are waiting.`},pagination:{current:c,pageSize:20,total:Number(u.data?.total||0),showSizeChanger:!1,hideOnSinglePage:!0,onChange:l}})]})}function Ue({rows:e,formId:t,refreshKey:n,showForm:a,canEdit:s,onChanged:c}){let[l,u]=(0,r.useState)(1),d=Q((0,r.useCallback)(()=>oe({page:l,limit:20,formId:t,details:!0}),[l,t]),n),f=d.reload,p=d.data?.details,m=t=>{i.Modal.confirm({title:`Try this lead again?`,content:(0,o.jsxs)(`span`,{children:[`We will try to bring in lead `,(0,o.jsx)(`strong`,{children:t.facebookLeadId}),` from `,(0,o.jsx)(`strong`,{children:Le(e,t)}),` again.`]}),okText:`Retry`,cancelText:`Cancel`,autoFocusButton:`cancel`,onOk:async()=>{try{await se(t.facebookLeadId),i.message.success(`This lead will be tried again`)}catch(e){i.message.error(e?.status===409?`This lead is no longer failed. The list has been updated.`:C(e))}f(),c?.()}})},h=[...a?[{title:`Form`,dataIndex:`formName`,render:(t,n)=>Le(e,n)}]:[],{title:`Lead`,dataIndex:`facebookLeadId`,render:(e,t)=>(0,o.jsx)(ze,{lead:t,details:p})},...Be(p).slice(0,2),{title:`What went wrong`,dataIndex:`reason`,render:Se},{title:`Tries`,dataIndex:`attempts`,width:72,render:e=>e??`—`},{title:`When`,dataIndex:`lastFailedAt`,render:(e,t)=>Z(e||t.firstSeenAt)},{title:``,key:`retry`,width:96,render:(e,t)=>(0,o.jsx)(i.Tooltip,{title:s?``:`You don't have permission to retry leads`,children:(0,o.jsx)(`span`,{children:(0,o.jsx)(i.Button,{size:`small`,className:`fb-inline-btn`,disabled:!s,"aria-label":`Retry lead ${t.facebookLeadId}`,onClick:()=>m(t),children:`Retry`})})})}];return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)($,{title:`Could not load failed leads`,resource:d}),(0,o.jsx)(i.Table,{size:`small`,rowKey:e=>String(e.facebookLeadId),loading:d.loading,dataSource:d.data?.leads||[],columns:h,scroll:{x:860},locale:{emptyText:d.loading||d.error?` `:`No failed leads.`},pagination:{current:l,pageSize:20,total:Number(d.data?.total||0),showSizeChanger:!1,hideOnSinglePage:!0,onChange:u}})]})}var We=(e,t)=>Object.entries(e||{}).map(([e,n])=>(0,o.jsxs)(i.Tag,{className:`fb-group__reason`,children:[t(e),n>1?` · ${n}`:``]},e));function Ge({rows:e=[],canEdit:t=!0,refreshKey:n=0,onChanged:a}){let[s,c]=(0,r.useState)(``),[l,u]=(0,r.useState)(`unassigned`),d=(0,r.useCallback)(()=>j({status:l,formId:s,groupBy:`form`}),[l,s]),f=(0,r.useCallback)(()=>oe({formId:s,groupBy:`form`}),[s]),p=Q(d,n),m=Q(f,n),h=(e,t)=>Array.isArray(e.data?.groups)?e.data.groups.reduce((e,t)=>e+Number(t.count||0),0):e.data?.[t],g=h(p,l===`unassigned`?`unassignedCount`:`total`),_=h(m,`failedCount`)??m.data?.total;return(0,o.jsxs)(`div`,{className:`fb-tab-body`,children:[(0,o.jsx)(`div`,{className:`fb-toolbar`,children:(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-attention-form`,children:`Form`}),(0,o.jsx)(fe,{id:`fb-attention-form`,rows:e,value:s,onChange:c})]})}),(0,o.jsxs)(`div`,{className:`fb-subhead`,children:[(0,o.jsxs)(`h4`,{children:[`Waiting leads`,g===void 0?``:` (${g})`]}),(0,o.jsx)(i.Select,{"aria-label":`Show waiting leads`,value:l,className:`fb-subhead-select`,onChange:u,options:[{value:`unassigned`,label:`Waiting`},{value:`resolved`,label:`Sorted`},{value:`all`,label:`All`}]})]}),(0,o.jsx)($,{title:`Could not load waiting leads`,resource:p}),(0,o.jsx)(Ve,{rows:e,resource:p,unit:l===`unassigned`?`waiting`:`leads`,emptyText:`No leads are waiting.`,describe:e=>(0,o.jsxs)(o.Fragment,{children:[We(e.reasons,Ce),e.latest?(0,o.jsxs)(`span`,{className:`fb-group__latest`,children:[`Latest `,Z(e.latest)]}):null]}),renderBody:t=>(0,o.jsx)(He,{rows:e,formId:String(t.formId),status:l,refreshKey:n}),fallback:(0,o.jsx)(He,{rows:e,formId:s,status:l,refreshKey:n,showForm:!0})}),(0,o.jsx)(`div`,{className:`fb-subhead`,children:(0,o.jsxs)(`h4`,{children:[`Failed leads`,_===void 0?``:` (${_})`]})}),(0,o.jsx)($,{title:`Could not load failed leads`,resource:m}),(0,o.jsx)(Ve,{rows:e,resource:m,unit:`failed`,emptyText:`No failed leads.`,describe:e=>(0,o.jsxs)(o.Fragment,{children:[We(e.reasons,Se),e.latest?(0,o.jsxs)(`span`,{className:`fb-group__latest`,children:[`Latest `,Z(e.latest)]}):null]}),renderBody:r=>(0,o.jsx)(Ue,{rows:e,formId:String(r.formId),refreshKey:n,canEdit:t,onChanged:a}),fallback:(0,o.jsx)(Ue,{rows:e,formId:s,refreshKey:n,canEdit:t,onChanged:a,showForm:!0})})]})}function Ke({rows:e,formId:t,refreshKey:n,showForm:a}){let[s,c]=(0,r.useState)(1),l=Q((0,r.useCallback)(()=>A({page:s,limit:20,formId:t}),[s,t]),n),u=[...a?[{title:`Form`,dataIndex:`formName`,render:(t,n)=>Le(e,n)}]:[],{title:`Lead ID`,dataIndex:`facebookLeadId`},{title:`Skipped counsellor`,dataIndex:`skippedCounsellorName`,render:e=>e||`Unknown counsellor`},{title:`Reason`,dataIndex:`reason`,render:be},{title:`Went to`,dataIndex:`assignedToName`,render:e=>e||`—`},{title:`When`,dataIndex:`skippedAt`,render:Z}];return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)($,{title:`Could not load skipped counsellors`,resource:l}),(0,o.jsx)(i.Table,{size:`small`,rowKey:e=>String(e.id||`${e.facebookLeadId}-${e.skippedCounsellorLegacyId}`),loading:l.loading,dataSource:l.data?.skips||[],columns:u,scroll:{x:860},locale:{emptyText:l.loading||l.error?` `:`No one has been skipped yet.`},pagination:{current:s,pageSize:20,total:Number(l.data?.total||0),showSizeChanger:!1,hideOnSinglePage:!0,onChange:c}})]})}function qe({rows:e=[],refreshKey:t=0}){let[n,i]=(0,r.useState)(``),a=Q((0,r.useCallback)(()=>A({formId:n,groupBy:`form`}),[n]),t);return(0,o.jsxs)(`div`,{className:`fb-tab-body`,children:[(0,o.jsx)(`div`,{className:`fb-toolbar`,children:(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-skips-form`,children:`Form`}),(0,o.jsx)(fe,{id:`fb-skips-form`,rows:e,value:n,onChange:i})]})}),(0,o.jsx)($,{title:`Could not load skipped counsellors`,resource:a}),(0,o.jsx)(Ve,{rows:e,resource:a,unit:`skips`,emptyText:`No one has been skipped yet.`,describe:e=>(0,o.jsxs)(o.Fragment,{children:[e.people?.length?(0,o.jsxs)(`span`,{className:`fb-group__people`,children:[`Skipped: `,e.people.join(`, `)]}):null,We(e.reasons,be)]}),renderBody:n=>(0,o.jsx)(Ke,{rows:e,formId:String(n.formId),refreshKey:t}),fallback:(0,o.jsx)(Ke,{rows:e,formId:n,refreshKey:t,showForm:!0})})]})}function Je({rows:e=[],refreshKey:t=0}){let[n,a]=(0,r.useState)(``),[s,c]=(0,r.useState)(1),l=Q((0,r.useCallback)(()=>P({page:s,limit:20,formId:n}),[s,n]),t),u=[{title:`When`,dataIndex:`at`,width:190,render:Z},{title:`Form`,dataIndex:`formName`,render:(t,n)=>Le(e,n)},{title:`What changed`,key:`change`,render:(e,t)=>Te(t)},{title:`By`,dataIndex:`performedByName`,render:e=>e||`—`}];return(0,o.jsxs)(`div`,{className:`fb-tab-body`,children:[(0,o.jsx)(`div`,{className:`fb-toolbar`,children:(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-history-form`,children:`Form`}),(0,o.jsx)(fe,{id:`fb-history-form`,rows:e,value:n,onChange:e=>{a(e),c(1)}})]})}),(0,o.jsx)($,{title:`Could not load history`,resource:l}),(0,o.jsx)(i.Table,{size:`small`,rowKey:e=>String(e.id||`${e.formId}-${e.at}`),loading:l.loading,dataSource:l.data?.history||[],columns:u,scroll:{x:720},locale:{emptyText:l.loading||l.error?` `:`No setup changes yet. They will appear here when someone changes a form.`},pagination:{current:s,pageSize:20,total:Number(l.data?.total||0),showSizeChanger:!1,hideOnSinglePage:!0,onChange:c}})]})}var{Title:Ye,Text:Xe}=i.Typography;function Ze({icon:e,title:t,subtitle:n,actions:r,crumbs:a=[],onHome:s}){return(0,o.jsxs)(`div`,{className:`cc-settings-header`,children:[s?(0,o.jsx)(i.Breadcrumb,{className:`cc-settings-crumbs`,items:[{title:(0,o.jsx)(`a`,{onClick:e=>{e.preventDefault(),s()},href:`?`,children:`Settings`})},...a.map(e=>({title:e})),{title:t}]}):null,(0,o.jsxs)(`div`,{className:`cc-settings-header__row`,children:[(0,o.jsxs)(`div`,{className:`cc-settings-header__who`,children:[e?(0,o.jsx)(`span`,{className:`cc-settings-icon-tile`,"aria-hidden":`true`,children:e}):null,(0,o.jsxs)(`div`,{style:{minWidth:0},children:[(0,o.jsx)(Ye,{level:3,className:`cc-settings-header__title`,children:t}),n?(0,o.jsx)(Xe,{type:`secondary`,className:`cc-settings-header__sub`,children:n}):null]})]}),r?(0,o.jsx)(i.Space,{wrap:!0,className:`cc-settings-header__actions`,children:r}):null]})]})}function Qe({items:e}){return(0,o.jsx)(`div`,{className:`cc-settings-tiles`,children:e.filter(Boolean).map(e=>(0,o.jsxs)(`div`,{className:`cc-settings-tile is-${e.tone||`pink`}`,children:[e.icon?(0,o.jsx)(`span`,{className:`cc-settings-tile__icon`,"aria-hidden":`true`,children:e.icon}):null,(0,o.jsxs)(`div`,{style:{minWidth:0},children:[(0,o.jsx)(`div`,{className:`cc-settings-tile__label`,children:e.label}),(0,o.jsx)(`div`,{className:`cc-settings-tile__value`,children:e.value??`–`}),e.sub?(0,o.jsx)(`div`,{className:`cc-settings-tile__sub`,children:e.sub}):null]})]},e.key))})}function $e({tone:e=`grey`,icon:t,children:n}){return(0,o.jsxs)(`span`,{className:`cc-settings-pill is-${e}`,children:[t,n]})}function et({name:e}){let t=String(e||``).trim().split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0].toUpperCase()).join(``)||`?`;return(0,o.jsx)(`span`,{className:`cc-settings-initials`,"aria-hidden":`true`,children:t})}function tt(e,t){let n=Number(e)||0,r=Number(t);return n<=0||!Number.isFinite(r)?0:Math.floor(n*Math.min(1,Math.max(0,r)))}function nt(e){if(e==null||e===``)return e;let t=Number(e);return Number.isFinite(t)?Math.round(t*100):e}function rt(e){if(e==null||e===``)return e;let t=Number(e);return Number.isFinite(t)?Math.round(t)/100:e}function it(e={},t={}){let n=Number(e.cap??t.openLeadCap??0)||0,r=Number(e.untouched??0)||0,i=e.refillAt??tt(n,t.refillAtRatio??.5);if(n<=0)return{text:String(r),percent:0,tone:`grey`,hint:`No limit`,cap:n,untouched:r,refillAt:i,room:null};let a=Math.min(100,Math.round(r/n*100)),o=`${r} / ${n}`;return r>=n?{text:o,percent:a,tone:`red`,hint:`Full · refills at ${i}`,cap:n,untouched:r,refillAt:i,room:0}:e.waitingForRefill?{text:o,percent:a,tone:`amber`,hint:`Waiting · refills at ${i}`,cap:n,untouched:r,refillAt:i,room:0}:{text:o,percent:a,tone:`green`,hint:`Can take ${n-r} more`,cap:n,untouched:r,refillAt:i,room:n-r}}var at={assigned:{label:`Lead assigned`,tone:`blue`},capped:{label:`Reached limit`,tone:`amber`},reset:{label:`Quota refilled (reset)`,tone:`green`}};function ot(e={}){let t=Number(e.cap)||0,n=Number(e.untouchedBefore)||0,r=t>0?` of ${t}`:``;switch(e.event){case`assigned`:return`${e.formName?`${e.formName} · `:``}untouched ${n} → ${n+1}${r}`;case`capped`:return t>0?`Holds ${n}${r} untouched · gets no new lead until ${e.refillAt??0} or fewer`:`Holds ${n} untouched`;case`reset`:return t>0?`Untouched fell to ${n}${r} · can take ${Math.max(0,t-n)} more`:`Untouched fell to ${n}`;default:return`–`}}var{Text:st,Paragraph:ct}=i.Typography,lt={eligible:{label:`Active – Eligible`,color:`green`},logged_out:{label:`Logged Out – Not Eligible`,color:`default`},waiting_for_login:{label:`Waiting for Login`,color:`blue`},on_leave:{label:`On Leave – Skipped`,color:`orange`},admin_disabled:{label:`Admin Disabled – Skipped`,color:`red`},at_cap:{label:`At open-lead limit – Skipped`,color:`gold`},inactive:{label:`Inactive user – Skipped`,color:`red`},past_day:{label:`Past day`,color:`default`}},ut={awaiting_cutoff:`Waiting for cut-off`,no_active_counsellor:`Waiting for a counsellor who is online and under the open-lead limit`,distribution_not_configured:`Form has no counsellor list`,distribution_disabled:`Form distribution is switched off`},dt=(e,t=`Not recorded`)=>e?(0,s.default)(e).format(`h:mm A`):t,ft=(e,t=`Not recorded`)=>e?(0,s.default)(e).format(`D MMM, h:mm A`):t,pt=e=>{if(!e)return`Not recorded`;let t=Math.max(0,(0,s.default)().diff((0,s.default)(e),`minute`));return t<60?`${t} min`:`${Math.floor(t/60)} h ${t%60} min`};function mt(e,t){let[n,i]=(0,r.useState)({loading:!0}),[a,o]=(0,r.useState)(0);return(0,r.useEffect)(()=>{let t=!0;return e().then(e=>t&&i({loading:!1,data:e}),e=>t&&i({loading:!1,error:C(e,`This could not be loaded.`)})),()=>{t=!1}},[a,...t]),[n,()=>{i(e=>({...e,loading:!0})),o(e=>e+1)}]}var ht=({text:e,onRetry:t})=>(0,o.jsx)(i.Alert,{type:`error`,showIcon:!0,message:e,action:(0,o.jsx)(i.Button,{size:`small`,onClick:t,children:`Try again`})});function gt({canEdit:e=!1}){let[t,n]=(0,r.useState)(null),[c,l]=mt(()=>ce(t?t.format(`YYYY-MM-DD`):``),[t]),[u,d]=(0,r.useState)(null),[f,p]=(0,r.useState)(``),m=c.data??{},h=m.summary??{},g=!t||m.day===m.today,_=Number(m.settings?.openLeadCap??0)||0,ee=h.refillAt??tt(_,m.settings?.refillAtRatio??.5),v=async(e,t)=>{p(`t${e.legacyUserId}`);try{await ue(e.legacyUserId,t,t?``:`Disabled by admin`),i.message.success(`${e.name} ${t?`will receive new leads again`:`will not receive new leads`}`),l()}catch(e){i.message.error(C(e))}finally{p(``)}},y=[{title:`Counsellor`,key:`name`,render:(e,t)=>(0,o.jsxs)(i.Space,{direction:`vertical`,size:0,children:[(0,o.jsx)(st,{strong:!0,children:t.name}),(0,o.jsx)(st,{type:`secondary`,style:{fontSize:12},children:(t.forms??[]).join(`, `)})]})},{title:`First login`,dataIndex:`firstLoginAt`,render:e=>dt(e,`Not logged in today`),sorter:(e,t)=>String(e.firstLoginAt??``).localeCompare(String(t.firstLoginAt??``))},{title:`Last seen / logout`,key:`seen`,render:(e,t)=>t.loggedOutAt&&(!t.lastSeenAt||t.loggedOutAt>t.lastSeenAt)?`Logged out ${dt(t.loggedOutAt)}`:dt(t.lastSeenAt,`Not seen today`)},{title:`Status`,dataIndex:`status`,render:e=>(0,o.jsx)(i.Tag,{color:lt[e]?.color,children:lt[e]?.label??e}),filters:Object.entries(lt).map(([e,t])=>({value:e,text:t.label})),onFilter:(e,t)=>t.status===e},{title:`Untouched now`,dataIndex:`untouched`,sorter:(e,t)=>(e.untouched??0)-(t.untouched??0),render:(e,t)=>{let n=it(t,m.settings);return(0,o.jsx)(i.Tooltip,{title:`Untouched leads this counsellor holds / the most one counsellor may hold`,children:(0,o.jsxs)(`div`,{className:`ld-quota`,children:[(0,o.jsx)(`span`,{className:`ld-quota__text is-${n.tone}`,children:n.text}),n.cap>0?(0,o.jsx)(i.Progress,{percent:n.percent,size:`small`,showInfo:!1,strokeColor:`var(--ld-tone-${n.tone})`}):null,(0,o.jsx)(`span`,{className:`ld-quota__hint`,children:n.hint})]})})}},{title:`Assigned today`,dataIndex:`assigned`,align:`right`,sorter:(e,t)=>e.assigned-t.assigned,render:e=>(0,o.jsx)(`span`,{className:`ld-num`,children:e??0})},{title:`Resets today`,dataIndex:`resetsToday`,align:`right`,sorter:(e,t)=>(e.resetsToday??0)-(t.resetsToday??0),render:e=>e?(0,o.jsx)($e,{tone:`green`,icon:(0,o.jsx)(a.SyncOutlined,{}),children:e}):(0,o.jsx)(`span`,{className:`ld-muted`,children:`0`})},{title:`Total since start`,dataIndex:`totalAssignedSinceStart`,align:`right`,sorter:(e,t)=>(e.totalAssignedSinceStart??0)-(t.totalAssignedSinceStart??0),render:e=>e==null?`Not counted yet`:(0,o.jsx)(`span`,{className:`ld-num`,children:e})},{title:`Target`,dataIndex:`target`,align:`right`},{title:`Progress`,key:`progress`,width:140,render:(e,t)=>(0,o.jsx)(i.Progress,{percent:t.target?Math.min(100,Math.round(t.assigned/t.target*100)):0,size:`small`,showInfo:!1})},{title:`Difference`,dataIndex:`difference`,align:`right`,render:(e,t)=>t.status===`eligible`&&e>0?(0,o.jsxs)(st,{type:`warning`,children:[e,` behind`]}):t.status===`eligible`?`On target`:`Not in today's share`},...e&&g?[{title:``,key:`act`,width:210,render:(e,t)=>t.status===`inactive`?null:(0,o.jsxs)(i.Space,{children:[t.status===`admin_disabled`?(0,o.jsx)(i.Button,{size:`small`,loading:f===`t${t.legacyUserId}`,onClick:()=>v(t,!0),children:`Enable`}):(0,o.jsx)(i.Popconfirm,{title:`Stop new leads for ${t.name}?`,description:`Leads they already have stay with them.`,okText:`Disable`,okButtonProps:{danger:!0},onConfirm:()=>v(t,!1),children:(0,o.jsx)(i.Button,{size:`small`,danger:!0,loading:f===`t${t.legacyUserId}`,children:`Disable`})}),(0,o.jsx)(i.Button,{size:`small`,onClick:()=>d(t),children:`Leave`})]})}]:[]];return(0,o.jsxs)(`div`,{className:`ld-today ld-panel`,children:[(0,o.jsxs)(i.Space,{wrap:!0,style:{marginBottom:12,width:`100%`,justifyContent:`space-between`},children:[(0,o.jsxs)(i.Space,{wrap:!0,children:[(0,o.jsx)(i.DatePicker,{value:t,onChange:n,allowClear:!0,placeholder:`Today`,disabledDate:e=>e&&e.isAfter((0,s.default)(),`day`)}),m.settings?(0,o.jsx)(i.Tag,{color:m.settings.mode===`equal_daily`?`magenta`:`default`,children:m.settings.mode===`equal_daily`?`Equal daily distribution`:`Round-robin (earlier behaviour)`}):null]}),(0,o.jsx)(i.Button,{icon:(0,o.jsx)(a.ReloadOutlined,{}),onClick:l,children:`Refresh`})]}),c.loading&&!c.data?(0,o.jsx)(i.Skeleton,{active:!0}):c.error?(0,o.jsx)(ht,{text:c.error,onRetry:l}):(0,o.jsxs)(o.Fragment,{children:[m.settings?.mode===`equal_daily`&&g?(0,o.jsx)(i.Alert,{style:{marginBottom:12},showIcon:!0,type:m.holding?`info`:`success`,message:m.holding?`Leads received until ${dt(m.cutoffAt)} wait, then they are shared equally among counsellors who are online at ${dt(m.cutoffAt)}.`:`Cut-off ${dt(m.cutoffAt)} has passed: each new lead goes to the online counsellor with the fewest leads today.`}):null,(0,o.jsx)(Qe,{items:[{key:`received`,label:`Received`,value:h.received??0,tone:`blue`,icon:(0,o.jsx)(a.InboxOutlined,{})},{key:`assigned`,label:`Assigned`,value:h.assigned??0,tone:`green`,icon:(0,o.jsx)(a.CheckCircleOutlined,{})},{key:`left`,label:`Left to assign`,value:h.pending??0,tone:`violet`,icon:(0,o.jsx)(a.ClockCircleOutlined,{}),sub:`Waiting for all counsellors`},{key:`eligible`,label:`Eligible now`,value:h.eligible??0,tone:`pink`,icon:(0,o.jsx)(a.TeamOutlined,{})},{key:`atCap`,label:`At open-lead limit`,value:h.atCap??0,tone:`amber`,icon:(0,o.jsx)(a.WarningOutlined,{})},{key:`resets`,label:`Resets today`,value:h.resetsToday??0,tone:`green`,icon:(0,o.jsx)(a.SyncOutlined,{}),sub:`Quota refills`},{key:`unavailable`,label:`Unavailable`,value:h.unavailable??0,tone:`grey`,icon:(0,o.jsx)(a.UserOutlined,{})},{key:`target`,label:`Target each`,value:h.target??0,tone:`blue`,icon:(0,o.jsx)(a.ThunderboltOutlined,{})},{key:`balance`,label:`Balance`,tone:h.balance===`balanced`?`green`:`amber`,icon:(0,o.jsx)(a.BarChartOutlined,{}),value:(0,o.jsx)(`span`,{className:`ld-balance`,children:h.balance===`balanced`?`Balanced`:`Catching up (gap ${h.spread})`})}]}),_>0?(0,o.jsxs)(`div`,{className:`ld-explain`,children:[(0,o.jsx)(a.InfoCircleOutlined,{}),(0,o.jsxs)(`div`,{children:[(0,o.jsx)(`strong`,{children:`How the numbers work.`}),` "Untouched `,`x / ${_}`,`" is per counsellor: one counsellor holds at most `,_,` untouched leads at a time.`,` `,`When their untouched leads fall to `,ee,` or fewer, their quota refills (a `,(0,o.jsx)(`em`,{children:`reset`}),`) and they get leads again up to `,_,`.`,` `,`So "Assigned today" can be well above `,_,`. "Left to assign" is the queue for everyone together, not for one counsellor.`]})]}):null,h.balance!==`balanced`&&(h.spread??0)>1?(0,o.jsx)(ct,{type:`secondary`,style:{fontSize:12},children:`Counsellors who joined later get new leads first until they catch up. Leads already assigned are never moved, so an exact match is not always possible.`}):null,(0,o.jsx)(i.Table,{rowKey:`legacyUserId`,size:`small`,columns:y,dataSource:m.counsellors??[],pagination:!1,scroll:{x:`max-content`},loading:c.loading,locale:{emptyText:(0,o.jsx)(i.Empty,{description:`No counsellor is on any form's list yet. Add counsellors in the Forms tab.`})}})]}),u?(0,o.jsx)(_t,{counsellor:u,onClose:e=>{d(null),e&&l()}}):null]})}function _t({counsellor:e,onClose:t}){let[n]=i.Form.useForm(),[a,c]=mt(()=>L((0,s.default)().format(`YYYY-MM-DD`)),[]),[l,u]=(0,r.useState)(!1),[d,f]=(0,r.useState)(!1),p=(Array.isArray(a.data)?a.data:[]).filter(t=>Number(t.legacyUserId)===Number(e.legacyUserId)),m=async()=>{let t=await n.validateFields();u(!0);try{await R({legacyUserId:e.legacyUserId,from:t.range[0].format(`YYYY-MM-DD`),to:t.range[1].format(`YYYY-MM-DD`),reason:t.reason??``}),i.message.success(`Leave saved: no new leads on those days`),n.resetFields(),f(!0),c()}catch(e){i.message.error(C(e))}finally{u(!1)}},h=async e=>{try{await z(e),i.message.success(`Leave removed`),f(!0),c()}catch(e){i.message.error(C(e))}};return(0,o.jsxs)(i.Modal,{open:!0,title:`Leave · ${e.name}`,onCancel:()=>t(d),footer:(0,o.jsx)(i.Button,{onClick:()=>t(d),children:`Close`}),children:[(0,o.jsxs)(i.Form,{form:n,layout:`vertical`,children:[(0,o.jsx)(i.Form.Item,{name:`range`,label:`Days on leave`,rules:[{required:!0,message:`Choose the days`}],children:(0,o.jsx)(i.DatePicker.RangePicker,{style:{width:`100%`},disabledDate:e=>e&&e.isBefore((0,s.default)(),`day`)})}),(0,o.jsx)(i.Form.Item,{name:`reason`,label:`Reason (optional)`,children:(0,o.jsx)(i.Input,{maxLength:300})}),(0,o.jsx)(i.Button,{type:`primary`,loading:l,onClick:m,children:`Add leave`})]}),(0,o.jsx)(ct,{type:`secondary`,style:{margin:`12px 0 4px`},children:`Upcoming leave`}),a.loading?(0,o.jsx)(i.Skeleton,{active:!0,paragraph:{rows:1}}):a.error?(0,o.jsx)(ht,{text:a.error,onRetry:c}):p.length?(0,o.jsx)(i.Space,{direction:`vertical`,style:{width:`100%`},children:p.map(e=>(0,o.jsxs)(i.Space,{style:{justifyContent:`space-between`,width:`100%`},children:[(0,o.jsxs)(st,{children:[(0,s.default)(e.from).format(`D MMM`),` – `,(0,s.default)(e.to).format(`D MMM YYYY`),e.reason?` · ${e.reason}`:``]}),(0,o.jsx)(i.Popconfirm,{title:`Remove this leave?`,okText:`Remove`,onConfirm:()=>h(String(e._id)),children:(0,o.jsx)(i.Button,{size:`small`,type:`link`,danger:!0,children:`Remove`})})]},String(e._id)))}):(0,o.jsx)(st,{type:`secondary`,children:`None.`})]})}function vt({rows:e=[]}){let[t,n]=(0,r.useState)(`waiting`),[s,c]=(0,r.useState)(``),[l,u]=(0,r.useState)(1),[d,f]=mt(()=>B({status:t===`waiting`?``:t,formId:s,page:l,limit:25}),[t,s,l]),p=[{title:`Lead reference`,dataIndex:`facebookLeadId`},{title:`Form`,dataIndex:`facebookFormId`,render:t=>e.find(e=>e.formId===t)?.formName??`Form ${t}`},{title:`Received`,dataIndex:`createdAt`,render:ft},{title:`Waiting`,dataIndex:`createdAt`,key:`waited`,render:(e,t)=>t.status===`dead`?`Stopped`:pt(e)},{title:`Status`,dataIndex:`status`,render:(e,t)=>e===`dead`?(0,o.jsx)(i.Tag,{color:`red`,children:`Assignment Failed`}):e===`processing`?(0,o.jsx)(i.Tag,{color:`blue`,children:`Assigning…`}):(0,o.jsx)(i.Tag,{color:t.lastResult===`awaiting_cutoff`?`purple`:`gold`,children:ut[t.lastResult]??`Pending Assignment`})},{title:`Next try`,dataIndex:`nextAttemptAt`,render:(e,t)=>t.status===`dead`?`No more tries`:ft(e,`Not scheduled`)},{title:`Detail`,key:`detail`,render:(e,t)=>t.lastErrorCode||(ut[t.lastResult]?``:t.lastResult)||`No detail`}];return(0,o.jsxs)(`div`,{className:`ld-queue`,children:[(0,o.jsxs)(i.Space,{wrap:!0,style:{marginBottom:12},children:[(0,o.jsx)(i.Segmented,{value:t,onChange:e=>{n(e),u(1)},options:[{value:`waiting`,label:`Waiting`},{value:`failed`,label:`Failed`},{value:`all`,label:`All`}]}),(0,o.jsx)(i.Select,{style:{minWidth:220},value:s,onChange:e=>{c(e),u(1)},options:[{value:``,label:`All forms`},...e.map(e=>({value:e.formId,label:e.formName??e.formId}))]}),(0,o.jsx)(i.Button,{icon:(0,o.jsx)(a.ReloadOutlined,{}),onClick:f,children:`Refresh`})]}),(0,o.jsx)(ct,{type:`secondary`,style:{fontSize:12},children:`Leads stay here safely until a counsellor can take them; nothing is lost when nobody is logged in. A lead becomes an LMS lead when it is assigned.`}),d.error?(0,o.jsx)(ht,{text:d.error,onRetry:f}):(0,o.jsx)(i.Table,{rowKey:e=>String(e._id??e.facebookLeadId),size:`small`,loading:d.loading,columns:p,dataSource:d.data?.rows??[],scroll:{x:`max-content`},pagination:{current:l,pageSize:25,total:d.data?.total??0,onChange:u,showSizeChanger:!1},locale:{emptyText:(0,o.jsx)(i.Empty,{description:t===`failed`?`No failed leads.`:`No leads are waiting.`})}})]})}var yt=[{value:`report`,label:`Report`},{value:`log`,label:`Log`},{value:`assignments`,label:`Assignments`}],bt=e=>e?{from:e[0].format(`YYYY-MM-DD`),to:e[1].format(`YYYY-MM-DD`)}:{};function xt(){let[e,t]=(0,r.useState)(`report`),[a,c]=(0,r.useState)(``),[l,u]=(0,r.useState)(null),[d,f]=mt(()=>n.H(bt(l)),[l]),p=(Array.isArray(d.data?.rows)?d.data.rows:[]).map(e=>({value:String(e.legacyUserId),label:e.name}));return(0,o.jsxs)(`div`,{className:`ld-history ld-panel`,children:[(0,o.jsxs)(`div`,{className:`ld-toolbar`,children:[(0,o.jsx)(i.Segmented,{value:e,onChange:t,options:yt}),e===`assignments`?null:(0,o.jsxs)(i.Space,{wrap:!0,children:[(0,o.jsx)(i.Select,{style:{minWidth:200},value:a,onChange:c,"aria-label":`Counsellor`,options:[{value:``,label:`All counsellors`},...p],showSearch:!0,optionFilterProp:`label`}),(0,o.jsx)(i.DatePicker.RangePicker,{value:l,onChange:u,allowEmpty:[!1,!1],disabledDate:e=>e&&e.isAfter((0,s.default)(),`day`)})]})]}),e===`report`?(0,o.jsx)(St,{state:d,reload:f,counsellor:a}):null,e===`log`?(0,o.jsx)(Ct,{counsellor:a,range:l},`${a}|${JSON.stringify(bt(l))}`):null,e===`assignments`?(0,o.jsx)(wt,{}):null]})}function St({state:e,reload:t,counsellor:n}){let r=Array.isArray(e.data?.rows)?e.data.rows:[],c=n?r.filter(e=>String(e.legacyUserId)===n):r,l=n?{...e.data?.summary,counsellors:c.length,leadsReceived:c.reduce((e,t)=>e+(t.leadsReceived??0),0),resets:c.reduce((e,t)=>e+(t.resets??0),0)}:e.data?.summary??{},u=Math.max(1,...c.map(e=>e.leadsReceived??0)),d=[{title:`Counsellor`,dataIndex:`name`,render:e=>(0,o.jsx)(st,{strong:!0,children:e}),sorter:(e,t)=>String(e.name).localeCompare(String(t.name))},{title:`Leads received`,dataIndex:`leadsReceived`,width:220,sorter:(e,t)=>e.leadsReceived-t.leadsReceived,defaultSortOrder:`descend`,render:e=>(0,o.jsxs)(`div`,{className:`ld-bar`,children:[(0,o.jsx)(`span`,{className:`ld-num`,children:e??0}),(0,o.jsx)(i.Progress,{percent:Math.round((e??0)/u*100),size:`small`,showInfo:!1,strokeColor:`var(--cc-s-accent)`})]})},{title:`Resets`,dataIndex:`resets`,align:`right`,sorter:(e,t)=>e.resets-t.resets,render:e=>e?(0,o.jsx)($e,{tone:`green`,icon:(0,o.jsx)(a.SyncOutlined,{}),children:e}):(0,o.jsx)(`span`,{className:`ld-muted`,children:`0`})},{title:`Reached limit`,dataIndex:`timesCapped`,align:`right`,sorter:(e,t)=>e.timesCapped-t.timesCapped,render:e=>e?(0,o.jsx)($e,{tone:`amber`,children:e}):(0,o.jsx)(`span`,{className:`ld-muted`,children:`0`})},{title:`Last reset`,dataIndex:`lastResetAt`,render:e=>e?ft(e):`Never`},{title:`First lead`,dataIndex:`firstAssignedAt`,render:ft},{title:`Last lead`,dataIndex:`lastAssignedAt`,render:ft}];return e.error?(0,o.jsx)(ht,{text:e.error,onRetry:t}):(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(Qe,{items:[{key:`people`,label:`Counsellors`,value:l.counsellors??0,tone:`blue`,icon:(0,o.jsx)(a.TeamOutlined,{})},{key:`leads`,label:`Leads received`,value:l.leadsReceived??0,tone:`pink`,icon:(0,o.jsx)(a.InboxOutlined,{})},{key:`resets`,label:`Resets`,value:l.resets??0,tone:`green`,icon:(0,o.jsx)(a.SyncOutlined,{}),sub:`Quota refills`},{key:`since`,label:`Resets tracked since`,value:l.logSince?(0,s.default)(l.logSince).format(`D MMM YYYY`):`No reset yet`,tone:`violet`,icon:(0,o.jsx)(a.ClockCircleOutlined,{})}]}),(0,o.jsx)(ct,{type:`secondary`,style:{fontSize:12},children:`Leads received count every automatic assignment in equal daily mode. A reset is when a counsellor who reached the open-lead limit worked enough leads for their quota to refill.`}),(0,o.jsx)(i.Table,{rowKey:`legacyUserId`,size:`small`,loading:e.loading,columns:d,dataSource:c,pagination:!1,scroll:{x:`max-content`},locale:{emptyText:(0,o.jsx)(i.Empty,{description:`Nothing recorded for these filters yet.`})}})]})}function Ct({counsellor:e,range:t}){let[s,c]=(0,r.useState)(``),[l,u]=(0,r.useState)(1),[d,f]=mt(()=>n.lt({legacyUserId:e,event:s,page:l,limit:25,...bt(t)}),[e,t,s,l]),p=[{title:`When`,dataIndex:`at`,render:ft},{title:`Counsellor`,dataIndex:`counsellorName`,render:(e,t)=>e||`Counsellor #${t.counsellorId}`},{title:`Event`,dataIndex:`event`,render:e=>(0,o.jsx)($e,{tone:at[e]?.tone??`grey`,children:at[e]?.label??e})},{title:`Detail`,key:`detail`,render:(e,t)=>ot(t)}];return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(i.Space,{wrap:!0,style:{marginBottom:12},children:[(0,o.jsx)(i.Segmented,{value:s,onChange:e=>{c(e),u(1)},options:[{value:``,label:`All events`},...Object.entries(at).map(([e,t])=>({value:e,label:t.label}))]}),(0,o.jsx)(i.Button,{icon:(0,o.jsx)(a.ReloadOutlined,{}),onClick:f,children:`Refresh`})]}),d.error?(0,o.jsx)(ht,{text:d.error,onRetry:f}):(0,o.jsx)(i.Table,{rowKey:e=>String(e._id),size:`small`,loading:d.loading,columns:p,dataSource:d.data?.rows??[],scroll:{x:`max-content`},pagination:{current:l,pageSize:25,total:d.data?.total??0,onChange:u,showSizeChanger:!1},locale:{emptyText:(0,o.jsx)(i.Empty,{description:`No events for these filters yet.`})}})]})}function wt(){let[e,t]=(0,r.useState)((0,s.default)()),[n,c]=(0,r.useState)(1),[l,u]=mt(()=>V({date:e?e.format(`YYYY-MM-DD`):``,page:n,limit:25}),[e,n]),d=[{title:`Lead reference`,dataIndex:`facebookLeadId`},{title:`Form`,dataIndex:`formName`},{title:`Received`,dataIndex:`receivedAt`,render:ft},{title:`Assigned`,dataIndex:`assignedAt`,render:ft},{title:`Counsellor`,dataIndex:`counsellorName`},{title:`Their leads that day`,dataIndex:`countAtAssignment`,align:`right`},{title:`Skipped`,dataIndex:`skipped`,render:e=>Array.isArray(e)&&e.length?(0,o.jsx)(i.Tooltip,{title:e.map(e=>`${e.name||`#${e.legacyUserId}`}: ${lt[e.reason]?.label??e.reason}`).join(`
2
+ `),children:(0,o.jsxs)(i.Tag,{children:[e.length,` skipped`]})}):`None skipped`}];return(0,o.jsxs)(`div`,{className:`ld-assignments`,children:[(0,o.jsxs)(i.Space,{wrap:!0,style:{marginBottom:12},children:[(0,o.jsx)(i.DatePicker,{value:e,onChange:e=>{t(e),c(1)},allowClear:!0,placeholder:`All days`}),(0,o.jsx)(i.Button,{icon:(0,o.jsx)(a.ReloadOutlined,{}),onClick:u,children:`Refresh`})]}),(0,o.jsx)(ct,{type:`secondary`,style:{fontSize:12},children:`Every automatic assignment in equal daily mode. Manual reassignments are in the Reassign leads tab and History.`}),l.error?(0,o.jsx)(ht,{text:l.error,onRetry:u}):(0,o.jsx)(i.Table,{rowKey:e=>String(e._id),size:`small`,loading:l.loading,columns:d,dataSource:l.data?.rows??[],scroll:{x:`max-content`},pagination:{current:n,pageSize:25,total:l.data?.total??0,onChange:c,showSizeChanger:!1},locale:{emptyText:(0,o.jsx)(i.Empty,{description:`No assignments for this day yet.`})}})]})}var Tt=[`Asia/Kolkata`,`Asia/Dubai`,`Asia/Singapore`,`Europe/London`,`America/New_York`,`UTC`];function Et({canEdit:e=!1}){let[t]=i.Form.useForm(),[n,c]=mt(()=>I(),[]),[l,u]=(0,r.useState)(!1),d=n.data?.settings;(0,r.useEffect)(()=>{d&&t.setFieldsValue({openLeadCap:15,capWindowDays:0,refillAtRatio:.5,...d,startTime:(0,s.default)(d.startTime,`HH:mm`),cutoffTime:(0,s.default)(d.cutoffTime,`HH:mm`),resetTime:(0,s.default)(d.resetTime,`HH:mm`)})},[d,t]);let f=i.Form.useWatch(`mode`,t),p=i.Form.useWatch(`openLeadCap`,t),m=i.Form.useWatch(`refillAtRatio`,t),h=async()=>{let e=await t.validateFields(),n={...e,startTime:e.startTime.format(`HH:mm`),cutoffTime:e.cutoffTime.format(`HH:mm`),resetTime:e.resetTime.format(`HH:mm`)};i.Modal.confirm({title:`Save distribution settings?`,content:n.mode===`equal_daily`?`New leads will go to the online counsellor with the fewest leads today. Leads already assigned do not move.`:`New leads will go back to plain round-robin.`,okText:`Save`,onOk:async()=>{u(!0);try{await le(n),i.message.success(`Distribution settings saved`),c()}catch(e){i.message.error(C(e))}finally{u(!1)}}})};if(n.loading&&!n.data)return(0,o.jsx)(i.Skeleton,{active:!0});if(n.error)return(0,o.jsx)(ht,{text:n.error,onRetry:c});let g=tt(p,m);return(0,o.jsxs)(i.Form,{form:t,layout:`vertical`,disabled:!e,className:`ld-settings ld-panel`,style:{maxWidth:820},children:[(0,o.jsxs)(`section`,{className:`ld-card`,children:[(0,o.jsxs)(`div`,{className:`ld-card__title`,children:[(0,o.jsx)(a.TeamOutlined,{}),` Who gets leads`]}),(0,o.jsx)(i.Form.Item,{name:`mode`,label:`Only give leads to counsellors who are logged in`,valuePropName:`checked`,getValueProps:e=>({checked:e===`equal_daily`}),normalize:e=>e?`equal_daily`:`round_robin`,children:(0,o.jsx)(i.Switch,{checkedChildren:`On`,unCheckedChildren:`Off`})}),(0,o.jsx)(ct,{type:`secondary`,style:{marginBottom:0},children:f===`equal_daily`?`Only counsellors who are logged in right now, enabled, not on leave and under the open-lead limit get leads. Each lead goes to the one with the fewest leads today; equal counts take turns (round robin). A lead nobody can take waits and is offered again every 2 minutes.`:`Off: round robin as before. Leads take turns through each form's counsellor list, skipping only inactive users. Login, leave and the open-lead limit are not checked, and nothing waits for a login.`})]}),(0,o.jsxs)(`section`,{className:`ld-card ld-settings-group`,hidden:f!==`equal_daily`,children:[(0,o.jsxs)(`div`,{className:`ld-card__title`,children:[(0,o.jsx)(a.WarningOutlined,{}),` `,(0,o.jsx)(st,{strong:!0,children:`Open-lead limit`})]}),(0,o.jsx)(ct,{type:`secondary`,style:{margin:`4px 0 12px`,fontSize:13},children:`A counsellor who has this many untouched leads gets no new lead until they work some (a call, a follow-up, a status change or a save). Their leads are never moved. 0 = no limit.`}),(0,o.jsxs)(i.Row,{gutter:12,children:[(0,o.jsx)(i.Col,{xs:24,md:8,children:(0,o.jsx)(i.Form.Item,{name:`openLeadCap`,label:`Untouched leads per counsellor`,rules:[{required:!0}],children:(0,o.jsx)(i.InputNumber,{min:0,max:500,addonAfter:`leads`,style:{width:`100%`}})})}),(0,o.jsx)(i.Col,{xs:24,md:8,children:(0,o.jsx)(i.Form.Item,{name:`refillAtRatio`,label:`Refill when untouched falls to`,rules:[{required:!0,message:`Enter 0 to 100`}],getValueProps:e=>({value:nt(e)}),normalize:rt,children:(0,o.jsx)(i.InputNumber,{min:0,max:100,step:5,precision:0,addonAfter:`% of the limit`,style:{width:`100%`}})})}),(0,o.jsx)(i.Col,{xs:24,md:8,children:(0,o.jsx)(i.Form.Item,{name:`capWindowDays`,label:`Count untouched leads from`,rules:[{required:!0}],children:(0,o.jsx)(i.Select,{options:[{value:0,label:`Today`},{value:1,label:`Today and yesterday`},{value:2,label:`The last 3 days`},{value:6,label:`The last 7 days`}]})})})]}),Number(p)>0?(0,o.jsxs)(`div`,{className:`ld-explain`,children:[(0,o.jsx)(a.SyncOutlined,{}),(0,o.jsxs)(`div`,{children:[`A counsellor receives up to `,(0,o.jsx)(`strong`,{children:p}),` untouched leads. After reaching `,p,`, they get new leads again once their untouched leads fall to `,(0,o.jsx)(`strong`,{children:g}),` or fewer, then up to `,p,` again. Each refill is counted as a `,(0,o.jsx)(`em`,{children:`reset`}),` in History.`,Number(m)===0?` 0% = they wait until every lead is worked.`:``,Number(m)===1?` 100% = one lead at a time, as soon as they are under the limit.`:``]})]}):null]}),(0,o.jsxs)(`section`,{className:`ld-card`,hidden:f!==`equal_daily`,children:[(0,o.jsxs)(`div`,{className:`ld-card__title`,children:[(0,o.jsx)(a.ClockCircleOutlined,{}),` Daily timing`]}),(0,o.jsxs)(i.Row,{gutter:12,children:[(0,o.jsx)(i.Col,{xs:12,md:6,children:(0,o.jsx)(i.Form.Item,{name:`startTime`,label:`Day starts`,rules:[{required:!0}],children:(0,o.jsx)(i.TimePicker,{format:`HH:mm`,minuteStep:5,style:{width:`100%`}})})}),(0,o.jsx)(i.Col,{xs:12,md:6,children:(0,o.jsx)(i.Form.Item,{name:`cutoffTime`,label:`Initial cut-off`,rules:[{required:!0}],extra:`Morning leads wait until this time.`,children:(0,o.jsx)(i.TimePicker,{format:`HH:mm`,minuteStep:5,style:{width:`100%`}})})}),(0,o.jsx)(i.Col,{xs:12,md:6,children:(0,o.jsx)(i.Form.Item,{name:`resetTime`,label:`Daily reset`,rules:[{required:!0}],children:(0,o.jsx)(i.TimePicker,{format:`HH:mm`,minuteStep:5,style:{width:`100%`}})})}),(0,o.jsx)(i.Col,{xs:12,md:6,children:(0,o.jsx)(i.Form.Item,{name:`timezone`,label:`Time zone`,rules:[{required:!0}],children:(0,o.jsx)(i.Select,{options:Tt.map(e=>({value:e,label:e}))})})}),(0,o.jsx)(i.Col,{xs:24,md:12,children:(0,o.jsx)(i.Form.Item,{name:`holdUntilCutoff`,label:`Hold morning leads until the cut-off`,valuePropName:`checked`,extra:`Off (recommended): leads go to whoever is online as they arrive; the open-lead limit spreads the morning backlog.`,children:(0,o.jsx)(i.Switch,{})})}),(0,o.jsx)(i.Col,{xs:24,md:12,children:(0,o.jsx)(i.Form.Item,{name:`onlineWindowMinutes`,label:`Offline after no activity for`,rules:[{required:!0}],children:(0,o.jsx)(i.InputNumber,{min:2,max:120,addonAfter:`minutes`,style:{width:`100%`}})})})]})]}),(0,o.jsx)(`div`,{className:`ld-settings__actions`,children:e?(0,o.jsx)(i.Button,{type:`primary`,size:`large`,loading:l,onClick:h,children:`Save settings`}):(0,o.jsx)(st,{type:`secondary`,children:`Only users who can edit lead mapping can change these settings.`})})]})}var Dt=e.t({default:()=>Bt}),{Text:Ot,Title:kt}=i.Typography,At=10,jt=`—`,Mt=`You don't have permission to do this.`,Nt=`This could not be loaded. Press Try again first.`;function Pt(e,t){return Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[]}var Ft={forms:{load:m,read:e=>Pt(e,`forms`),label:`Facebook forms`},courses:{load:h,read:e=>Pt(e,`courses`),label:`courses`},mappings:{load:g,read:e=>Pt(e,`mappings`),label:`chosen courses`},distributions:{load:E,read:e=>Pt(e,`distributions`),label:`counsellor lists`},counsellors:{load:D,read:e=>Pt(e,`counsellors`),label:`active counsellors`}},It=Object.keys(Ft),Lt=Object.fromEntries(It.map(e=>[e,[]])),Rt=Object.fromEntries(It.map(e=>[e,{loaded:!1,ok:!1,error:``}]));function zt({distribution:e}){let t=e?.counsellors||[];if(!t.length)return(0,o.jsx)(Ot,{type:`secondary`,children:`Not set up`});let n=t.map(e=>e.name||`Unnamed counsellor`),r=De(e);return(0,o.jsxs)(`div`,{className:`fb-who`,children:[(0,o.jsx)(i.Tooltip,{title:n.join(`, `),trigger:[`hover`,`focus`],children:(0,o.jsxs)(`span`,{className:`fb-avatars`,role:`group`,tabIndex:0,"aria-label":`Gets leads: ${n.join(`, `)}`,children:[n.slice(0,3).map((e,t)=>(0,o.jsx)(`span`,{className:`fb-avatar`,"aria-hidden":`true`,children:(Array.from(e)[0]||`?`).toUpperCase()},`${e}-${t}`)),n.length>3&&(0,o.jsxs)(`span`,{className:`fb-avatar fb-avatar--more`,"aria-hidden":`true`,children:[`+`,n.length-3]})]})}),(0,o.jsxs)(`span`,{className:`fb-next`,children:[`Next: `,r||`No one active`]})]})}function Bt(){let[e,t]=(0,r.useState)(Lt),[n,s]=(0,r.useState)(Rt),[l,u]=(0,r.useState)(!0),[f,p]=(0,r.useState)(null),[m,_]=(0,r.useState)(`forms`),[v,y]=(0,r.useState)(``),[b,x]=(0,r.useState)(`all`),[S,w]=(0,r.useState)(null),[T,O]=(0,r.useState)(1),[k,A]=(0,r.useState)(``),[j,te]=(0,r.useState)(null),[ne,N]=(0,r.useState)(!1),[re,ie]=(0,r.useState)(0),oe=(0,r.useRef)(0),se=(0,r.useRef)(0),P=(0,r.useRef)({element:null,formId:``}),F=(0,r.useRef)(null),ce=(0,r.useCallback)(async()=>{let e=++oe.current;u(!0);let n=await Promise.allSettled(It.map(e=>Ft[e].load()));e===oe.current&&(t(e=>{let t={...e};return n.forEach((e,n)=>{e.status===`fulfilled`&&(t[It[n]]=Ft[It[n]].read(e.value))}),t}),s(e=>{let t={...e};return n.forEach((n,r)=>{let i=It[r];t[i]=n.status===`fulfilled`?{loaded:!0,ok:!0,error:``}:{loaded:e[i].loaded,ok:!1,error:C(n.reason,`Please try again.`,{hideServerText:!0})}}),t}),u(!1))},[]),I=(0,r.useCallback)(()=>(ie(e=>e+1),ce()),[ce]);(0,r.useEffect)(()=>{ce()},[ce]),(0,r.useEffect)(()=>{let e=!0;return ae().then(t=>{e&&p(t)}).catch(()=>{}),()=>{e=!1}},[]);let{alerts:le,alertsOk:ue,failedCount:L}=J({refreshKey:re}),R={add:f?.permissions?.canAdd!==!1,edit:f?.permissions?.canEdit!==!1,remove:f?.permissions?.canDelete!==!1},{forms:z,courses:B,mappings:V,distributions:H,counsellors:U}=e,W=n.forms.loaded,G=n.mappings.loaded,K=n.distributions.loaded,q=!W||!G||!K,de=l&&!It.some(e=>n[e].loaded),fe=(0,r.useMemo)(()=>new Map(H.map(e=>[String(e.formId),e])),[H]),pe=(0,r.useMemo)(()=>new Map(V.map(e=>[String(e.formId),e])),[V]),Y=(0,r.useMemo)(()=>new Map(B.map(e=>[String(e.courseId),e.courseName])),[B]),X=(0,r.useMemo)(()=>{let e=z.map(e=>({formId:String(e.id),formName:e.name||`Unnamed form`,inFormsList:!0})),t=new Set(e.map(e=>e.formId));return[...V,...H].forEach(n=>{let r=String(n.formId);t.has(r)||(t.add(r),e.push({formId:r,formName:n.formName||`Unnamed form`,inFormsList:!1}))}),e.map(e=>{let t=pe.get(e.formId),n=fe.get(e.formId);return{...e,key:e.formId,mapping:t,distribution:n,courseName:t&&(Y.get(String(t.courseId))||t.courseName)||``,status:Ee({mapping:t,distribution:n,inFormsList:e.inFormsList},{forms:W,mappings:G,distributions:K})}})},[z,V,H,pe,fe,Y,W,G,K]),ge=(0,r.useMemo)(()=>{let e=v.trim().toLowerCase();return X.filter(t=>S&&!S.includes(t.formId)||b!==`all`&&t.status!==b?!1:`${t.formName} ${t.formId} ${t.courseName}`.toLowerCase().includes(e))},[X,S,b,v]),Z=!!v.trim()||b!==`all`||!!S,_e=Math.min(T,Math.max(1,Math.ceil(ge.length/At))),ye=()=>{y(``),x(`all`),w(null),O(1)},be=e=>{y(``),x(`all`),w(e),O(1),_(`forms`)},xe=e=>{y(``),w(null),x(e),O(1),_(`forms`)},Se=n.forms.ok&&n.mappings.ok&&n.distributions.ok,Ce=e=>X.filter(t=>t.status===e).length,we=ue?Number(le?.unassignedCount||0):null,Te=we===null||L===null?null:we+L,De=[{key:`ready`,label:`forms ready`,value:Se?Ce(`ready`):jt,onClick:Se?()=>xe(`ready`):void 0},{key:`setup`,label:`need setup`,value:Se?Ce(`needs_setup`):jt,onClick:Se?()=>xe(`needs_setup`):void 0},{key:`waiting`,label:`leads waiting`,value:we??jt,onClick:we===null?void 0:()=>_(`attention`)},{key:`failed`,label:`failed leads`,value:L??jt,onClick:L===null?void 0:()=>_(`attention`)},{key:`counsellors`,label:`active counsellors`,value:n.counsellors.ok?U.length:jt}],Oe=e=>{t(t=>({...t,...e})),s(t=>{let n={...t};return Object.keys(e).forEach(e=>{n[e]={loaded:!0,ok:!0,error:``}}),n})},ke=async()=>{let[e,t,n,r]=await Promise.all([h(),g(),E(),D()]),i={courses:Pt(e,`courses`),mappings:Pt(t,`mappings`),distributions:Pt(n,`distributions`),counsellors:Pt(r,`counsellors`)};return Oe(i),i},Ae=async(e,t,n=null)=>{if(!q){P.current={element:n,formId:e.formId},A(e.formId);try{await ke(),se.current+=1,te({token:se.current,row:e,section:t}),N(!0)}catch(e){i.message.error(C(e,`Could not open this form. Please try again.`))}finally{A(``)}}},je=()=>{let{element:e,formId:t}=P.current;if(e?.isConnected){e.focus();return}[...F.current?.querySelectorAll(`[data-form-menu]`)||[]].find(e=>e.dataset.formMenu===t)?.focus()},Me=()=>{ie(e=>e+1),ce()},Pe=e=>{i.Modal.confirm({title:`Remove course mapping?`,content:(0,o.jsxs)(`span`,{children:[`Remove the course mapping for `,(0,o.jsx)(`strong`,{children:e.formName}),`? Existing lead courses remain unchanged. `,e.distribution?`This form has saved counsellors. They stay in place unless you remove them separately.`:`Future leads from this form will arrive without a course.`]}),okText:`Remove mapping`,okType:`danger`,cancelText:`Cancel`,autoFocusButton:`cancel`,onOk:async()=>{A(e.formId);try{await ee(e.formId),i.message.success(`Course mapping removed`),Me()}catch(e){throw i.message.error(C(e,`Could not remove the mapping. Please try again.`)),e}finally{A(``)}}})},Fe=e=>{i.Modal.confirm({title:`Remove counsellor distribution?`,content:(0,o.jsxs)(`span`,{children:[`Remove the saved counsellors and whose turn is next for `,(0,o.jsx)(`strong`,{children:e.formName}),`? Leads already given out will not change. New leads from this form will wait until counsellors are set up again. Its course mapping stays as it is.`]}),okText:`Remove distribution`,okType:`danger`,cancelText:`Cancel`,autoFocusButton:`cancel`,onOk:async()=>{A(e.formId);try{if((await M(e.formId))?.deleted===!1)throw Error(`This has already been removed. Refresh and try again.`);i.message.success(`Counsellor distribution removed`),Me()}catch(e){throw i.message.error(C(e,`Could not remove the distribution. Please try again.`)),e}finally{A(``)}}})},Q=e=>{let t=e=>q?Nt:e?``:Mt,n=t(e.mapping?R.edit:R.add),r=t(e.distribution?R.edit:R.add);return{items:[{key:`mapping`,icon:e.mapping?(0,o.jsx)(a.EditOutlined,{}):(0,o.jsx)(a.PlusOutlined,{}),label:e.mapping?`Edit mapping`:`Set up mapping`,disabled:!!n,title:n},...e.mapping&&R.remove?[{key:`removeMapping`,icon:(0,o.jsx)(a.DeleteOutlined,{}),label:`Remove mapping`,danger:!0,disabled:q}]:[],{type:`divider`},{key:`distribution`,icon:(0,o.jsx)(a.TeamOutlined,{}),label:e.distribution?`Edit distribution`:`Set up distribution`,disabled:!!r,title:r},...e.distribution&&R.remove?[{key:`removeDistribution`,icon:(0,o.jsx)(a.DeleteOutlined,{}),label:`Remove distribution`,danger:!0,disabled:q}]:[]],onClick:({key:t})=>{t===`mapping`?Ae(e,`course`):t===`distribution`?Ae(e,`counsellors`):t===`removeMapping`?Pe(e):t===`removeDistribution`&&Fe(e)}}},$=e=>e.stopPropagation(),Le=[{title:`Form`,dataIndex:`formName`,key:`form`,render:(e,t)=>(0,o.jsxs)(`div`,{children:[(0,o.jsx)(`button`,{type:`button`,className:`fb-form-name`,disabled:q,onClick:e=>{$(e),Ae(t,`course`,e.currentTarget)},children:e}),(0,o.jsx)(`div`,{children:(0,o.jsxs)(Ot,{type:`secondary`,className:`fb-small`,children:[`Form ID: `,t.formId]})})]})},{title:`Course`,key:`course`,render:(e,t)=>G?t.mapping?(0,o.jsxs)(`span`,{className:`fb-course`,children:[t.courseName||`Course no longer available`,!t.mapping.isActive&&(0,o.jsx)(Ot,{type:`secondary`,children:` (off)`})]}):R.add?(0,o.jsx)(i.Button,{size:`small`,className:`fb-inline-btn`,disabled:q,loading:k===t.formId,onClick:e=>{$(e),Ae(t,`course`,e.currentTarget)},"aria-label":`Map course for ${t.formName}`,children:`Map course`}):(0,o.jsx)(Ot,{type:`secondary`,children:`No course yet`}):(0,o.jsx)(Ot,{type:`secondary`,children:jt})},{title:`Who gets leads`,key:`who`,render:(e,t)=>K?(0,o.jsx)(zt,{distribution:t.distribution}):(0,o.jsx)(Ot,{type:`secondary`,children:jt})},{title:`Status`,dataIndex:`status`,key:`status`,width:170,render:e=>(0,o.jsx)(Ne,{status:e})},{title:(0,o.jsx)(`span`,{className:`fb-sr-only`,children:`Actions`}),key:`actions`,width:56,align:`center`,render:(e,t)=>(0,o.jsx)(`span`,{onClick:$,children:(0,o.jsx)(i.Dropdown,{menu:Q(t),trigger:[`click`],placement:`bottomRight`,children:(0,o.jsx)(i.Button,{size:`small`,className:`fb-form-actions-trigger`,"aria-label":`Actions for ${t.formName}`,"data-form-menu":t.formId,loading:k===t.formId,icon:(0,o.jsx)(a.MoreOutlined,{})})})})}],Re=()=>l?` `:q?(0,o.jsx)(i.Empty,{description:`Forms can't be shown right now.`}):Z?(0,o.jsx)(i.Empty,{description:`No forms match these filters.`,children:(0,o.jsx)(i.Button,{onClick:ye,children:`Clear filters`})}):(0,o.jsx)(i.Empty,{description:`No Facebook forms yet. Create a lead form on Facebook, then refresh.`,children:(0,o.jsx)(i.Button,{onClick:I,children:`Refresh`})}),ze=It.filter(e=>!n[e].ok&&n[e].error),Be=ze.every(e=>n[e].loaded),Ve=()=>`Could not load ${ze.map(e=>Ft[e].label).join(`, `)}. ${[...new Set(ze.map(e=>n[e].error))].join(` `)}`,He=(0,o.jsxs)(`div`,{className:`fb-tab-body`,children:[(0,o.jsxs)(`div`,{className:`fb-toolbar`,children:[(0,o.jsxs)(`div`,{className:`fb-field fb-field--grow`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-forms-search`,children:`Search forms`}),(0,o.jsx)(i.Input,{id:`fb-forms-search`,allowClear:!0,prefix:(0,o.jsx)(a.SearchOutlined,{"aria-hidden":`true`}),placeholder:`Form or course name`,value:v,onChange:e=>{y(e.target.value),O(1)}})]}),(0,o.jsxs)(`div`,{className:`fb-field`,children:[(0,o.jsx)(`label`,{className:`fb-field-label`,htmlFor:`fb-forms-show`,children:`Show`}),(0,o.jsx)(i.Select,{id:`fb-forms-show`,className:`fb-show-select`,value:b,disabled:!G||!K,onChange:e=>{x(e),O(1)},options:[{value:`all`,label:`All forms`},...Object.entries(ve).map(([e,t])=>({value:e,label:t.label}))]})]})]}),S&&(0,o.jsxs)(`div`,{className:`fb-filter-note`,role:`status`,children:[(0,o.jsx)(`span`,{children:S.length===1?`Showing 1 form that needs attention.`:`Showing ${S.length} forms that need attention.`}),(0,o.jsx)(i.Button,{size:`small`,type:`link`,onClick:()=>{w(null),O(1)},children:`Show all forms`})]}),de?(0,o.jsx)(i.Skeleton,{active:!0,title:!1,paragraph:{rows:6}}):(0,o.jsx)(i.Table,{rowKey:`formId`,className:`fb-forms-table${q?``:` fb-forms-table--open`}`,columns:Le,dataSource:ge,loading:l,size:`middle`,scroll:{x:860},onRow:e=>({onClick:()=>Ae(e,`course`)}),pagination:{current:_e,pageSize:At,showSizeChanger:!1,onChange:O,showTotal:e=>`${e} Facebook form${e===1?``:`s`}`},locale:{emptyText:Re()}}),(0,o.jsx)(Ot,{type:`secondary`,className:`fb-small`,children:`Changing a form affects future leads only. Leads you already have keep their course and counsellor.`})]}),Ue={rows:X,refreshKey:re},We=[{key:`forms`,label:`Forms`,children:He},{key:`attention`,label:`Needs attention${Te===null?``:` (${Te})`}`,children:(0,o.jsx)(Ge,{...Ue,canEdit:R.edit,onChanged:()=>ie(e=>e+1)})},{key:`skips`,label:`Skipped counsellors`,children:(0,o.jsx)(qe,{...Ue})},{key:`reassign`,label:`Reassign leads`,children:(0,o.jsx)(he,{...Ue,eligibleCounsellors:U,limits:f?.limits,reasonTypes:f?.reasonTypes,canEdit:R.edit,onChanged:()=>ie(e=>e+1)})},{key:`history`,label:`History`,children:(0,o.jsx)(Je,{...Ue})},{key:`today`,label:`Today`,children:(0,o.jsx)(gt,{canEdit:R.edit})},{key:`queue`,label:`Pending queue`,children:(0,o.jsx)(vt,{rows:X})},{key:`assignments`,label:`Assignment history`,children:(0,o.jsx)(xt,{})},{key:`distributionSettings`,label:`Distribution settings`,children:(0,o.jsx)(Et,{canEdit:R.edit})}],Ke=j?X.find(e=>e.formId===j.row.formId)||j.row:null;return(0,o.jsxs)(`div`,{className:`facebook-course-mapping`,ref:F,children:[(0,o.jsxs)(`div`,{className:`admin-section-head fb-head`,children:[(0,o.jsxs)(`div`,{children:[(0,o.jsx)(kt,{level:4,children:`Facebook Leads`}),(0,o.jsx)(Ot,{type:`secondary`,children:`Choose the course and counsellors for each Facebook form.`})]}),(0,o.jsx)(i.Button,{icon:(0,o.jsx)(a.ReloadOutlined,{"aria-hidden":`true`}),onClick:I,loading:l,children:`Refresh`})]}),(0,o.jsx)(d,{items:De,className:`fb-health`,ariaLabel:`Facebook leads health`}),ze.length>0&&!l&&(0,o.jsx)(c,{className:`fb-load-problem`,type:Be?`warning`:`error`,title:Be?`Showing the last information we could load`:`Some information didn't load`,description:Ve(),action:(0,o.jsx)(i.Button,{size:`small`,onClick:I,children:`Try again`})}),f&&(!R.add||!R.edit||!R.remove)&&(0,o.jsx)(c,{className:`fb-load-problem`,type:`info`,title:`Your role can't make some changes here, so those actions are turned off.`}),(0,o.jsx)(me,{alerts:le,failedCount:L??0,onViewLeads:()=>_(`attention`),onShowForms:be}),(0,o.jsx)(i.Tabs,{size:`small`,activeKey:m,onChange:_,items:We,className:`fb-tabs`}),j&&(0,o.jsx)(Ie,{open:ne,row:Ke,section:j.section,mapping:pe.get(j.row.formId),current:fe.get(j.row.formId),courses:B,counsellors:U,limits:f?.limits,permissions:{canAdd:R.add,canEdit:R.edit},onClose:()=>N(!1),onSaved:Me,onAfterClose:je,onReload:async()=>{let e=await ke(),t=j.row.formId;return{mapping:e.mappings.find(e=>String(e.formId)===t),current:e.distributions.find(e=>String(e.formId)===t)}}},j.token)]})}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return Qe}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return Ze}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Dt}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return $e}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return et}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Bt}});
3
+ //# sourceMappingURL=FacebookCourseMappingsSection-CaD4kZq3.cjs.map