import{I as L}from"./index-4b46c3db.js";import{a as b,_ as I,A as T,r as l,o as d,c as u,w as m,j as h,d as s,k as N,e as a,I as V,J as M,t as O,b as w,F as Y,m as q,h as j,K as G,L as Q}from"./index-be2d4151.js";import"./InfoButton.vue_vue_type_style_index_0_scoped_635db2d1_lang-ea4dfeb4.js";import{C as z,E as J,D as H}from"./EditButton-6b424ab5.js";import{L as K,C as $}from"./index-124eb047.js";import{I as W}from"./index-f10fdf98.js";import{L as E}from"./Loading-c46365ec.js";import{P as X}from"./index-8cbf5e02.js";import{l as Z}from"./lodash-cc03f756.js";import{C as ee}from"./CloseButton-91fa6b44.js";import{S as te}from"./SubmitButton-1d5ea630.js";import{U as oe}from"./UpdateButton-331adda6.js";import{F as se}from"./index-5f541e4d.js";import{F as re}from"./default-f38ac8a4.js";import{T as ae}from"./index-9c004d68.js";import{T as ie}from"./index-5600e357.js";import{B as le}from"./BrandService-b147be33.js";import{D as ne}from"./DealershipService-12029f82.js";import{M as de}from"./ModelService-da301f16.js";import{M as ce}from"./Multiselect-89305a7f.js";import{c as me,a as D,V as ue}from"./array-9fca5ec5.js";import"./logo-black-d3c46f69.js";import"./logo-white-e1b05cf3.js";import"./transition-4fc77ecd.js";import"./vue-cleave.min-19d21cac.js";const y="https://aha-api.autohub.ph/api/v3/promo-codes",C={fetchRecords(t={}){return b.get(`${y}`,{params:t})},fetchRecord(t){return b.get(`${y}/${t}`)},async create(t){return b.post(`${y}`,t)},async update(t,e){return b.put(`${y}/${t}`,e)},async remove(t){return b.delete(`${y}/${t}`)},async fetchCustomerByFilter(t){return b.post(`${y}/users-by-filter`,t)}};function R(t,e=!0){console.log("Hello"),typeof t<"u"?typeof t!="string"&&(t=t.toString()):t="0.00";const i=t.replace(/,/g,"");if(isNaN(i)||i=="")return"0.00";let f=parseFloat(i).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});if(f.includes("-"))if(e)f=`(${f.replace("-","")})`;else return"0.00";return f}function pe(t){typeof t<"u"?typeof t!="string"&&(t=t.toString()):t="0.00";const e=t.replace(/[^\d.-]/g,"");return isNaN(e)||e==""?"0.00":parseFloat(e).toFixed(2)}const he={components:{FormModal:se,FormGroup:re,TextInput:ae,TextArea:ie,SubmitButton:te,UpdateButton:oe,CloseButton:ee,Loading:E,Multiselect:ce,FlatPickr:T},data(){return{brandOptions:[],modelOptions:[],dealerOptions:[],userOptions:[],form:{is_mobile_user:!0,brand_id:"",model_id:"",dealer_id:"",aha_owner_id:"",promo_code:"",promo_amount:"",is_percentage:!1,enabled:!0,start_date:"",expiry_date:"",created_by:JSON.parse(localStorage.getItem("activeUser")).id},errors:{},state:{isEdit:!1,isSaving:!1,isLoading:!1}}},computed:{dealershipAccess(){return this.$store.userSettings.getDealershipAccess.filter(t=>t.system_id==4)}},methods:{async fetchCustomer(){await C.fetchCustomerByFilter(this.form).then(t=>{t.status==200&&t.data.customers.forEach(e=>{e.aha_user_id!==null&&this.userOptions.push({value:e.aha_user_id,label:e.customer_name})})}).catch(t=>{console.log(t)})},async fetchBrands(t={}){t.dealers=this.dealershipAccess.map(e=>e.id),await le.fetchRecords(t).then(e=>{e.status==200&&(this.brandOptions=e.data.data.map(i=>({value:i.id,label:i.name})))}).catch(e=>{console.log(e)})},loadRecord(t){this.resetForm(),this.state.isEdit=!0;let e=Object.assign({},t);this.form={id:e.id,is_mobile_user:e.is_mobile_user==1,brand_id:e.brand_id,model_id:e.model_id,dealer_id:e.dealer_id,aha_owner_id:e.promo_details.length==1?e.aha_owner_id:null,promo_code:e.promo_code,promo_amount:e.promo_amount?e.promo_amount.replace("%",""):"",is_percentage:e.is_percentage==1,enabled:e.enabled==1,start_date:e.start_date,expiry_date:e.expiry_date,created_by:JSON.parse(localStorage.getItem("activeUser")).id},this.fetchModelsAndDealer()},closeModal(){this.state.showModal=!1},resetForm(){this.state.isEdit=!1,this.form={is_mobile_user:!0,brand_id:"",model_id:"",dealer_id:"",aha_owner_id:"",promo_code:"",promo_amount:"",is_percentage:!1,enabled:!0,start_date:"",expiry_date:"",created_by:JSON.parse(localStorage.getItem("activeUser")).id}},reload(){this.$emit("reload")},async saveRecord(){if(this.state.isSaving=!0,!this.state.isEdit)await C.create(this.form).then(t=>{t.status==201&&(this.$swal.fire({title:"Great!",text:"Record successfully saved.",icon:"success",timer:2e3}),this.state.showModal=!1,this.resetForm(),this.reload())}).catch(t=>{console.log(t),t.response.status==422?this.$swal.fire({title:"Ooops! something is wrong.",text:t.response.data.message,icon:"warning"}):this.$swal.fire({title:"Ooops! something is wrong.",text:"Please contact system administrator",icon:"error",timer:2e3})}).finally(()=>this.state.isSaving=!1);else{const t=this.form.id;await C.update(t,this.form).then(e=>{console.log("response.status",e.status),e.status==201?(this.$swal.fire({title:"Great!",text:"Record successfully updated.",icon:"success",timer:2e3}),this.state.showModal=!1,this.reload()):(this.$swal.fire({title:"Ooops! something is wrong.",text:"Please contact system administrator",icon:"error",timer:2e3}),this.state.showModal=!1)}).catch(e=>{console.log(e),e.response.status==422?this.$swal.fire({title:"Ooops! something is wrong.",text:e.response.data.message,icon:"warning"}):this.$swal.fire({title:"Ooops! something is wrong.",text:"Please contact system administrator",icon:"error",timer:2e3})}).finally(()=>{this.state.isSaving=!1})}},async submitForm(){try{await me().shape({promo_code:D().required("Color name field is required"),expiry_date:D().required("Expiry Date field is required")}).validate(this.form,{abortEarly:!1}),this.$swal.fire({title:"Are you sure you want to "+(this.state.isEdit?"update":"save")+" this record?",text:"",icon:"question",showCancelButton:!0,confirmButtonColor:"#34c38f",cancelButtonColor:"#f46a6a",confirmButtonText:"Yes",cancelButtonText:"No"}).then(e=>{e.value&&this.saveRecord()})}catch(t){if(t instanceof ue){const e={};t.inner.forEach(i=>{e[i.path]=i.message}),this.errors=e}this.state.isSaving=!1}},fetchModelsAndDealer(){this.fetchModelsUnderBrand(),this.fetchDealersUnderBrand(),this.fetchCustomer()},async fetchModelsUnderBrand(){this.modelOptions=[],await de.fetchRecords({brand:this.form.brand_id}).then(t=>{t.status==200&&(this.modelOptions=t.data.data.map(e=>({value:e.id,label:e.name})))}).catch(t=>{console.log(t)})},async fetchDealersUnderBrand(){this.dealerOptions=[];const t=this.dealershipAccess.map(e=>e.id);await ne.fetchRecords({brand:this.form.brand_id}).then(e=>{e.status==200&&(this.dealerOptions=e.data.data.filter(i=>t.includes(i.id)).map(i=>({value:i.id,label:i.name})))}).catch(e=>{console.log(e)})},formatAmount(t){return R(this.form.promo_amount)},formatAmountValue(){this.form.promo_amount=R(this.form.promo_amount)},unformatAmountValue(){this.form.promo_amount=pe(this.form.promo_amount)}},Validating(t){console.log(t)},mounted(){this.fetchBrands(),this.fetchCustomer()}},fe={class:"lg:p-2"},_e={class:"relative"},ge={class:"relative"},be={class:"relative"},ye={class:"relative"},ve={class:"relative"},we=s("label",null,"Is Percentage? : ",-1),Ce=s("i",{style:{"padding-left":"10px","font-size":"12px"}},"Check if promo value is in %",-1),xe={class:"relative"},Pe=s("label",null,"Is Enabled? : ",-1),Oe=s("i",{style:{"padding-left":"10px","font-size":"12px"}},"Check to enabled promo code",-1),Be={class:"flex gap-1 justify-end"};function Se(t,e,i,f,o,n){const v=l("Loading"),g=l("Multiselect"),p=l("FormGroup"),x=l("TextInput"),P=l("FlatPickr"),B=l("SubmitButton"),S=l("UpdateButton"),k=l("CloseButton"),F=l("FormModal");return d(),u(F,{title:o.state.isEdit?"Edit Promo Code":"Add New Promo Code",active:o.state.showModal,onSubmit:t.confirmSubmit,onClose:n.closeModal,themeClass:o.state.isEdit?"bg-primary-600":"bg-primary-800",sizeClass:"lg:w-1/2"},{default:m(()=>[o.state.isEdit&&o.state.isLoading?(d(),u(v,{key:0,text:"Fetching record"})):h("",!0),s("div",fe,[s("form",{onSubmit:e[12]||(e[12]=N((...r)=>t.confirmSubmit&&t.confirmSubmit(...r),["prevent"])),class:"space-y-4"},[o.state.isEdit&&o.state.isLoading?(d(),u(v,{key:0,text:"Fetching record"})):h("",!0),o.state.isSaving?(d(),u(v,{key:1,text:"Saving record"})):h("",!0),a(p,{label:"Brand",isRequired:!1},{default:m(()=>[s("div",_e,[a(g,{modelValue:o.form.brand_id,"onUpdate:modelValue":e[0]||(e[0]=r=>o.form.brand_id=r),"close-on-select":!0,searchable:!0,id:"company_id",options:o.brandOptions,onSelect:n.fetchModelsAndDealer},null,8,["modelValue","options","onSelect"])])]),_:1}),a(p,{label:"Dealer",isRequired:!1},{default:m(()=>[s("div",ge,[a(g,{modelValue:o.form.dealer_id,"onUpdate:modelValue":e[1]||(e[1]=r=>o.form.dealer_id=r),"close-on-select":!0,searchable:!0,options:o.dealerOptions},null,8,["modelValue","options"])])]),_:1}),a(p,{label:"Model",isRequired:!1},{default:m(()=>[s("div",be,[a(g,{modelValue:o.form.model_id,"onUpdate:modelValue":e[2]||(e[2]=r=>o.form.model_id=r),"close-on-select":!0,searchable:!0,options:o.modelOptions,onSelect:n.fetchCustomer},null,8,["modelValue","options","onSelect"])])]),_:1}),a(p,{label:"Customer"},{default:m(()=>[s("div",ye,[a(g,{modelValue:o.form.aha_owner_id,"onUpdate:modelValue":e[3]||(e[3]=r=>o.form.aha_owner_id=r),"close-on-select":!0,searchable:!0,id:"company_id",options:o.userOptions},null,8,["modelValue","options"])])]),_:1}),a(p,{label:"Promo Code",isRequired:!0},{default:m(()=>[a(x,{type:"text",placeholder:"Input promo code ",modelValue:o.form.promo_code,"onUpdate:modelValue":e[4]||(e[4]=r=>o.form.promo_code=r),error:o.errors.promo_code,classInput:"h-[48px]"},null,8,["modelValue","error"])]),_:1}),a(p,{label:"Promo Value",isRequired:!0},{default:m(()=>[a(x,{type:"text",placeholder:"Input promo value ",modelValue:o.form.promo_amount,"onUpdate:modelValue":e[5]||(e[5]=r=>o.form.promo_amount=r),error:o.errors.promo_amount,onBlur:e[6]||(e[6]=r=>n.formatAmountValue()),onFocus:e[7]||(e[7]=r=>n.unformatAmountValue()),classInput:"h-[48px]"},null,8,["modelValue","error"])]),_:1}),s("div",ve,[we,V(s("input",{type:"checkbox","onUpdate:modelValue":e[8]||(e[8]=r=>o.form.is_percentage=r)},null,512),[[M,o.form.is_percentage]]),Ce]),a(p,{label:"Promo Start Date",isRequired:!1},{default:m(()=>[a(P,{modelValue:o.form.start_date,"onUpdate:modelValue":e[9]||(e[9]=r=>o.form.start_date=r),class:"form-control",config:{wrap:!0,altFormat:"M j, Y",altInput:!0,enableTime:!1,dateFormat:"Y-m-d",minDate:"today"}},null,8,["modelValue"])]),_:1}),a(p,{label:"Promo Expiry Date",isRequired:!1},{default:m(()=>[a(P,{modelValue:o.form.expiry_date,"onUpdate:modelValue":e[10]||(e[10]=r=>o.form.expiry_date=r),class:"form-control",config:{wrap:!0,altFormat:"M j, Y",altInput:!0,enableTime:!1,dateFormat:"Y-m-d",minDate:"today"}},null,8,["modelValue"])]),_:1}),s("div",xe,[Pe,V(s("input",{type:"checkbox","onUpdate:modelValue":e[11]||(e[11]=r=>o.form.enabled=r)},null,512),[[M,o.form.enabled]]),Oe]),s("div",Be,[o.state.isEdit?(d(),u(S,{key:1,onClick:n.submitForm},null,8,["onClick"])):(d(),u(B,{key:0,onClick:n.submitForm},null,8,["onClick"])),a(k,{onClick:n.closeModal},null,8,["onClick"])])],32)])]),_:1},8,["title","active","onSubmit","onClose","themeClass"])}const ke=I(he,[["render",Se]]);const Fe={components:{Layout:K,CreateButton:z,InputGroup:W,Loading:E,EditButton:J,DeleteButton:H,Pagination:X,Form:ke,Card:$,Icon:L},setup(){},data(){return{title:"Promo Codes",breadcrumbs:[{text:"Home",href:"/"},{text:"Masterfile",href:"/masterfile/promo-codes"},{text:"Promo Codes",active:!0}],columns:[{label:"#",field:"#",sortable:!1},{label:"Promo Code",field:"promo_code"},{label:"Type",field:"is_percentage"},{label:"Value",field:"promo_amount"},{label:"Start Date",field:"start_date"},{label:"Expiry Date",field:"expiry_date"},{label:"Brand",field:"brand.name"},{label:"Dealer",field:"dealership.name"},{label:"Model",field:"model.name"},{label:"Customer(s)",field:"customers"},{label:"Created",field:"created_at"},{label:"Action",field:"action",sortable:!1}],perPageOptions:[{value:"10",label:"10"},{value:"50",label:"50"},{value:"100",label:"100"}],items:[],totalItems:0,searchQuery:null,serverOptions:{page:1,rowsPerPage:10,sortBy:"created_at",sortType:"asc"},state:{isLoading:!1,isEdit:!1,isDeleting:!1}}},watch:{serverOptions:{handler(){console.log(`perPage: ${this.serverOptions.rowsPerPage}`),this.fetchRecords()},deep:!0},searchQuery:Z.debounce(function(){this.fetchRecords()},800)},computed:{perPage:function(){return this.serverOptions.rowsPerPage},dealershipAccess(){return this.$store.userSettings.getDealershipAccess.filter(t=>t.system_id==4)}},methods:{async fetchRecords(){var t;this.state.isLoading=!0,this.state.isMounted=!1,await C.fetchRecords({keyword:this.searchQuery,page:this.serverOptions.page,per_page:this.serverOptions.rowsPerPage,sortBy:this.serverOptions.sortBy,sortType:this.serverOptions.sortType,dealers:(t=this.dealershipAccess)==null?void 0:t.map(e=>e.id)}).then(e=>{console.log("response");let i=e.data.data;console.log(i),this.items=i,this.items=i.map((f,o)=>({...f,created_at:moment(f.created_at).format("MMMM DD, YYYY hh:mma"),"#":(this.serverOptions.page-1)*this.serverOptions.rowsPerPage+(o+1)})),this.totalItems=e.data.total}).finally(()=>{this.state.isLoading=!1,this.state.isMounted=!0})},handlePageChange(t){console.log(t),console.log(this.serverOptions.page),this.serverOptions.page!=t&&(this.serverOptions.page=t)},handlePerPageChange(t){this.serverOptions.page=1,this.serverOptions.rowsPerPage=t},onSortChange(t){console.log(t),t[0].type!="none"&&(this.serverOptions.sortBy=t[0].field,this.serverOptions.sortType=t[0].type)},async deleteRecord(t){this.$swal.fire({title:"Are you sure?",text:"You want to delete this record?",icon:"warning",showCancelButton:!0,confirmButtonColor:"#34c38f",cancelButtonColor:"#f46a6a",confirmButtonText:"Yes, delete it!",background:this.$store.themeSettingsStore.isDark?"#1e293b":"#fff"}).then(e=>{console.log(e.value),e.value&&(this.state.isDeleting=!0,C.remove(t).then(i=>{i.status==200&&(this.$swal.fire({title:"Yaaay!",text:"Record has been deleted successfully.",type:"success",icon:"success",timer:2e3}),this.fetchRecords())}))}).catch(e=>{e.response&&e.response.status==401&&this.$swal.fire({title:"Ooops! something is wrong.",text:"Error deleting record. Please contact system administrator",type:"error",icon:"error",timer:2e3})}).finally(()=>{this.state.isDeleting=!1})},createRecord(){this.$refs.form.resetForm(),this.$refs.form.state.showModal=!0},editRecord(t){this.$refs.form.resetForm(),this.$refs.form.loadRecord(t),this.$refs.form.state.showModal=!0},handlePageChange(t){console.log(t),console.log(this.serverOptions.page),this.serverOptions.page!=t&&(this.serverOptions.page=t)},handlePerPageChange(t){this.serverOptions.page=1,this.serverOptions.rowsPerPage=t},reloadData(){this.fetchRecords()}},mounted(){this.fetchRecords()}},Ve=t=>(G("data-v-aa156d26"),t=t(),Q(),t),Me={class:"rounded-t bg-[url('@/assets/images/background/car-showroom.jpg')] bg-cover bg-[center] mih-h-24 pr-8"},De={class:"grid grid-cols-2"},Re={class:"p-8"},Ie={class:"bg-white bg-opacity-[0.5] rounded grid lg:grid-cols-2 p-2"},Ee={class:"flex gap-2 px-2"},Ue={class:"h-12 w-12 flex flex-col items-center justify-center rounded-full bg-white text-2xl mb-2 drop-shadow"},Ae={class:"text-3xl font-sans text-primary-800 py-1 drop-shadow"},Le={class:"bg-slate-200 slant-container w-full h-full float-right p-8"},Te={class:"flex justify-between"},Ne={class:"flex-grow"},Ye={key:0,class:"flex gap-1"},qe={key:1,class:"flex gap-1"},je={key:2,style:{width:"250px","max-height":"100px",overflow:"auto"},class:"flex gap-1"},Ge={class:"table-customer"},Qe=Ve(()=>s("tr",null,[s("th",null,"Customer Name"),s("th",null,"Used Code?")],-1)),ze={style:{width:"80%"}},Je={style:{width:"20%"}},He={class:"py-4 flex justify-end"};function Ke(t,e,i,f,o,n){const v=l("Icon"),g=l("InputGroup"),p=l("CreateButton"),x=l("EditButton"),P=l("DeleteButton"),B=l("Pagination"),S=l("vue-good-table"),k=l("Card"),F=l("Loading"),r=l("Form"),U=l("Layout");return d(),u(U,{breadcrumbs:o.breadcrumbs},{default:m(()=>[s("div",null,[a(k,{bodyClass:"p-0"},{default:m(()=>[s("div",Me,[s("div",De,[s("div",Re,[s("div",Ie,[s("div",Ee,[s("div",Ue,[a(v,{icon:"game-icons:city-car",class:"text-5xl text-primary-700"})]),s("div",Ae,O(o.title),1)])])]),s("div",Le,[s("div",null,[s("div",Te,[s("div",Ne,[a(g,{modelValue:o.searchQuery,"onUpdate:modelValue":e[0]||(e[0]=c=>o.searchQuery=c),class:"w-full focus:border-cyan-500 pt-1 pr-4",placeholder:"Search",type:"text",prependIcon:"heroicons-outline:search",merged:""},null,8,["modelValue"])]),s("div",null,[t.$ability.can("add","promoCode")?(d(),u(p,{key:0,onClick:n.createRecord},null,8,["onClick"])):h("",!0)])])])])])]),s("div",null,[a(S,{styleClass:"vgt-table lesspadding v-middle",columns:o.columns,rows:o.items,mode:"remote",search:!0,"sort-options":{enabled:!0},"pagination-options":{enabled:!0},onSortChange:n.onSortChange,"max-height":"600px"},{"table-row":m(c=>[c.column.field=="is_percentage"?(d(),w("div",Ye,[s("span",null,O(c.row.is_percentage==1?"(%)":"(₱)"),1)])):h("",!0),c.column.field=="action"?(d(),w("div",qe,[t.$ability.can("edit","promoCode")?(d(),u(x,{key:0,onClick:_=>n.editRecord(c.row)},null,8,["onClick"])):h("",!0),t.$ability.can("delete","promoCode")?(d(),u(P,{key:1,onClick:_=>n.deleteRecord(c.row.id)},null,8,["onClick"])):h("",!0)])):h("",!0),c.column.field=="customers"?(d(),w("div",je,[s("table",Ge,[Qe,(d(!0),w(Y,null,q(c.row.promo_details,(_,A)=>(d(),w("tr",{key:A},[s("td",ze,O(_.customer?_.customer.firstname+" "+_.customer.lastname:""),1),s("td",Je,[s("span",{class:j(_.used_code=="YES"?"text-success-500":"text-warning-500")},O(_.used_code),3)])]))),128))])])):h("",!0)]),"pagination-bottom":m(c=>[s("div",He,[a(B,{total:o.totalItems,current:o.serverOptions.page,"per-page":o.serverOptions.rowsPerPage,onPageChanged:n.handlePageChange,pageChanged:c.pageChanged,perPageChanged:c.perPageChanged,enableSelect:"",perPageOptions:o.perPageOptions,onChangePerPage:n.handlePerPageChange},null,8,["total","current","per-page","onPageChanged","pageChanged","perPageChanged","perPageOptions","onChangePerPage"])])]),_:1},8,["columns","rows","onSortChange"])])]),_:1}),o.state.isLoading?(d(),u(F,{key:0,text:"Feching records"})):h("",!0),a(r,{onCloseModal:e[1]||(e[1]=c=>o.state.showModal=!1),ref:"form",onReload:n.reloadData},null,8,["onReload"])])]),_:1},8,["breadcrumbs"])}const wt=I(Fe,[["render",Ke],["__scopeId","data-v-aa156d26"]]);export{wt as default};