@salla.sa/twilight-components
Version:
Salla Web Component
4 lines • 10.9 kB
JavaScript
/*!
* Crafted with ❤ by Salla
*/
import{r as s,h as i,H as e,a as t}from"./p-BHYtfMwX.js";function l(s,i){localStorage.getItem("salla-delivery-promise-debug")&&(void 0!==i?console.log(s,i):console.log(s))}async function r(s,i){l("fetchCities start",{productId:s,keyword:i});const e=null!=i?`?keyword=${encodeURIComponent(i)}`:"",t=await salla.api.request(salla.url.api(`products/${s}/delivery-promises/cities${e}`));return t.success&&Array.isArray(t.data)&&0!==t.data.length?(l("fetchCities success",{count:t.data.length}),{cities:t.data}):(l("fetchCities: no data",{response:t}),{cities:[]})}function a(){const s=(Boolean(salla.config.get("store.settings.bullet_delivery.settings.remember_last_session"))?salla.storage.store:salla.storage.session).get("bullet_delivery_intent");return s&&"object"==typeof s?s:null}const o={deliveryTo:"توصيل إلى",pickupFromBranch:"الاستلام من فرع",noResults:"لا توجد نتائج",selectCity:"اختر المدينة",changeCityTitle:"تغيير المدينة",changeCitySubtitle:"",cityFieldLabel:"المدينة",modalSearchPlaceholder:"ابحث عن مدينة",confirmAddress:"تأكيد العنوان",errorDeliveryPromise:"لا يتوفر وعد تسليم لهذه المدينة",errorPickupPromise:"لا يتوفر وعد تسليم لهذا الفرع"},n="salla-bullet-delivery-override-ip",h=class{constructor(i){s(this,i),this.isDeliveryPromiseEnabled=!1,this.isLoginCycleEnabled=!1,this.canRender=!1,this.labels=o,this.selectedLabel=null,this.deliveryMessage=null,this.hasError=!1,this.errorMessage="",this.isLoadingPromises=!1,this.selectedCityLoginCycle=null,this.selectedBranchLoginCycle=null,this.cities=[],this.selectedCity=null,this.isLoadingCities=!1,this.cityPendingSelection=null,this.modalCities=[],this.isSearchingCities=!1,this.citySearchCounter=0,this.onBulletDeliveryConfirmed=()=>{this.applyBulletIntent()},this.handleCitySearch=s=>{if(clearTimeout(this.citySearchTimer),!s.trim())return this.modalCities=[...this.cities],void(this.isSearchingCities=!1);this.citySearchTimer=setTimeout((()=>this.searchCitiesRemote(s)),300)},this.handleHeaderClick=s=>{s.stopPropagation(),this.isLoginCycleEnabled?this.openBulletDeliveryModal():this.openCityChangeModal()}}async componentDidLoad(){await salla.onReady(),await salla.lang.onLoaded(),this.labels={deliveryTo:salla.lang.getWithDefault("pages.products.promise_deliver_to",o.deliveryTo),pickupFromBranch:salla.lang.getWithDefault("pages.products.promise_pickup_from_branch",o.pickupFromBranch),noResults:salla.lang.getWithDefault("common.elements.no_options",o.noResults),selectCity:salla.lang.getWithDefault("common.elements.select_city",o.selectCity),changeCityTitle:salla.lang.getWithDefault("pages.products.promise_change_city_title",o.changeCityTitle),changeCitySubtitle:salla.lang.getWithDefault("pages.products.promise_change_city_subtitle","قد تتغيّر مدة التوصيل حسب المدينة."),cityFieldLabel:salla.lang.getWithDefault("pages.products.promise_city_field",o.cityFieldLabel),modalSearchPlaceholder:salla.lang.getWithDefault("pages.products.promise_search_city",o.modalSearchPlaceholder),confirmAddress:salla.lang.getWithDefault("pages.checkout.confirm_address",o.confirmAddress),errorDeliveryPromise:salla.lang.getWithDefault("pages.products.promise_delivery_not_available",o.errorDeliveryPromise),errorPickupPromise:salla.lang.getWithDefault("pages.products.promise_pickup_not_available",o.errorPickupPromise)},this.isDeliveryPromiseEnabled=salla.config.get("store.features",[]).includes("delivery-promises"),this.isLoginCycleEnabled=salla.config.get("store.features",[]).includes("bullet-delivery-v2"),this.productId=salla.config.get("page.id"),this.isDeliveryPromiseEnabled?this.isLoginCycleEnabled?await this.initLoginCycleFlow():(this.selectedLabel=`${this.labels.deliveryTo} ${this.labels.selectCity}`,await this.loadCities()):this.canRender=!1}disconnectedCallback(){window.removeEventListener("bulletDeliveryConfirmed",this.onBulletDeliveryConfirmed)}getIPDeliveryLocation(){const s="store.shipping.delivery_location",i={cityId:salla.config.get(`${s}.city_id`),cityName:salla.config.get(`${s}.city_name`)};return localStorage.getItem(n)?JSON.parse(localStorage.getItem(n)):i}async initLoginCycleFlow(){const s=this.applyBulletIntent(),{cityId:i,cityName:e}=this.getIPDeliveryLocation();l("delivery promise login cycle flow getIPDeliveryLocation",this.getIPDeliveryLocation()),i&&e&&!s&&(this.selectedLabel=`${this.labels.deliveryTo} ${e}`,await this.loadDeliveryMessage(i,"city")),this.canRender=!0,window.addEventListener("bulletDeliveryConfirmed",this.onBulletDeliveryConfirmed)}applyBulletIntent(){const s=function(){const s=a();if(!s)return null;if("address"===s.type){const i=s.address_details?.city,e=null!=i?.id?Number(i.id):null!=s.city_id?Number(s.city_id):null,t=i?.name?.trim()||"";return null!=e?{type:"address",option:{id:e,name:t}}:null}if("branch"===s.type){const i=null!=s.branch_id?Number(s.branch_id):null!=s.branch_details?.id?Number(s.branch_details.id):null,e=s.branch_details?.name?.trim()||"";return null!=i?{type:"branch",option:{id:i,name:e}}:null}return null}();return s?("address"===s.type?(this.selectedCityLoginCycle=s.option,this.selectedBranchLoginCycle=null,this.selectedLabel=`${this.labels.deliveryTo} ${s.option.name||this.labels.selectCity}`,this.loadDeliveryMessage(s.option.id,"city")):(this.selectedBranchLoginCycle=s.option,this.selectedCityLoginCycle=null,this.selectedLabel=`${this.labels.pickupFromBranch} ${s.option.name}`,this.loadDeliveryMessage(s.option.id,"branch")),!0):(this.selectedLabel=`${this.labels.deliveryTo} ${this.labels.selectCity}`,this.selectedCityLoginCycle=null,this.selectedBranchLoginCycle=null,this.deliveryMessage=null,!1)}openBulletDeliveryModal(){salla.event.emit("salla::bullet-delivery.modal.open.requested",function(){const s=a(),i={};if("address"===s?.type&&null!=s.address_id&&(i.preselected_address_id=Number(s.address_id)),"branch"===s?.type){const e=s.branch_id??s.branch_details?.id;null!=e&&(i.preselected_branch_id=Number(e))}return i}())}async loadCities(){this.isLoadingCities=!0,this.hasError=!1;const{cityId:s,cityName:i}=this.getIPDeliveryLocation();l("delivery promise standard flow getIPDeliveryLocation",this.getIPDeliveryLocation());try{const{cities:e}=await r(this.productId);if(!e.length)return void(this.canRender=!1);if(this.cities=e,this.canRender=!0,s&&i){this.selectedLabel=`${this.labels.deliveryTo} ${i}`;const e=this.cities.find((i=>String(i.id)===String(s)));e&&(l("delivery promise standard flow autoCity found",e),this.selectedCity=e),await this.loadDeliveryMessage(s,"city")}}catch(s){this.hasError=!0,this.errorMessage=s.message||"Failed to load cities",this.canRender=!1}finally{this.isLoadingCities=!1}}async loadDeliveryMessage(s,i){this.isLoadingPromises=!0,this.hasError=!1,this.deliveryMessage=null;try{this.deliveryMessage=await async function(s,i,e,t){l("fetchDeliveryMessage start",{productId:s,id:i,optionType:e});let r="";r="city"!==e||t?`?reference_id=${i}&reference_type=${e}`:`?reference_id=${i}`;const a=await salla.api.withoutNotifier((()=>salla.api.request(salla.url.api(`products/${s}/delivery-promises${r}`))));if(!a.success)throw l("fetchDeliveryMessage error",{response:a}),new Error(a.error?.message||"Failed to fetch delivery promise");const o=a.data?.message?.trim();return l("fetchDeliveryMessage success",{message:o}),o||null}(this.productId,s,i,this.isLoginCycleEnabled)}catch(s){this.hasError=!0,this.errorMessage="city"===i?this.labels.errorDeliveryPromise:this.labels.errorPickupPromise}finally{this.isLoadingPromises=!1}}async openCityChangeModal(){this.cityModalRef&&(this.cityPendingSelection=null,this.modalCities=[...this.cities],await this.cityModalRef.setTitle(this.labels.changeCityTitle),await this.cityModalRef.open())}async searchCitiesRemote(s){const i=++this.citySearchCounter;this.isSearchingCities=!0;try{const{cities:e}=await r(this.productId,s);if(i!==this.citySearchCounter)return;this.modalCities=e}catch{if(i!==this.citySearchCounter)return;this.modalCities=[]}finally{i===this.citySearchCounter&&(this.isSearchingCities=!1)}}async handleConfirmCityModal(){if(!this.cityPendingSelection)return void await(this.cityModalRef?.close());const s=this.cityPendingSelection;this.selectedCity=s,this.selectedLabel=`${this.labels.deliveryTo} ${function(s){const i=salla.config.get("user.language_code");return i&&"ar"!==i&&s.name_en?.trim()?s.name_en.trim():s.name}(s)}`,await this.loadDeliveryMessage(s.id,"city"),await(this.cityModalRef?.close())}renderLoadingSkeleton(){return i(e,{class:"s-delivery-promise-wrapper s-delivery-promise-skeleton"},i("div",{class:"s-delivery-promise-container"},i("div",{class:"s-delivery-promise-header s-delivery-promise-header-skeleton"},i("div",{class:"s-delivery-promise-location"},i("salla-skeleton",{height:"14px",width:"180px"})),i("salla-skeleton",{height:"18px",width:"18px"})),i("div",{class:"s-delivery-promise-loading"},i("salla-skeleton",{height:"20px",width:"80%"}))))}renderDeliveryMessage(){return this.isLoadingPromises?i("div",{class:"s-delivery-promise-loading"},i("salla-skeleton",{height:"20px",width:"80%"})):this.deliveryMessage?i("div",{class:"s-delivery-promise-message"},this.deliveryMessage):null}renderCityModalBody(){return i("div",{class:"s-delivery-promise-modal-body"},i("salla-searchable-dropdown",{label:this.labels.cityFieldLabel,placeholder:this.labels.modalSearchPlaceholder,items:this.modalCities,selectedItem:this.cityPendingSelection,searching:this.isSearchingCities,required:!0,noResultsText:this.labels.noResults,inputId:"s-delivery-promise-modal-search",onItemSelected:s=>{this.cityPendingSelection=s.detail},onSearchInput:s=>{this.handleCitySearch(s.detail)}}))}renderCityChangeModal(){return this.isLoginCycleEnabled?null:i("salla-modal",{id:"s-delivery-promise-city-modal",ref:s=>{this.cityModalRef=s},class:"s-delivery-promise-city-modal",isClosable:!0,width:"md","modal-title":this.labels.changeCityTitle,subTitle:this.labels.changeCitySubtitle},this.renderCityModalBody(),i("salla-button",{slot:"footer",width:"wide",disabled:!this.cityPendingSelection,onClick:()=>this.handleConfirmCityModal()},!this.isLoadingPromises&&this.labels.confirmAddress))}render(){return this.isDeliveryPromiseEnabled?this.isLoadingCities?this.renderLoadingSkeleton():this.canRender?i(e,{class:"s-delivery-promise-wrapper"},i("div",{class:"s-delivery-promise-container"},i("div",{class:"s-delivery-promise-header",onClick:this.handleHeaderClick},i("div",{class:"s-delivery-promise-location"},i("span",{class:"s-delivery-promise-title"},this.selectedLabel)),i("i",{class:"sicon-keyboard_arrow_down s-delivery-promise-arrow"})),this.hasError&&i("div",{class:"s-delivery-promise-error"},this.errorMessage),!this.hasError&&this.renderDeliveryMessage()),this.renderCityChangeModal()):null:null}get host(){return t(this)}};export{h as salla_delivery_promise}