ldc-le-gaulois-pro/resources/ts/components/fo/SaveProductComponent.vue
Vincent BRIDIER dbadf851b6
ts-1680
2023-08-08 19:54:56 +02:00

273 lines
8.2 KiB
Vue

<template>
<div :class="`save-product-component save-product`">
<div class="text-center text-lg-start pb-4">
<p class="ff-poppins-medium fs-lg">
{{ __("Conditionnement") }}
</p>
<p>{{ __("Ce produit est disponible en :") }}</p>
<div class="d-flex flex-wrap">
<div
v-for="(item, index) in itemPackaging"
:key="index"
>
<input
:id="`packaging-${String(index)}`"
:data-index="item.value"
class="packaging d-none input-pack input-checkbox-pack"
type="checkbox"
>
<div class="butn-wrap user-select-none">
<label
class="label-checkbox label-interest butn-cinq fs-xsm position-relative mb-1"
role="button"
:for="`packaging-${String(index)}`"
>
{{ item.value }}
</label>
</div>
</div>
</div>
</div>
<div class="text-center text-lg-start pb-4">
<p class="ff-poppins-medium fs-lg">
{{ __("Calibre") }}
</p>
<p>{{ __("Ce produit est disponible en :") }}</p>
<div class="d-flex flex-wrap">
<div
v-for="(item, index) in itemCaliber"
:key="index"
>
<input
:id="`caliber-${String(index)}`"
:data-index="item.value"
class="caliber d-none input-pack input-checkbox-pack"
type="checkbox"
>
<div class="butn-wrap user-select-none">
<label
class="label-checkbox label-interest butn-cinq fs-xsm position-relative mb-1"
role="button"
:for="`caliber-${String(index)}`"
>
{{ item.value }}
</label>
</div>
</div>
</div>
</div>
<div
class="butn-wrap d-flex justify-content-center justify-content-lg-start text-center my-4 w-100 w-lg-auto"
>
<button
class="interest-butn butn-prim mx-0 py-lg-2"
@click.prevent="addProduct"
:title="
__(
'Cliquez ici pour ajouter cette sélection et la retrouver facilement dans le formulaire de contact'
)
"
data-bs-tooltip="tooltip"
>
{{ __("Je suis intéressé.e") }}
</button>
<!-- LOADING -->
<div
v-if="isLoading"
class="text-center"
>
<FontAwesomeIcon
icon="fa-solid fa-circle-notch"
class="fa-spin h1"
/>
</div>
</div>
</div>
</template>
<script lang="ts">
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { Tooltip } from "bootstrap";
import { defineComponent } from "vue";
import parseLaravelErrorMessages from "../../modules/parseLaravelErrorMessages";
import route from "../../modules/route";
import toast from "../../modules/toast";
import trans from "../../modules/trans";
export default defineComponent({
mixins: [parseLaravelErrorMessages, route, toast, trans],
components: {
FontAwesomeIcon,
},
data(): {
product: LaravelModel;
itemPackaging: {
value: string;
}[];
itemCaliber: {
value: string;
}[];
/** (computed on ajax calls) selected packaging ids */
packagingChecked: string[];
/** (computed on ajax calls) selected caliber ids */
caliberChecked: string[];
rangeColor: string;
messages: string[];
messageType: boolean;
isLoading: boolean;
tooltipList: HTMLButtonElement[];
} {
return {
product: {},
itemPackaging: [
{
value: "",
},
],
itemCaliber: [
{
value: "",
},
],
packagingChecked: [""],
caliberChecked: [""],
rangeColor: "",
messages: [],
messageType: false,
isLoading: false,
tooltipList: [],
};
},
mounted() {
const json = String(this.$attrs.json ?? "{}");
const data = JSON.parse(json);
this.product = data.product;
this.itemPackaging = data.packaging;
this.itemCaliber = data.caliber;
this.rangeColor = data.rangeColor;
this.$nextTick(() => {
this.initComponent();
this.updateBootstrapTooltip();
});
},
methods: {
/**
* Init the component with some querySelector.
*/
initComponent() {
const labelCheckbox = document.querySelectorAll(".label-checkbox");
labelCheckbox.forEach((element) => {
element.addEventListener("click", () => {
element.classList.toggle("range-bg-color-checked");
});
});
},
/**
* Call a specific route to save a product, thanks to
* the slug of the model,
* the id of packaging and caliber checked input
*/
addProduct(): void {
const saveProductRoute = route.methods.route(
"products.add-product-to-basket",
{ PRODUCT: String(this.product.slug) }
);
if (!saveProductRoute) {
throw new Error("Undefined route products.add-product-to-basket");
}
this.prepareIdsCheckInputs();
this.isLoading = true;
window.axios
.post(saveProductRoute, {
packaging: this.packagingChecked,
caliber: this.caliberChecked,
})
.then((data) => {
this.notify(
this.__("Ce produit a bien été enregistré dans la demande de contact.")
);
document
.querySelectorAll(".counter-wrapper")
.forEach((value: Element) => {
value.textContent = data.data.saveProductInBasketCounter;
if (data.data.saveProductInBasketCounter > 0) {
value.classList.remove("hide-counter-wrapper");
}
});
})
.catch((e) => {
let message = trans.methods.__("Erreur de la communication serveur");
if (e.response.status === 422) {
message =
this.parseValidationErrors(e.response?.data?.errors ?? {}) ||
message;
if (window.vueDebug) {
console.warn(e.response.data.errors);
}
} else if (e.response.status === 419) {
// * CSRF TOKEN MISMATCH (On ne pourrais plus faire d'appels AJAX sans recharger la page)
this.errorNotify(
this.__("Votre session a expiré, la page va être rechargée")
);
setTimeout(() => window.location.reload(), 2000);
} else if (e.response.status === 403) {
// * Access denied
this.errorNotify(
this.__("Vous n'êtes pas autorisé a effectuer cette action")
);
setTimeout(() => window.location.reload(), 2000);
} else {
if (window.vueDebug) {
console.error(e);
}
}
this.errorNotify(message);
})
.then(() => {
this.isLoading = false;
});
},
/**
* Get the id of all inputs checked,
* return boolean according to the inputs checked.
*/
prepareIdsCheckInputs(): void {
const packagingAll = [].slice.call(
document.querySelectorAll(".packaging")
) as Array<HTMLInputElement>;
this.packagingChecked = packagingAll
.filter((x) => x.checked)
.map((x) => x.dataset.index) as string[];
const caliberAll = [].slice.call(
document.querySelectorAll(".caliber")
) as Array<HTMLInputElement>;
this.caliberChecked = caliberAll
.filter((x) => x.checked)
.map((x) => x.dataset.index) as string[];
},
/**
* Update Bootstrap tooltips.
*/
updateBootstrapTooltip() {
let newTooltipList = [].slice.call(
document.querySelectorAll(".save-product [data-bs-tooltip=\"tooltip\"]")
) as HTMLButtonElement[];
let tmp = newTooltipList.filter((x) => !this.tooltipList.includes(x));
tmp.map((tooltip) => {
return new Tooltip(tooltip);
});
this.closeBootstrapTooltip();
this.tooltipList = newTooltipList;
},
/**
* Close all Bootstrap tooltips.
*/
closeBootstrapTooltip() {
this.tooltipList.forEach((tooltip) => {
tooltip.blur();
Tooltip.getInstance(tooltip)?.hide();
});
},
},
});
</script>