1import{d as Z,a as g,u as y,e as F,j as e}from"./query-vendor-_CTnhe7O.js";import{C as N}from"./card-qTQsd6Lx.js";import{b as m,s as c,a as C,a4 as J,K as B,I as f,B as b}from"./index-CSN0_rIN.js";import{L as v}from"./label-CaEG72nf.js";import{T as z,a as L,b as w,c as i,d as Q,e as n}from"./table-7Snb3dA-.js";import{u as $}from"./useUserRole-BsQBPayS.js";import{c as X}from"./react-vendor-DGf8d9XT.js";import{p as D,V as G,bs as Y,R as A}from"./icons-vendor-DvzEQjW4.js";import"./radix-vendor-BcAgND1y.js";import"./supabase-vendor-CZpx0hCK.js";import"./charts-vendor-k6ViREfG.js";import"./motion-vendor-CnxG56Tq.js";import"./carousel-vendor-BedNBA4P.js";const _={hero:"bg-emerald-500/15 text-emerald-700 dark:text-emerald-400",strong:"bg-sky-500/15 text-sky-700 dark:text-sky-400",steady:"bg-amber-500/15 text-amber-700 dark:text-amber-400",slow:"bg-orange-500/15 text-orange-700 dark:text-orange-400",stale:"bg-rose-500/15 text-rose-700 dark:text-rose-400"};function ue(){const{isAdmin:E,loading:V}=$(),x=Z(),[h,K]=g.useState(""),[p,M]=g.useState(null),[d,U]=g.useState(null),q=y({queryKey:["dynamic-pricing-settings"],queryFn:async()=>{const{data:s,error:t}=await c.from("dynamic_pricing_settings").select("*").eq("id",1).single();if(t)throw t;return s}}),k=y({queryKey:["product-velocity"],queryFn:async()=>{const{data:s,error:t}=await c.from("product_velocity").select("product_id, units_30d, units_60d, revenue_30d, tier, percentile, computed_at, products!inner(id, name, price, original_price, status)").order("units_30d",{ascending:!1}).limit(500);if(t)throw t;return s??[]}}),O=y({queryKey:["pricing-rules"],queryFn:async()=>{const{data:s,error:t}=await c.from("product_pricing_rules").select("*");if(t)throw t;return new Map((s??[]).map(a=>[a.product_id,a]))}}),I=y({queryKey:["price-history-recent"],queryFn:async()=>{const{data:s,error:t}=await c.from("price_history").select("*").order("created_at",{ascending:!1}).limit(25);if(t)throw t;return s??[]}}),l=F({mutationFn:async s=>{const{error:t}=await c.from("dynamic_pricing_settings").update({...s,updated_at:new Date().toISOString()}).eq("id",1);if(t)throw t},onSuccess:()=>{x.invalidateQueries({queryKey:["dynamic-pricing-settings"]}),m.success("Settings saved")},onError:s=>m.error(s.message)}),P=F({mutationFn:async({productId:s,locked:t})=>{const{error:a}=await c.from("product_pricing_rules").upsert({product_id:s,locked:t,updated_at:new Date().toISOString()});if(a)throw a},onSuccess:()=>x.invalidateQueries({queryKey:["pricing-rules"]})});async function R(s){M(s?"dry":"live");try{const{data:t,error:a}=await c.functions.invoke("apply-dynamic-pricing",{body:{},method:"POST",...s?{headers:{}}:{}}),o=`https://wjwpxrtxgdobvnwcfwbe.supabase.co/functions/v1/apply-dynamic-pricing${s?"?dry_run=1":""}`,j=(await c.auth.getSession()).data.session,u=await(await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j?.access_token??"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Indqd3B4cnR4Z2RvYnZud2Nmd2JlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ3MDc1MTksImV4cCI6MjA5MDI4MzUxOX0.ydCrhThclfMMVcdmfTSq90Gz1EtknR65StaUKdh_sMU"}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Indqd3B4cnR4Z2RvYnZud2Nmd2JlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ3MDc1MTksImV4cCI6MjA5MDI4MzUxOX0.ydCrhThclfMMVcdmfTSq90Gz1EtknR65StaUKdh_sMU"}})).json();U(u),u.skipped?m.warning(u.reason??"Skipped"):m.success(s?`Dry run: ${u.products_evaluated} evaluated`:`Updated ${u.products_updated} prices`),x.invalidateQueries({queryKey:["product-velocity"]}),x.invalidateQueries({queryKey:["price-history-recent"]})}catch(t){m.error(t.message??"Engine failed")}finally{M(null)}}const S=g.useMemo(()=>{const s=O.data??new Map;return(k.data??[]).filter(a=>!h||(a.products?.name??"").toLowerCase().includes(h.toLowerCase())).map(a=>{const o=Number(a.products?.original_price??0),j=Number(a.products?.price??0),T=o>0?Math.round((1-j/o)*100):0;return{...a,original:o,current:j,discount:T,rule:s.get(a.product_id)}})},[k.data,O.data,h]);if(V)return null;if(!E)return e.jsx(X,{to:"/admin",replace:!0});const r=q.data;return e.jsxs("div",{className:"container mx-auto p-4 space-y-6 max-w-7xl",children:[e.jsxs("header",{className:"flex flex-col sm:flex-row sm:items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold",children:"Dynamic Pricing Engine"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Velocity-based markdowns: hot sellers stay near full price, slow movers drop deeper."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(C,{variant:"outline",onClick:()=>R(!0),disabled:!!p,children:[p==="dry"?e.jsx(D,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(G,{className:"h-4 w-4 mr-2"}),"Dry run"]}),e.jsxs(C,{onClick:()=>R(!1),disabled:!!p||!r?.enabled,children:[p==="live"?e.jsx(D,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Y,{className:"h-4 w-4 mr-2"}),"Run now"]})]})]}),e.jsxs(N,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold",children:"Global settings"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Engine is ",r?.enabled?"ON":"OFF","."]})]}),q.isLoading?e.jsx(J,{className:"h-6 w-12"}):e.jsx(B,{checked:!!r?.enabled,onCheckedChange:s=>l.mutate({enabled:s})})]}),r&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Max change per run (%)"}),e.jsx(f,{type:"number",defaultValue:r.max_change_pct,onBlur:s=>{const t=Number(s.target.value);!Number.isNaN(t)&&t!==r.max_change_pct&&l.mutate({max_change_pct:t})}})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"New product grace (days)"}),e.jsx(f,{type:"number",defaultValue:r.new_product_grace_days,onBlur:s=>{const t=Number(s.target.value);!Number.isNaN(t)&&t!==r.new_product_grace_days&&l.mutate({new_product_grace_days:t})}})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Stale threshold (days)"}),e.jsx(f,{type:"number",defaultValue:r.stale_days,onBlur:s=>{const t=Number(s.target.value);!Number.isNaN(t)&&t!==r.stale_days&&l.mutate({stale_days:t})}})]}),e.jsxs("div",{children:[e.jsx(v,{className:"text-xs",children:"Rank scope"}),e.jsxs("select",{className:"flex h-10 w-full rounded-md border border-input bg-background px-3 text-sm",defaultValue:r.rank_scope,onCh
1ange:s=>l.mutate({rank_scope:s.target.value}),children:[e.jsx("option",{value:"global",children:"Global"}),e.jsx("option",{value:"seed_type",children:"By seed type"}),e.jsx("option",{value:"type",children:"By product type"})]})]})]}),r?.discount_bands&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Bands:"})," ",Object.entries(r.discount_bands).map(([s,t])=>e.jsxs("span",{className:"mr-3",children:[e.jsx(b,{variant:"outline",className:`mr-1 ${_[s]}`,children:s}),t[0],"â",t[1],"%"]},s))]})]}),d&&e.jsx(N,{className:"p-4 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold",children:["Last run ",d.dry_run?"(dry)":""]}),e.jsxs("p",{className:"text-muted-foreground",children:["Evaluated ",d.products_evaluated," · Updated ",d.products_updated," · Skipped ",d.skipped]})]}),e.jsx("div",{className:"flex gap-2 text-xs",children:Object.entries(d.tiers??{}).map(([s,t])=>e.jsxs(b,{variant:"outline",className:_[s],children:[s,": ",t]},s))})]})}),e.jsxs(N,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("h2",{className:"font-semibold",children:["Products (",S.length,")"]}),e.jsx(f,{placeholder:"Search productsâ¦",value:h,onChange:s=>K(s.target.value),className:"max-w-xs"})]}),k.isLoading?e.jsx(J,{className:"h-64 w-full"}):S.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground py-8 text-center",children:["No velocity data yet. Hit ",e.jsx("strong",{children:"Dry run"})," to compute."]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(z,{children:[e.jsx(L,{children:e.jsxs(w,{children:[e.jsx(i,{children:"Product"}),e.jsx(i,{className:"text-right",children:"30d units"}),e.jsx(i,{className:"text-right",children:"60d units"}),e.jsx(i,{children:"Tier"}),e.jsx(i,{className:"text-right",children:"MSRP"}),e.jsx(i,{className:"text-right",children:"Price"}),e.jsx(i,{className:"text-right",children:"Discount"}),e.jsx(i,{className:"text-center",children:"Lock"})]})}),e.jsx(Q,{children:S.slice(0,200).map(s=>e.jsxs(w,{children:[e.jsx(n,{className:"max-w-xs truncate",children:s.products?.name}),e.jsx(n,{className:"text-right tabular-nums",children:s.units_30d}),e.jsx(n,{className:"text-right tabular-nums",children:s.units_60d}),e.jsx(n,{children:e.jsx(b,{variant:"outline",className:_[s.tier],children:s.tier})}),e.jsxs(n,{className:"text-right tabular-nums",children:["$",s.original.toFixed(2)]}),e.jsxs(n,{className:"text-right tabular-nums",children:["$",s.current.toFixed(2)]}),e.jsxs(n,{className:"text-right tabular-nums",children:[s.discount,"%"]}),e.jsx(n,{className:"text-center",children:e.jsx(B,{checked:!!s.rule?.locked,onCheckedChange:t=>P.mutate({productId:s.product_id,locked:t})})})]},s.product_id))})]})})]}),e.jsxs(N,{className:"p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"font-semibold",children:"Recent price changes"}),e.jsxs(C,{size:"sm",variant:"ghost",onClick:()=>I.refetch(),children:[e.jsx(A,{className:"h-3 w-3 mr-1"})," Refresh"]})]}),(I.data??[]).length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No automated changes yet."}):e.jsxs(z,{children:[e.jsx(L,{children:e.jsxs(w,{children:[e.jsx(i,{children:"When"}),e.jsx(i,{children:"Tier"}),e.jsx(i,{className:"text-right",children:"Old"}),e.jsx(i,{className:"text-right",children:"New"}),e.jsx(i,{children:"Reason"})]})}),e.jsx(Q,{children:(I.data??[]).map(s=>e.jsxs(w,{children:[e.jsx(n,{className:"text-xs",children:new Date(s.created_at).toLocaleString()}),e.jsx(n,{children:e.jsx(b,{variant:"outline",className:_[s.tier],children:s.tier})}),e.jsxs(n,{className:"text-right tabular-nums",children:["$",Number(s.old_price??0).toFixed(2)]}),e.jsxs(n,{className:"text-right tabular-nums",children:["$",Number(s.new_price??0).toFixed(2)]}),e.jsx(n,{className:"text-xs text-muted-foreground",children:s.reason})]},s.id))})]})]})]})}export{ue 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.