1import{k as me,l as ue,p as he,r as l,s as d,q as c,j as e,B as m,A as _e,v as o,I as j,_ as Y,N as _,G as I,O as pe,bd as G,a as ge,L as xe,a2 as fe}from"./index-D6S94l3r.js";import{T as W}from"./textarea-zkxjn3Pk.js";import{S as q,a as M,b as L,c as T,d as p}from"./select-BkXyGY_9.js";import{C as H}from"./calendar-DLPb_Pgl.js";import{P as J,a as K,b as X}from"./popover-DtuDutnd.js";import{P as ve}from"./plus-BOxbBXe6.js";import{P as je}from"./pencil-C_L5e1Pl.js";import"./index-BdQq_4o_.js";import"./chevron-down-0kA1qCjF.js";import"./chevron-up-D18T203o.js";import"./isSameMonth-Bz5De9AU.js";import"./subDays-BSNKuTGW.js";function qe(){const{user:x,isAdmin:D,isMarketing:Z,isTrustee:E,loading:k}=me(),f=D||Z||E,y=D||E,U=ue(),[V,g]=he(),N=V.get("mode"),u=V.get("id"),[w,ee]=l.useState([]),[F,se]=l.useState([]),[v,te]=l.useState([]),[ie,$]=l.useState(!0),[P,R]=l.useState(!1),[O,re]=l.useState(""),[b,B]=l.useState(null),[t,r]=l.useState({code:"",description:"",discount_type:"percentage",discount_value:"",valid_from:void 0,valid_until:void 0,showtime_ids:[],usage_limit:"",minimum_purchase_amount:"",is_active:!0,production_ids:[],enable_conditional:!1,trigger_production_ids:[],target_production_ids:[],requires_all_triggers:!1,trigger_message:""});l.useEffect(()=>{!k&&(!x||!f)&&U("/admin/login")},[x,f,k,U]),l.useEffect(()=>{x&&f&&C()},[x,f]),l.useEffect(()=>{if(u&&w.length>0){const s=w.find(i=>i.id===u);s&&ae(s)}},[u,w]);const C=async()=>{$(!0);try{const[s,i,a]=await Promise.all([d.from("discount_codes").select("*, discount_code_productions(production_id), discount_code_showtimes(showtime_id)").order("created_at",{ascending:!1}),d.from("productions").select("id, title").order("title"),d.from("showtimes").select("id, date, time, production_id, productions(title)").gte("date",new Date().toISOString().split("T")[0]).order("date").order("time")]);if(s.error)throw s.error;if(i.error)throw i.error;if(a.error)throw a.error;ee(s.data||[]),se(i.data||[]),te(a.data||[])}catch(s){c.error("Failed to load data",{description:s.message})}finally{$(!1)}},ae=async s=>{const{data:i}=await d.from("conditional_discounts").select("*").eq("discount_code_id",s.id).single();r({code:s.code,description:s.description||"",discount_type:s.discount_type,discount_value:s.discount_value.toString(),valid_from:s.valid_from?new Date(s.valid_from):void 0,valid_until:s.valid_until?new Date(s.valid_until):void 0,showtime_ids:s.discount_code_showtimes?.map(a=>a.showtime_id)||[],usage_limit:s.usage_limit?.toString()||"",minimum_purchase_amount:s.minimum_purchase_amount?.toString()||"",is_active:s.is_active,production_ids:s.discount_code_productions?.map(a=>a.production_id)||[],enable_conditional:!!i,trigger_production_ids:i?.trigger_production_ids||[],target_production_ids:i?.target_production_ids||[],requires_all_triggers:i?.requires_all_triggers||!1,trigger_message:i?.trigger_message||""})},A=()=>{r({code:"",description:"",discount_type:"percentage",discount_value:"",valid_from:void 0,valid_until:void 0,showtime_ids:[],usage_limit:"",minimum_purchase_amount:"",is_active:!0,production_ids:[],enable_conditional:!1,trigger_production_ids:[],target_production_ids:[],requires_all_triggers:!1,trigger_message:""})},oe=()=>t.code.trim()?!t.discount_value||parseFloat(t.discount_value)<=0?(c.error("Discount value must be greater than 0"),!1):t.discount_type==="percentage"&&parseFloat(t.discount_value)>100?(c.error("Percentage discount cannot exceed 100%"),!1):t.valid_from&&t.valid_until&&t.valid_from>t.valid_until?(c.error("Valid Until must be after Valid From"),!1):!0:(c.error("Code is required"),!1),de=async()=>{if(oe()){R(!0);try{const{data:{user:s}}=await d.auth.getUser();if(!s)throw new Error("Not authenticated");const i={code:t.code.toUpperCase().trim(),description:t.description.trim()||null,discount_type:t.discount_type,discount_value:parseFloat(t.discount_value),valid_from:t.valid_from?.toISOString()||null,valid_until:t.valid_until?.toISOString()||null,applies_to_dates_from:null,applies_to_dates_until:null,usage_limit:t.usage_limit?parseInt(t.usage_limit):null,minimum_purchase_amount:t.minimum_purchase_amount?parseFloat(t.minimum_purchase_amount):null,is_active:t.is_active,created_by:s.id};let a;if(u){const{error:n}=await d.from("discount_codes").update(i).eq("id",u);if(n)throw n;a=u,await Promise.all([d.from("discount_code_productions").delete().eq("discount_code_id",u),d.from("discount_code_showtimes").delete().eq("discount_code_id",u),d.from("conditional_discounts").delete().eq("discount_code_id",u)])}else{const{data:n,error:h}=await d.from("discount_codes").insert(i).select().single();if(h)throw h;a=n.id}const S=[];if(t.production_ids.length>0){const n=t.production_ids.map(h=>({discount_code_id:a,production_id:h}));S.push(d.from("discount_code_productions").insert(n))}if(t.showtime_ids.length>0){const n=t.showtime_ids.map(h=>({discount_code_id:a,showtime_id:h}));S.push(d.from("discount_code_showtimes").insert(n))}if(S.length>0){const h=(await Promise.all(S)).filter(le=>le.error);if(h.length>0)throw h[0].error}if(t.enable_conditional&&t.trigger_production_ids.length>0&&t.target_production_ids.length>0){const{error:n}=await d.from("conditional_discounts").insert({discount_code_id:a,trigger_production_ids:t.trigger_production_ids,target_production_ids:t.target_production_ids,requires_all_triggers:t.requires_all_triggers,trigger_message:t.trigger_message||null});if(n)throw n}const{error:Q}=await d.functions.invoke("create-shopify-discount",{body:{discountCodeId:a,code:t.code.toUpperCase().trim(),discountType:t.discount_type,discountValue:parseFloat(t.discount_value),validFrom:t.valid_from?.toISOString(),val
1idUntil:t.valid_until?.toISOString(),usageLimit:t.usage_limit?parseInt(t.usage_limit):null,minimumPurchaseAmount:t.minimum_purchase_amount?parseFloat(t.minimum_purchase_amount):null,productionIds:t.production_ids,showtimeIds:t.showtime_ids}});Q?(console.error("Shopify creation error:",Q),c.error("Discount saved but Shopify sync failed",{description:"You may need to sync manually"})):c.success(u?"Discount code updated":"Discount code created"),A(),g({}),C()}catch(s){c.error("Failed to save discount code",{description:s.message})}finally{R(!1)}}},ne=async s=>{if(confirm(`Are you sure you want to delete discount code "${s.code}"?`))try{s.shopify_price_rule_id&&await d.functions.invoke("delete-shopify-discount",{body:{shopifyPriceRuleId:s.shopify_price_rule_id,shopifyDiscountCodeId:s.shopify_discount_code_id,shopifyCollectionId:s.shopify_collection_id}});const{error:i}=await d.from("discount_codes").delete().eq("id",s.id);if(i)throw i;c.success("Discount code deleted"),C()}catch(i){c.error("Failed to delete discount code",{description:i.message})}},ce=async s=>{try{const{error:i}=await d.from("discount_codes").update({is_active:!s.is_active}).eq("id",s.id);if(i)throw i;c.success(`Discount code ${s.is_active?"deactivated":"activated"}`),C()}catch(i){c.error("Failed to update discount code",{description:i.message})}},z=w.filter(s=>{const i=s.code.toLowerCase().includes(O.toLowerCase()),a=b===null||s.is_active===b;return i&&a});return k||!x||!f?null:N==="create"||N==="edit"?e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b border-border",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs(m,{variant:"ghost",onClick:()=>{A(),g({})},children:[e.jsx(_e,{className:"mr-2 h-4 w-4"}),"Back to Discount Codes"]})})}),e.jsxs("main",{className:"container mx-auto px-4 py-8 max-w-2xl",children:[e.jsxs("h1",{className:"text-3xl font-bold mb-8",children:[N==="edit"?"Edit":"Create"," Discount Code"]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx(o,{htmlFor:"code",children:"Discount Code *"}),e.jsx(j,{id:"code",value:t.code,onChange:s=>r({...t,code:s.target.value.toUpperCase()}),placeholder:"SUMMER10",maxLength:20,className:"uppercase"})]}),e.jsxs("div",{children:[e.jsx(o,{htmlFor:"description",children:"Description"}),e.jsx(W,{id:"description",value:t.description,onChange:s=>r({...t,description:s.target.value}),placeholder:"Internal notes about this discount",rows:3})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(o,{htmlFor:"discount_type",children:"Discount Type *"}),e.jsxs(q,{value:t.discount_type,onValueChange:s=>r({...t,discount_type:s}),children:[e.jsx(M,{children:e.jsx(L,{})}),e.jsxs(T,{children:[e.jsx(p,{value:"percentage",children:"Percentage (%)"}),e.jsx(p,{value:"fixed_amount",children:"Fixed Amount (£)"})]})]})]}),e.jsxs("div",{children:[e.jsx(o,{htmlFor:"discount_value",children:"Value *"}),e.jsx(j,{id:"discount_value",type:"number",step:"0.01",min:"0",value:t.discount_value,onChange:s=>r({...t,discount_value:s.target.value}),placeholder:t.discount_type==="percentage"?"10":"5.00"})]})]}),e.jsxs("div",{className:"border-t pt-6",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Code Validity Period"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"When the code can be entered"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(o,{children:"Valid From"}),e.jsxs(J,{children:[e.jsx(K,{asChild:!0,children:e.jsxs(m,{variant:"outline",className:I("w-full justify-start text-left font-normal",!t.valid_from&&"text-muted-foreground"),children:[e.jsx(Y,{className:"mr-2 h-4 w-4"}),t.valid_from?_(t.valid_from,"PPP"):"Pick a date"]})}),e.jsx(X,{className:"w-auto p-0",align:"start",children:e.jsx(H,{mode:"single",selected:t.valid_from,onSelect:s=>r({...t,valid_from:s}),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(o,{children:"Valid Until"}),e.jsxs(J,{children:[e.jsx(K,{asChild:!0,children:e.jsxs(m,{variant:"outline",className:I("w-full justify-start text-left font-normal",!t.valid_until&&"text-muted-foreground"),children:[e.jsx(Y,{className:"mr-2 h-4 w-4"}),t.valid_until?_(t.valid_until,"PPP"):"Pick a date"]})}),e.jsx(X,{className:"w-auto p-0",align:"start",children:e.jsx(H,{mode:"single",selected:t.valid_until,onSelect:s=>r({...t,valid_until:s}),initialFocus:!0,className:"pointer-events-auto"})})]})]})]})]}),e.jsxs("div",{className:"border-t pt-6",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Performance Date Restrictions"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Select specific performances this discount applies to"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(o,{children:"Performances (Optional - leave empty for all)"}),e.jsxs("div",{className:"border rounded-md p-4 max-h-64 overflow-y-auto space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("input",{type:"checkbox",id:"select-all-showtimes",checked:t.showtime_ids.length===v.length&&v.length>0,onChange:s=>{s.target.checked?r({...t,showtime_ids:v.map(i=>i.id)}):r({...t,showtime_ids:[]})},className:"h-4 w-4"}),e.jsx(o,{htmlFor:"select-all-showtimes",className:"font-medium cursor-pointer",children:"All Performances"})]}),v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No upcoming performances"}):v.map(s=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",id:`showtime-${s.id}
1`,checked:t.showtime_ids.includes(s.id),onChange:i=>{i.target.checked?r({...t,showtime_ids:[...t.showtime_ids,s.id]}):r({...t,showtime_ids:t.showtime_ids.filter(a=>a!==s.id)})},className:"h-4 w-4"}),e.jsxs(o,{htmlFor:`showtime-${s.id}`,className:"text-sm cursor-pointer flex-1",children:[s.productions?.title," - ",_(new Date(s.date),"MMM d, yyyy")," at ",pe(s.time)]})]},s.id))]})]})]}),e.jsxs("div",{className:"border-t pt-6",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Restrictions"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(o,{htmlFor:"production_ids",children:"Limit to Productions (Optional)"}),e.jsxs(q,{value:t.production_ids.length===1?t.production_ids[0]:"",onValueChange:s=>{if(s==="all")r({...t,production_ids:[]});else{const i=t.production_ids;i.includes(s)?r({...t,production_ids:i.filter(a=>a!==s)}):r({...t,production_ids:[...i,s]})}},children:[e.jsx(M,{children:e.jsx(L,{placeholder:t.production_ids.length===0?"All Productions":`${t.production_ids.length} selected`})}),e.jsxs(T,{children:[e.jsx(p,{value:"all",children:"All Productions"}),F.map(s=>e.jsx(p,{value:s.id,children:s.title},s.id))]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Leave empty for all productions"})]}),e.jsxs("div",{children:[e.jsx(o,{htmlFor:"usage_limit",children:"Usage Limit"}),e.jsx(j,{id:"usage_limit",type:"number",min:"0",value:t.usage_limit,onChange:s=>r({...t,usage_limit:s.target.value}),placeholder:"Unlimited"})]}),e.jsxs("div",{children:[e.jsx(o,{htmlFor:"minimum_purchase_amount",children:"Minimum Purchase Amount (£)"}),e.jsx(j,{id:"minimum_purchase_amount",type:"number",step:"0.01",min:"0",value:t.minimum_purchase_amount,onChange:s=>r({...t,minimum_purchase_amount:s.target.value}),placeholder:"0.00"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{id:"is_active",checked:t.is_active,onCheckedChange:s=>r({...t,is_active:s})}),e.jsx(o,{htmlFor:"is_active",children:"Active"})]})]})]}),e.jsxs("div",{className:"border-t pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(G,{id:"enable_conditional",checked:t.enable_conditional,onCheckedChange:s=>r({...t,enable_conditional:s})}),e.jsx(o,{htmlFor:"enable_conditional",className:"text-lg font-semibold",children:"Conditional Discount (Cross-Production)"})]}),t.enable_conditional&&e.jsxs("div",{className:"space-y-4 pl-6 border-l-2 border-border",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set up rules for discounts that apply when customers buy tickets for specific productions"}),e.jsxs("div",{children:[e.jsx(o,{children:"Trigger Productions *"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Customer must have these in cart to see the discount suggestion"}),e.jsx("div",{className:"border rounded-md p-4 max-h-48 overflow-y-auto space-y-2",children:F.map(s=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",id:`trigger-${s.id}`,checked:t.trigger_production_ids.includes(s.id),onChange:i=>{i.target.checked?r({...t,trigger_production_ids:[...t.trigger_production_ids,s.id]}):r({...t,trigger_production_ids:t.trigger_production_ids.filter(a=>a!==s.id)})},className:"h-4 w-4"}),e.jsx(o,{htmlFor:`trigger-${s.id}`,className:"text-sm cursor-pointer flex-1",children:s.title})]},s.id))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",id:"requires_all_triggers",checked:t.requires_all_triggers,onChange:s=>r({...t,requires_all_triggers:s.target.checked}),className:"h-4 w-4"}),e.jsx(o,{htmlFor:"requires_all_triggers",className:"text-sm cursor-pointer",children:"Require ALL trigger productions (vs ANY one of them)"})]}),e.jsxs("div",{children:[e.jsx(o,{children:"Discount Applies To *"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"The discount will only apply to tickets for these productions"}),e.jsx("div",{className:"border rounded-md p-4 max-h-48 overflow-y-auto space-y-2",children:F.map(s=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",id:`target-${s.id}
1`,checked:t.target_production_ids.includes(s.id),onChange:i=>{i.target.checked?r({...t,target_production_ids:[...t.target_production_ids,s.id]}):r({...t,target_production_ids:t.target_production_ids.filter(a=>a!==s.id)})},className:"h-4 w-4"}),e.jsx(o,{htmlFor:`target-${s.id}`,className:"text-sm cursor-pointer flex-1",children:s.title})]},s.id))})]}),e.jsxs("div",{children:[e.jsx(o,{htmlFor:"trigger_message",children:"Suggestion Message"}),e.jsx(W,{id:"trigger_message",value:t.trigger_message,onChange:s=>r({...t,trigger_message:s.target.value}),placeholder:"Add tickets for [Production] and save 10% with this code!",rows:2}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"This message will be shown to customers when conditions are met"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-6",children:[e.jsxs(m,{onClick:de,disabled:P,children:[P&&e.jsx(ge,{className:"mr-2 h-4 w-4 animate-spin"}),N==="edit"?"Update":"Create"," Discount Code"]}),e.jsx(m,{variant:"outline",onClick:()=>{A(),g({})},disabled:P,children:"Cancel"})]})]})]})]}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b border-border",children:e.jsxs("div",{className:"container mx-auto px-4 py-4 flex justify-between items-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Discount Codes"}),e.jsx(xe,{to:"/admin",children:e.jsx(m,{variant:"outline",children:"Back to Admin"})})]})}),e.jsxs("main",{className:"container mx-auto px-4 py-8",children:[e.jsxs("div",{className:"flex justify-between items-center mb-8",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(j,{placeholder:"Search codes...",value:O,onChange:s=>re(s.target.value),className:"w-64"}),e.jsxs(q,{value:b===null?"all":b?"active":"inactive",onValueChange:s=>{B(s==="all"?null:s==="active")},children:[e.jsx(M,{className:"w-32",children:e.jsx(L,{})}),e.jsxs(T,{children:[e.jsx(p,{value:"all",children:"All"}),e.jsx(p,{value:"active",children:"Active"}),e.jsx(p,{value:"inactive",children:"Inactive"})]})]})]}),y&&e.jsxs(m,{onClick:()=>g({mode:"create"}),children:[e.jsx(ve,{className:"mr-2 h-4 w-4"}),"New Discount Code"]})]}),ie?e.jsx("p",{className:"text-muted-foreground",children:"Loading discount codes..."}):z.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No discount codes found"}),y&&e.jsx(m,{onClick:()=>g({mode:"create"}),children:"Create your first discount code"})]}):e.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-4 font-semibold",children:"Code"}),e.jsx("th",{className:"text-left p-4 font-semibold",children:"Type"}),e.jsx("th",{className:"text-left p-4 font-semibold",children:"Value"}),e.jsx("th",{className:"text-left p-4 font-semibold",children:"Valid Period"}),e.jsx("th",{className:"text-left p-4 font-semibold",children:"Performance Dates"}),e.jsx("th",{className:"text-left p-4 font-semibold",children:"Usage"}),e.jsx("th",{className:"text-left p-4 font-semibold",children:"Status"}),e.jsx("th",{className:"text-right p-4 font-semibold",children:"Actions"})]})}),e.jsx("tbody",{children:z.map(s=>e.jsxs("tr",{className:"border-t border-border",children:[e.jsx("td",{className:"p-4 font-mono font-semibold",children:s.code}),e.jsx("td",{className:"p-4",children:s.discount_type==="percentage"?"%":"£"}),e.jsx("td",{className:"p-4",children:s.discount_type==="percentage"?`${s.discount_value}%`:`£${s.discount_value}`}),e.jsx("td",{className:"p-4 text-sm",children:s.valid_from&&s.valid_until?e.jsxs(e.Fragment,{children:[_(new Date(s.valid_from),"MMM d")," - ",_(new Date(s.valid_until),"MMM d, yyyy")]}):s.valid_from?e.jsxs(e.Fragment,{children:["From ",_(new Date(s.valid_from),"MMM d, yyyy")]}):s.valid_until?e.jsxs(e.Fragment,{children:["Until ",_(new Date(s.valid_until),"MMM d, yyyy")]}):e.jsx("span",{className:"text-muted-foreground",children:"Anytime"})}),e.jsx("td",{className:"p-4 text-sm",children:s.discount_code_showtimes?.length>0?e.jsxs("span",{children:[s.discount_code_showtimes.length," performance(s)"]}):e.jsx("span",{className:"text-muted-foreground",children:"All performances"})}),e.jsxs("td",{className:"p-4",children:[s.usage_count," / ",s.usage_limit||"â"]}),e.jsx("td",{className:"p-4",children:y?e.jsx(m,{variant:s.is_active?"default":"secondary",size:"sm",onClick:()=>ce(s),children:s.is_active?"Active":"Inactive"}):e.jsx("span",{className:I("text-sm font-medium",s.is_active?"text-primary":"text-muted-foreground"),children:s.is_active?"Active":"Inactive"})}),e.jsx("td",{className:"p-4",children:e.jsxs("div",{className:"flex gap-2 justify-end",children:[y&&e.jsx(m,{variant:"outline",size:"icon",onClick:()=>g({mode:"edit",id:s.id}),children:e.jsx(je,{className:"h-4 w-4"})}),D&&e.jsx(m,{variant:"outline",size:"icon",onClick:()=>ne(s),children:e.jsx(fe,{className:"h-4 w-4"})})]})})]},s.id))})]})})]})]})}export{qe 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.