1import{j as e,r as p}from"./vendor-ui-B6LJVmB2.js";import{eB as H,eC as k,eD as S,f as Y,B as E,aa as J,b as W,e as T,s as $,eE as X,eF as ee,eG as se,a3 as te,h as L,I as U,aq as ae,a as re,ac as D,eH as ne,ah as ie}from"./index-R7rnvG6Y.js";import{P as oe}from"./PageHeaderV2-BWKQCVLz.js";import{ae as le,cp as ce,co as de,T as ue,U as me,ck as z,av as he,cm as pe}from"./vendor-icons-rWq2ByuV.js";import{a as xe,u as fe}from"./vendor-query-D2dui6iP.js";import"./vendor-supabase-C_jStVHz.js";import"./vendor-react-C26fm6iv.js";import"./vendor-markdown--mR8Btqo.js";const V=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],w={HOURLY:"hourly",DAILY:"daily",WEEKDAYS:"weekdays",WEEKLY:"weekly",MONTHLY:"monthly"},I={kind:w.DAILY,hour:9,minute:0,weekday:1,dayOfMonth:1},ye={hourly:"Every hour",daily:"Every day",weekdays:"Every weekday",weekly:"Every week",monthly:"Every month"};function R(s){return String(s).padStart(2,"0")}function G(s,t){const r=s<12?"AM":"PM";return`${s%12===0?12:s%12}:${R(t)} ${r}`}function _e(s){const{kind:t,hour:r,minute:n,weekday:i,dayOfMonth:o}=s;switch(t){case w.HOURLY:return`${n} * * * *`;case w.WEEKDAYS:return`${n} ${r} * * 1-5`;case w.WEEKLY:return`${n} ${r} * * ${i}`;case w.MONTHLY:return`${n} ${r} ${o} * *`;case w.DAILY:default:return`${n} ${r} * * *`}}function F(s,t){const r=G(s.hour,s.minute);switch(s.kind){case w.HOURLY:return`Every hour, at ${R(s.minute)} minutes past`;case w.WEEKDAYS:return`Every weekday at ${r} (${t})`;case w.WEEKLY:return`Every ${V[s.weekday]??"Monday"} at ${r} (${t})`;case w.MONTHLY:return`On day ${s.dayOfMonth} of every month at ${r} (${t})`;case w.DAILY:default:return`Every day at ${r} (${t})`}}function ge(s){const t=s.timezone||"UTC";if(s.schedule_kind===H.INTERVAL){const x=Math.round((s.interval_ms??0)/6e4);return x<=0?"On a repeating schedule":x===60?"Every hour":x%60===0?`Every ${x/60} hours`:`Every ${x} minutes`}const r=(s.cron_expr??"").trim(),n=r.split(/\s+/);if(n.length!==5)return r?`On the schedule ${r}`:"On a schedule";const[i,o,c,y,d]=n,l=/^\d+$/;if(!l.test(i))return`On the schedule ${r} (${t})`;if(o==="*"&&c==="*"&&y==="*"&&d==="*")return`Every hour, at ${R(Number(i))} minutes past`;if(!l.test(o)||y!=="*")return`On the schedule ${r} (${t})`;const f=G(Number(o),Number(i));return c==="*"&&d==="1-5"?`Every weekday at ${f} (${t})`:c==="*"&&d==="*"?`Every day at ${f} (${t})`:c==="*"&&l.test(d)?`Every ${V[Number(d)%7]} at ${f} (${t})`:l.test(c)&&d==="*"?`On day ${Number(c)} of every month at ${f} (${t})`:`On the schedule ${r} (${t})`}function A(s){const t=typeof s=="string"?Number(s):s??0;return Number.isFinite(t)?`$${t.toFixed(2)}`:"$0.00"}function q(s){const r=`This automation can spend at most ${A(s.daily_budget_usd??1)} per day. If it reaches that, it stops for the day and tells you.`,n=s.allowance??{},i=Number(n.current_usage??0),o=Number(n.allowance??0),c=`Your plan includes ${o} automations. You're using ${i}.`,y=s.overage_pricing_status==="not_yet_priced";let d,l=!1;switch(n.reason){case"within_allowance":d="This one is included in your plan. No extra charge.";break;case"overage_enabled":d=y?"You're at your plan's limit. You've allowed going over, so this one will be added to your bill at your plan's rate.":`You're at your plan's limit. This one will be billed at ${A(s.overage_rate_usd)} each.`;break;case"hard_stop":l=!0,d=`You're at your plan's limit of ${o} automations. Turn off one you no longer need, or upgrade, and then try again.`;break;default:d=n.allowed?"This one is included in your plan.":"We couldn't check your plan's limit, so nothing was created. Please try again.",l=n.allowed!==!0}return{ceiling:r,allowance:c,impact:d,isBlocked:l}}function we(s,t){switch(s){case"owner_cap_reached":return`You already have ${t.owner_cap??100} automations, which is the most one person can have. Turn one off to make room.`;case"org_allowance_hard_stop":return q(t).impact;default:return s?`We couldn't set that up: ${s.replace(/_/g," ")}.`:"We couldn't set that up. Please try again."}}function be({automation:s,canControl:t,onToggle:r,isBusy:n}){const i=s.status===k.ACTIVE,o=s.visibility===S.ORG,c=Number(s.missed_fire_count??0);return e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.02] p-5",role:"group","aria-label":s.name,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{className:"text-base font-normal text-white/95",children:s.name}),!i&&e.jsx(Y,{variant:"outline",children:"Off"}),o&&e.jsx(Y,{variant:"secondary",children:"Everyone"})]}),e.jsxs("p",{className:"mt-1 flex items-center gap-1.5 text-sm text-soft-secondary",children:[e.jsx(le,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),ge(s)]})]}),t&&e.jsx(E,{size:"sm",variant:"outline",onClick:()=>r(s),disabled:n,children:i?e.jsxs(e.Fragment,{children:[e.jsx(ce,{className:"mr-1.5 h-3.5 w-3.5","aria-hidden":!0}),"Turn off"]}):e.jsxs(e.Fragment,{children:[e.jsx(de,{className:"mr-1.5 h-3.5 w-3.5","aria-hidden":!0}),"Turn back on"]})})]}),e.jsx("p",{className:"mt-3 border-l-2 border-white/15 pl-3 text-sm text-soft-secondary",children:s.prompt}),!i&&s.disabled_reason&&e.jsxs("p",{className:"mt-3 rounded-md border border-amber-400/25 bg-amber-400/[0.04] px-3 py-2 text-sm text-amber-200/90",children:["Turned off ",J(s.disabled_at)," ago:"," ",s.disabled_reason]}),c>0&&e.jsxs("p",{className:"mt-3 flex items-start gap-1.5 rounded-md border border-amber-400/25 bg-amber-400/[0.04] px-3 py-2 text-sm text-amber-200/90",children:[e.jsx(ue,{className:"mt-0.5 h-3.5 w-3.5 shrink-0","aria-hidden":!0}
1),e.jsxs("span",{children:[c===1?"1 run was missed":`${c} runs were missed`,s.last_missed_reason?`: ${s.last_missed_reason}`:"."]})]}),e.jsxs("dl",{className:"mt-4 grid grid-cols-2 gap-x-4 gap-y-2 text-xs text-soft-secondary sm:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-white/50",children:"Next run"}),e.jsx("dd",{children:i?s.next_fire_at?W(s.next_fire_at,"MMM d, h:mm a"):"Being scheduled":"Not scheduled"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-white/50",children:"Last run"}),e.jsx("dd",{children:s.last_fire_at?W(s.last_fire_at,"MMM d, h:mm a"):"Never"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-white/50",children:"Runs so far"}),e.jsx("dd",{children:Number(s.fire_count??0)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-white/50",children:"Cost so far"}),e.jsx("dd",{children:A(s.cost_usd_to_date)})]})]}),e.jsxs("p",{className:"mt-3 flex items-center gap-1.5 text-xs text-soft-secondary",children:[e.jsx(me,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),s.is_mine?"Yours":`Set up by ${s.owner_email??"someone in your organization"}`," · ","Can spend up to ",A(s.daily_budget_usd)," a day"]})]})}const j=()=>null;function Ne(s,t=!0){const r=xe(),n=t&&!!s,i=["workspace-automations",s],{data:o,isLoading:c,error:y,refetch:d}=fe({queryKey:i,enabled:n,queryFn:async()=>{const{data:a,error:u}=await $.rpc("rpc_list_workspace_automations",{p_org_id:s});if(u)throw new Error(u.message);return a??[]}}),l=p.useMemo(()=>
1o??[],[o]),f=T({invalidates:[],settlement:"immediate",mutationFn:async a=>{if(!s)throw new Error("No organization selected.");const{data:u,error:_}=await $.rpc("rpc_create_workspace_cron",{p_org_id:s,p_name:a.name,p_prompt:a.prompt,p_schedule_kind:H.CRON,p_cron_expr:a.cronExpr,p_interval_ms:j(),p_timezone:a.timezone,p_next_fire_at:j(),p_misfire_grace_seconds:X,p_daily_budget_usd:a.dailyBudgetUsd,p_visibility:a.visibility,p_target_doc_ids:j(),p_confirm:a.confirm});if(_)throw new Error(_.message);return u},onSuccess:a=>{a!=null&&a.created&&r.invalidateQueries({queryKey:i})}}),x=T({invalidates:["listWorkspaceAutomations"],settlement:"immediate",mutationFn:async({id:a,pause:u})=>{const{error:_}=await $.rpc("rpc_set_workspace_cron_status",{p_cron_id:a,p_status:u?k.DISABLED:k.ACTIVE,p_reason:u?ee:j(),p_next_fire_at:j()});if(_)throw new Error(_.message)}}),b=T({invalidates:["listWorkspaceAutomations"],settlement:"immediate",mutationFn:async a=>{if(!s)throw new Error("No organization selected.");const{data:u,error:_}=await $.rpc("rpc_disable_all_workspace_crons",{p_org_id:s,p_reason:a});if(_)throw new Error(_.message);return Number(u??0)}});return{automations:l,isLoading:c,error:y??null,refresh:()=>void d(),createAutomation:f.mutateAsync,setStatus:x.mutateAsync,disableAll:b.mutateAsync,isMutating:f.isPending||x.isPending||b.isPending}}const B={visibility:S.PERSONAL,dailyBudgetUsd:se};function ve(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}function Ee({open:s,onOpenChange:t,canCreateOrgWide:r,onSubmit:n,isBusy:i}){const[o,c]=p.useState(""),[y,d]=p.useState(""),[l,f]=p.useState(I),[x,b]=p.useState(!1),[a,u]=p.useState(null),[_,m]=p.useState(null),N=p.useMemo(ve,[]),v=p.useMemo(()=>({name:o.trim(),prompt:y.trim(),cronExpr:_e(l),timezone:N,visibility:x&&r?S.ORG:B.visibility,dailyBudgetUsd:B.dailyBudgetUsd,confirm:!1}),[o,y,l,N,x,r]),M=p.useCallback(()=>{c(""),d(""),f(I),b(!1),u(null),m(null)},[]),O=p.useCallback(()=>{M(),t(!1)},[M,t]),P=p.useCallback(async h=>{m(null);try{const g=await n({...v,confirm:h});if(g.created){O();return}u(g),g.blocked&&m(we(g.reason,g.disclosure))}catch(g){m(g instanceof Error&&g.message?g.message:"We couldn't set that up. Please try again.")}},[n,v,O]),C=a?q(a.disclosure):null,Q=v.name.length>0&&v.prompt.length>0;return e.jsx(te,{open:s,onOpenChange:h=>h?t(!0):O(),tier:"form",title:"Set up an automation",icon:e.jsx(z,{className:"h-5 w-5","aria-hidden":!0}),description:"Describe the work and schedule. Review actions and costs before creating it.",maxWidth:"xl",isLoading:i,footer:e.jsx("div",{className:"flex w-full flex-wrap justify-end gap-2",children:a&&!a.blocked?e.jsx(E,{onClick:()=>void P(!0),disabled:i,children:"Yes, set it up"}):e.jsx(E,{onClick:()=>void P(!1),disabled:i||!Q,children:"Review"})}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(L,{htmlFor:"automation-name",children:"Name it"}),e.jsx(U,{id:"automation-name",value:o,maxLength:120,placeholder:"Weekly supplier price check",onChange:h=>{c(h.target.value),u(null)}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(L,{htmlFor:"automation-prompt",children:"What should it do?"}),e.jsx(ae,{id:"automation-prompt",value:y,maxLength:4e3,rows:3,placeholder:"Check for supplier price changes since last week and summarize what moved.",onChange:h=>{d(h.target.value),u(null)}})]}),e.jsxs("fieldset",{className:"space-y-1.5",children:[e.jsx("legend",{className:"text-sm text-white/80",children:"How often?"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.values(w).map(h=>e.jsx(E,{type:"button",size:"sm",variant:l.kind===h?"default":"outline","aria-pressed":l.kind===h,onClick:()=>{f(g=>({...g,kind:h})),u(null)},children:ye[h]},h))}),l.kind!==w.HOURLY&&e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(L,{htmlFor:"automation-hour",className:"text-xs",children:"At"}),e.jsx(U,{id:"automation-hour",type:"number",min:0,max:23,className:"w-20",value:l.hour,onChange:h=>{const g=Math.min(23,Math.max(0,Number(h.target.value)||0));f(Z=>({...Z,hour:g})),u(null)}}),e.jsxs("span",{className:"text-xs text-soft-secondary",children:["o'clock, ",N]})]}),e.jsx("p",{className:"pt-1 text-sm text-soft-secondary",children:F(l,N)})]}),r&&e.jsxs("label",{className:"flex items-start gap-2 text-sm text-soft-secondary",children:[e.jsx("input",{type:"checkbox",className:"mt-1",checked:x,onChange:h=>{b(h.target.checked),u(null)}}),e.jsx("span",{children:"Make this visible to everyone in the organization. Otherwise it is yours alone, and only you and an admin can see it."})]}),C&&e.jsxs("div",{className:"space-y-2 rounded-lg border border-white/10 bg-white/[0.03] p-4",children:[e.jsx("h4",{className:"text-sm text-white/90",children:"Before this is created, here's what you're agreeing to"}),e.jsxs("p",{className:"text-sm text-soft-secondary",children:[e.jsx("strong",{className:"font-normal text-white/80",children:"Runs:"})," ",F(l,N)]}),e.jsxs("p",{className:"text-sm text-soft-secondary",children:[e.jsx("strong",{className:"font-normal text-white/80",children:"Scope:"})," ",v.visibility===S.ORG?"Visible to everyone in your organization":"Yours alone (admins can still see it)"]}),e.jsx("p",{className:"text-sm text-soft-secondary",children:C.ceiling}),e.jsx("p",{className:"text-sm text-soft-secondary",children:C.allowance}),e.jsx("p",{className:"text-sm text-white/85",children:C.impact}),e.jsxs("p",{className:"text-xs text-soft-secondary",children:["You have ",Number((a==null?void 0:a.disclosure.owner_active_count)??0)," of your ",Number((a==null?void 0:a.disclosure.owner_cap)??0)," automations set up. Each run stops on its own at"," ",A(a==null?void 0:a.disclosure.daily_budget_usd)," a day."]})]}),_&&e.jsx("p",{role:"alert",className:"rounded-md border border-red-400/30 bg-red-400/[0.04] px-3 py-2 text-sm text-red-300",children:_})]})})}function K(s,t){return s instanceof Error&&s.message?s.message:t}function Le(){const{orgId:s,role:t}=re(),r=ie(t),[n,i]=p.useState(!1),{automations:o,isLoading:c,error:y,refresh:d,createAutomation:l,setStatus:f,disableAll:
1x,isMutating:b}=Ne(s??null),a=p.useMemo(()=>o.filter(m=>m.status===k.ACTIVE).length,[o]),u=p.useCallback(m=>{const N=m.status===k.ACTIVE;f({id:m.id,pause:N}).catch(v=>{D({title:"Couldn't change that",description:K(v,"Please try again."),variant:"destructive"})})},[f]),_=p.useCallback(()=>{x(ne).then(m=>{D({title:"Everything is off",description:m===1?"1 automation was turned off. Nothing is scheduled to run.":`${m} automations were turned off. Nothing is scheduled to run.`})}).catch(m=>{D({title:"Couldn't turn everything off",description:K(m,"Please try again."),variant:"destructive"})})},[x]);return e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 px-4 py-6 sm:px-6",children:[e.jsx(oe,{title:"Automations",subtitle:"Work that happens on a schedule instead of when you ask. Every one of them is listed here, with what it has done and what it has cost.",titleIcon:e.jsx(z,{className:"h-6 w-6 text-[var(--gold)]","aria-hidden":!0}),showRefresh:!0,onRefresh:d}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs(E,{onClick:()=>i(!0),disabled:!s,children:[e.jsx(he,{className:"mr-1.5 h-4 w-4","aria-hidden":!0}),"Set up an automation"]}),r&&a>0&&e.jsxs(E,{variant:"outline",onClick:_,disabled:b,children:[e.jsx(pe,{className:"mr-1.5 h-4 w-4","aria-hidden":!0}),"Turn everything off"]})]}),y&&e.jsxs("div",{className:"rounded-lg border border-red-400/30 bg-red-400/[0.04] px-4 py-3 text-sm text-red-300",children:["We couldn't load your automations. ",y.message]}),c&&e.jsx("p",{className:"text-sm text-soft-secondary",children:"Loading automationsâ¦"}),!c&&o.length===0&&e.jsx("div",{className:"rounded-xl border border-white/10 bg-white/[0.02] p-6 text-sm text-soft-secondary",children:"Nothing runs on a schedule yet. Set one up and it will show here, with every run it makes and what it cost."}),e.jsx("div",{className:"space-y-3",children:o.map(m=>e.jsx(be,{automation:m,canControl:m.is_mine||r,onToggle:u,isBusy:b},m.id))}),e.jsx(Ee,{open:n,onOpenChange:i,canCreateOrgWide:r,onSubmit:l,isBusy:b})]})}export{Le as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.