haiku-atelier-2024/web/app/themes/haiku-atelier-2024/assets/js/scripts-page-panier.js
2024-11-15 14:04:01 +01:00

458 lines
22 KiB
JavaScript

import { z } from "./index.CeK6pfoJ.js";
import { p as parse, V as ValiError } from "./index.BueHQ6RV.js";
import { a as ROUTE_API_RETIRE_ARTICLE_PANIER, b as ROUTE_API_MAJ_ARTICLE_PANIER, c as ROUTE_API_MAJ_CLIENT, d as ROUTE_API_NOUVELLE_COMMANDES } from "./api.js";
import { l as SELECTEUR_ENTREES_PANIER, m as SELECTEUR_CONTENEUR_PANIER, n as SELECTEUR_SOUS_TOTAL_PRODUITS, o as SELECTEUR_SOUS_TOTAL_LIVRAISON_COUT, p as SELECTEUR_SOUS_TOTAL_LIVRAISON_PRESTATAIRE, q as SELECTEUR_TOTAL_PANIER, r as SELECTEUR_BOUTON_SEPARATION_ADRESSES, s as SELECTEUR_FORMULAIRE_PANIER, t as SELECTEUR_FORMULAIRE_FACTURATION, u as SELECTEUR_BOUTON_ACTIONS_FORMULAIRE, v as ATTRIBUT_CLE_PANIER, w as SELECTEUR_BOUTON_SOUSTRACTION_QUANTITE, x as SELECTEUR_CHAMP_QUANTITE_LIGNE_PANIER, y as SELECTEUR_BOUTON_ADDITION_QUANTITE, z as SELECTEUR_BOUTON_SUPPRESSION_PANIER, B as ATTRIBUT_DESACTIVE, A as ATTRIBUT_CONTIENT_ARTICLES, C as SELECTEUR_PRIX_LIGNE_PANIER, k as ATTRIBUT_HIDDEN } from "./dom.js";
import { N as NOM_CANAL_BOUTON_PANIER, a as NOM_CANAL_CONTENU_PANIER } from "./messages3.js";
import { r as recupereElementOuLeve, a as recupereElementAvecSelecteur, b as recupereElementsAvecSelecteur, e as eitherSessionStorageGet, c as eitherJsonParse } from "./dom2.js";
import { l as leveServerError, r as reporteErreur, a as leveErreur } from "./erreurs.js";
import { e as estReponse500, a as estError } from "./gardes.js";
import { e as emetMessageMajBoutonPanier, a as emetMessageMajContenuPanier, v as valideMessageMajBoutonPanier, b as valideMessageMajContenuPanier } from "./messages.js";
import { p as postBackend, t as traiteReponseBackendWCSelonCodesHTTP } from "./reseau.js";
import { W as WCStoreCartSchema } from "./cart.js";
import { W as WCStoreCartRemoveItemArgsSchema } from "./cart-remove-item.js";
import { W as WCStoreCartUpdateCustomerArgsSchema } from "./cart-update-customer.js";
import { W as WCStoreCartUpdateItemArgsSchema } from "./cart-update-item.js";
import { W as WCStoreShippingRateShippingRateSchema } from "./couts-livraison.js";
import { W as WCV3OrdersArgsSchema, a as WCV3OrderSchema } from "./orders2.js";
import { c as recupereElementsDocumentEither, r as recupereElementDocumentEither, y, p as propEither, a as recupereElementDansDocumentOuLeve } from "./utils.js";
import { e as eitherParse } from "./validation.js";
import { p as pipe } from "./pipe.XPB0wEfw.js";
import { l } from "./index-0eef19ec.CFsloYN6.js";
import { M as Maybe, E as Either } from "./Either.wHNxn7Os.js";
import "./exports.DT-46nyp.js";
import "./messages2.js";
import "./erreurs2.js";
import "./cart2.js";
import "./adresses.js";
import "./orders3.js";
import "./belt_Option-91f3b350.BKMoZFhU.js";
const ETATS_PAGE = _etats;
const ENTREES_PANIER_EITHER = recupereElementsDocumentEither(
SELECTEUR_ENTREES_PANIER
);
const CONTENEUR_PANIER = pipe(
recupereElementDocumentEither(SELECTEUR_CONTENEUR_PANIER),
recupereElementOuLeve
);
const SOUS_TOTAL_PRODUITS = pipe(
recupereElementDocumentEither(SELECTEUR_SOUS_TOTAL_PRODUITS),
recupereElementOuLeve
);
const SOUS_TOTAL_LIVRAISON_COUT = pipe(
recupereElementDocumentEither(SELECTEUR_SOUS_TOTAL_LIVRAISON_COUT),
recupereElementOuLeve
);
const SOUS_TOTAL_LIVRAISON_PRESTATAIRE = pipe(
recupereElementDocumentEither(SELECTEUR_SOUS_TOTAL_LIVRAISON_PRESTATAIRE),
recupereElementOuLeve
);
const TOTAL_PANIER = pipe(
recupereElementDocumentEither(SELECTEUR_TOTAL_PANIER),
recupereElementOuLeve
);
const BOUTON_SEPARATION_ADRESSES = pipe(
recupereElementDocumentEither(SELECTEUR_BOUTON_SEPARATION_ADRESSES),
recupereElementOuLeve
);
const FORMULAIRE_PANIER = pipe(
recupereElementDocumentEither(SELECTEUR_FORMULAIRE_PANIER),
recupereElementOuLeve
);
const FORMULAIRE_FACTURATION = pipe(
recupereElementDocumentEither(SELECTEUR_FORMULAIRE_FACTURATION),
recupereElementOuLeve
);
let BOUTON_ACTIONS_FORMULAIRE = pipe(
recupereElementDocumentEither(SELECTEUR_BOUTON_ACTIONS_FORMULAIRE),
recupereElementOuLeve
);
const recupereElementDansEntreePanierOuLeve = (entree) => (selecteur) => pipe(recupereElementAvecSelecteur(entree)(selecteur), recupereElementOuLeve);
const desactiveBoutonsEntreesPanier = (entrees) => entrees.forEach((entree) => {
const recupereElementDansEntree = recupereElementDansEntreePanierOuLeve(entree);
const elements = {
boutonAddition: recupereElementDansEntree(SELECTEUR_BOUTON_ADDITION_QUANTITE),
boutonSoustraction: recupereElementDansEntree(SELECTEUR_BOUTON_SOUSTRACTION_QUANTITE),
boutonSuppression: recupereElementDansEntree(SELECTEUR_BOUTON_SUPPRESSION_PANIER)
};
elements.boutonSoustraction.setAttribute(ATTRIBUT_DESACTIVE, "");
elements.boutonAddition.setAttribute(ATTRIBUT_DESACTIVE, "");
elements.boutonSuppression.setAttribute(ATTRIBUT_DESACTIVE, "");
elements.boutonSuppression.textContent = "C= C= C= C= C=┌(;・ω・)┘";
});
const majEtatsActivationBoutons = (entrees) => entrees.forEach((entree) => {
const recupereElementDansEntree = recupereElementDansEntreePanierOuLeve(entree);
const elements = {
boutonAddition: recupereElementDansEntree(SELECTEUR_BOUTON_ADDITION_QUANTITE),
boutonSoustraction: recupereElementDansEntree(SELECTEUR_BOUTON_SOUSTRACTION_QUANTITE),
boutonSuppression: recupereElementDansEntree(SELECTEUR_BOUTON_SUPPRESSION_PANIER),
champQuantite: recupereElementDansEntree(SELECTEUR_CHAMP_QUANTITE_LIGNE_PANIER)
};
Number(elements.champQuantite?.value) === 1 ? elements.boutonSoustraction.setAttribute(ATTRIBUT_DESACTIVE, "") : elements.boutonSoustraction.removeAttribute(ATTRIBUT_DESACTIVE);
elements.boutonAddition.removeAttribute(ATTRIBUT_DESACTIVE);
elements.boutonSuppression.removeAttribute(ATTRIBUT_DESACTIVE);
elements.boutonSuppression.textContent = "Remove";
});
const initialiseMajEntreesPanier = () => {
ENTREES_PANIER_EITHER.ifRight((entrees) => {
entrees.forEach((entree) => {
const recupereElementDansEntree = recupereElementDansEntreePanierOuLeve(entree);
const clePanier = Maybe.fromNullable(entree.getAttribute(ATTRIBUT_CLE_PANIER)).ifNothing(() => {
entree.remove();
return;
}).orDefault("CLE_PANIER_INEXISTANTE");
const boutonSoustraction = recupereElementDansEntree(SELECTEUR_BOUTON_SOUSTRACTION_QUANTITE);
const champQuantite = recupereElementDansEntree(SELECTEUR_CHAMP_QUANTITE_LIGNE_PANIER);
const boutonAddition = recupereElementDansEntree(SELECTEUR_BOUTON_ADDITION_QUANTITE);
const boutonSuppression = recupereElementDansEntree(SELECTEUR_BOUTON_SUPPRESSION_PANIER);
boutonSuppression.addEventListener("click", () => {
Either.encase(
() => parse(WCStoreCartRemoveItemArgsSchema, { key: clePanier })
).map(async (args) => {
desactiveBoutonsEntreesPanier(entrees);
await postBackend({
corps: JSON.stringify(args),
nonce: ETATS_PAGE.nonce,
route: ROUTE_API_RETIRE_ARTICLE_PANIER
}).then(async (reponse) => {
if (estReponse500(reponse)) leveServerError("500 Server Error");
pipe(
// Récupère la Réponse
await reponse.json(),
// Traite tous les codes HTTPs possibles
(corpsReponse) => traiteReponseBackendWCSelonCodesHTTP(
corpsReponse,
WCStoreCartSchema
),
// Émets des Messages via BroadcastChannels pour la mise à jour de la page
l.tap((panier) => {
emetMessageMajBoutonPanier({ quantiteProduits: panier.items_count });
emetMessageMajContenuPanier({
produits: panier.items,
sousTotalPanier: Number(panier.totals.total_price) / 100,
totalPanier: Number(panier.totals.total_items) / 100
});
entree.remove();
})
);
}).catch((e) => {
if (estError(e)) {
reporteErreur(e);
} else {
console.error("e n'est pas une Erreur ?!", e);
}
majEtatsActivationBoutons(entrees);
});
}).ifLeft((erreur) => reporteErreur(erreur));
});
boutonSoustraction.addEventListener("click", (evenement) => {
Maybe.fromNullable(champQuantite.valueAsNumber).filter((valeur) => valeur > 1).ifJust((valeur) => {
Either.encase(
() => parse(WCStoreCartUpdateItemArgsSchema, { key: clePanier, quantity: valeur - 1 })
).map(async (args) => {
desactiveBoutonsEntreesPanier(entrees);
await postBackend({
corps: JSON.stringify(args),
nonce: ETATS_PAGE.nonce,
route: ROUTE_API_MAJ_ARTICLE_PANIER
}).then(async (reponse) => {
if (estReponse500(reponse)) leveServerError("500 Server Error");
pipe(
// Récupère la Réponse
await reponse.json(),
// Traite tous les codes HTTPs possibles
(corpsReponse) => traiteReponseBackendWCSelonCodesHTTP(
corpsReponse,
WCStoreCartSchema
),
l.tap((panier) => {
emetMessageMajBoutonPanier({ quantiteProduits: panier.items_count });
emetMessageMajContenuPanier({
produits: panier.items,
sousTotalPanier: Number(panier.totals.total_price) / 100,
totalPanier: Number(panier.totals.total_items) / 100
});
})
);
}).catch((e) => {
if (estError(e)) {
reporteErreur(e);
} else {
console.error("e n'est pas une Erreur ?!", e);
}
majEtatsActivationBoutons(entrees);
});
});
});
});
boutonAddition.addEventListener("click", () => {
Maybe.fromNullable(champQuantite.valueAsNumber).ifJust((valeur) => {
desactiveBoutonsEntreesPanier(entrees);
Either.encase(
() => parse(WCStoreCartUpdateItemArgsSchema, { key: clePanier, quantity: valeur + 1 })
).map(async (args) => {
await postBackend({
corps: JSON.stringify(args),
nonce: ETATS_PAGE.nonce,
route: ROUTE_API_MAJ_ARTICLE_PANIER
}).then(async (reponse) => {
if (estReponse500(reponse)) leveServerError("500 Server Error");
pipe(
// Récupère la Réponse
await reponse.json(),
// Traite tous les codes HTTPs possibles
(corpsReponse) => traiteReponseBackendWCSelonCodesHTTP(
corpsReponse,
WCStoreCartSchema
),
l.tap((panier) => {
emetMessageMajBoutonPanier({ quantiteProduits: panier.items_count });
emetMessageMajContenuPanier({
produits: panier.items,
sousTotalPanier: Number(panier.totals.total_price) / 100,
totalPanier: Number(panier.totals.total_items) / 100
});
})
);
}).catch((e) => {
if (estError(e)) {
reporteErreur(e);
} else {
console.error("e n'est pas une Erreur ?!", e);
}
majEtatsActivationBoutons(entrees);
});
});
});
});
});
});
};
const initialiseMajConteneurPanier = () => {
new BroadcastChannel(NOM_CANAL_BOUTON_PANIER).onmessage = (evenementMessage) => {
valideMessageMajBoutonPanier(evenementMessage).map(y.getUnsafe("donnees")).ifRight((donnees) => {
CONTENEUR_PANIER.setAttribute(ATTRIBUT_CONTIENT_ARTICLES, String(donnees.quantiteProduits !== 0));
});
};
};
const initialiseMajContenuPanier = () => {
new BroadcastChannel(NOM_CANAL_CONTENU_PANIER).onmessage = (message) => {
valideMessageMajContenuPanier(message).chain(propEither("donnees")).ifRight((donnees) => {
donnees.produits.forEach((ligne) => {
ENTREES_PANIER_EITHER.ifRight((entrees) => {
Maybe.fromNullable(entrees.find((entree) => entree.getAttribute(ATTRIBUT_CLE_PANIER) === ligne.key)).ifJust(
(entree) => {
const recupereElementDansEntree = recupereElementDansEntreePanierOuLeve(entree);
const prixLigne = recupereElementDansEntree(SELECTEUR_PRIX_LIGNE_PANIER);
const champQuantite = recupereElementDansEntree(
SELECTEUR_CHAMP_QUANTITE_LIGNE_PANIER
);
entree.setAttribute("data-quantite", String(ligne.quantity));
prixLigne.textContent = `${String(Number(ligne.totals.line_total) / 100)}`;
champQuantite.setAttribute("value", String(ligne.quantity));
majEtatsActivationBoutons(entrees);
}
);
SOUS_TOTAL_PRODUITS.textContent = `${String(donnees.totalPanier)}`;
TOTAL_PANIER.textContent = `${String(donnees.totalPanier)}`;
});
});
}).ifLeft((erreur) => {
reporteErreur(erreur);
ENTREES_PANIER_EITHER.ifRight((entrees) => majEtatsActivationBoutons(entrees));
});
};
};
const initialiseMajFormulairesPanier = () => {
BOUTON_SEPARATION_ADRESSES.addEventListener("click", () => {
Maybe.fromFalsy(BOUTON_SEPARATION_ADRESSES.checked).ifJust(() => {
FORMULAIRE_FACTURATION.removeAttribute(ATTRIBUT_HIDDEN);
recupereElementsAvecSelecteur(FORMULAIRE_FACTURATION)("input, select").ifRight(
(champs) => champs.forEach((champ) => champ.removeAttribute(ATTRIBUT_DESACTIVE))
);
}).ifNothing(() => {
FORMULAIRE_FACTURATION.setAttribute(ATTRIBUT_HIDDEN, "");
recupereElementsAvecSelecteur(FORMULAIRE_FACTURATION)(
"input, select"
).ifRight(
(champs) => champs.forEach((champ) => {
champ.setAttribute(ATTRIBUT_DESACTIVE, "");
champ.value = "";
})
);
});
});
};
const initialiseBoutonActions = () => {
BOUTON_ACTIONS_FORMULAIRE.addEventListener("click", (evenement) => {
Maybe.fromFalsy(FORMULAIRE_PANIER.checkValidity()).ifJust(() => {
evenement.preventDefault();
FORMULAIRE_PANIER.removeAttribute(ATTRIBUT_HIDDEN);
BOUTON_ACTIONS_FORMULAIRE.textContent = "Check-out";
}).ifJust(() => {
const donneesFormulaire = pipe(
new FormData(FORMULAIRE_PANIER),
(formData) => formData.entries(),
(entrees) => Array.from(entrees),
(tuple) => y.fromPairs(tuple)
);
const argumentsFormulaire = {
billing_address: {
address_1: donneesFormulaire["facturation-adresse"] ?? donneesFormulaire["livraison-adresse"] ?? "",
address_2: "",
city: donneesFormulaire["facturation-ville"] ?? donneesFormulaire["livraison-ville"] ?? "",
company: "",
country: "FR",
email: donneesFormulaire["facturation-email"] ?? donneesFormulaire["livraison-email"] ?? "",
first_name: donneesFormulaire["facturation-prenom"] ?? donneesFormulaire["livraison-prenom"] ?? "",
last_name: donneesFormulaire["facturation-nom"] ?? donneesFormulaire["livraison-nom"] ?? "",
phone: donneesFormulaire["facturation-telephone"] ?? donneesFormulaire["livraison-telephone"] ?? "",
postcode: donneesFormulaire["facturation-code-postal"] ?? donneesFormulaire["livraison-code-postal"] ?? "",
state: donneesFormulaire["facturation-region-etat"] ?? donneesFormulaire["livraison-region-etat"] ?? ""
},
shipping_address: {
address_1: donneesFormulaire["livraison-adresse"] ?? "",
address_2: "",
city: donneesFormulaire["livraison-ville"] ?? "",
company: "",
country: "FR",
first_name: donneesFormulaire["livraison-prenom"] ?? "",
last_name: donneesFormulaire["livraison-nom"] ?? "",
phone: donneesFormulaire["livraison-telephone"] ?? "",
postcode: donneesFormulaire["livraison-code-postal"] ?? "",
state: donneesFormulaire["livraison-region-etat"] ?? ""
}
};
Either.encase(
() => parse(WCStoreCartUpdateCustomerArgsSchema, argumentsFormulaire)
).map(async (args) => {
await postBackend({
corps: JSON.stringify(args),
nonce: ETATS_PAGE.nonce,
route: ROUTE_API_MAJ_CLIENT
}).then(async (reponse) => {
if (estReponse500(reponse)) leveServerError("500 Server Error");
pipe(
// Récupère la Réponse
await reponse.json(),
// Traite tous les codes HTTPs possibles
(corpsReponse) => traiteReponseBackendWCSelonCodesHTTP(
corpsReponse,
WCStoreCartSchema
),
l.tap((donnees) => {
const sousTotalLivraison = donnees.totals.total_shipping === "0" ? "Free" : `${String(donnees.totals.total_shipping)} €`;
const sousTotalPrestataire = z(donnees.shipping_rates[0]?.shipping_rates[0]?.name).with("Mondial Relay - Livraison Point Relais (Gratuit)", () => "Mondial Relay - Pickup Point").with("Free shipping", () => "Free Shipping").otherwise(() => "");
SOUS_TOTAL_LIVRAISON_COUT.textContent = sousTotalLivraison;
SOUS_TOTAL_LIVRAISON_PRESTATAIRE.textContent = sousTotalPrestataire;
sessionStorage.setItem(
"shipping_rates",
JSON.stringify(donnees.shipping_rates[0]?.shipping_rates[0] ?? "")
);
})
);
initialiseBoutonCreationCommande();
});
}).ifLeft((a) => console.error(a.issues));
});
});
};
const initialiseBoutonCreationCommande = () => {
BOUTON_ACTIONS_FORMULAIRE.outerHTML = BOUTON_ACTIONS_FORMULAIRE.outerHTML;
BOUTON_ACTIONS_FORMULAIRE = recupereElementDansDocumentOuLeve(SELECTEUR_BOUTON_ACTIONS_FORMULAIRE);
BOUTON_ACTIONS_FORMULAIRE.addEventListener("click", (evenement) => {
Maybe.fromFalsy(FORMULAIRE_PANIER.checkValidity()).ifJust(() => {
evenement.preventDefault();
BOUTON_ACTIONS_FORMULAIRE.textContent = "Submitting...";
}).ifJust(() => {
const donneesFormulaire = Object.fromEntries(new FormData(FORMULAIRE_PANIER));
const methodeLivraison = eitherSessionStorageGet("shipping_rates").chain(eitherJsonParse).chain(
(json) => eitherParse(
json,
WCStoreShippingRateShippingRateSchema
)
).ifLeft((e) => {
if (e instanceof ValiError) console.error(e.issues);
console.error("methodeLivraison", e);
BOUTON_ACTIONS_FORMULAIRE.textContent = "Check-out";
leveErreur(e);
}).unsafeCoerce();
const articlesPanier = ENTREES_PANIER_EITHER.orDefault([]).map((entree) => ({
product_id: Number(entree.getAttribute("data-id-produit")),
quantity: Number(entree.getAttribute("data-quantite")),
...entree.getAttribute("data-id-variation") && {
variation_id: Number(entree.getAttribute("data-id-variation"))
}
}));
const argumentsFormulaire = {
billing: {
address_1: donneesFormulaire["facturation-adresse"] ?? donneesFormulaire["livraison-adresse"] ?? "",
address_2: "",
city: donneesFormulaire["facturation-ville"] ?? donneesFormulaire["livraison-ville"] ?? "",
company: "",
country: "FR",
email: donneesFormulaire["facturation-email"] ?? donneesFormulaire["livraison-email"] ?? "",
first_name: donneesFormulaire["facturation-prenom"] ?? donneesFormulaire["livraison-prenom"] ?? "",
last_name: donneesFormulaire["facturation-nom"] ?? donneesFormulaire["livraison-nom"] ?? "",
phone: donneesFormulaire["facturation-telephone"] ?? donneesFormulaire["livraison-telephone"] ?? "",
postcode: donneesFormulaire["facturation-code-postal"] ?? donneesFormulaire["livraison-code-postal"] ?? "",
state: donneesFormulaire["facturation-region-etat"] ?? donneesFormulaire["livraison-region-etat"] ?? ""
},
currency: methodeLivraison.currency_code,
line_items: articlesPanier,
shipping: {
address_1: donneesFormulaire["livraison-adresse"] ?? "",
address_2: "",
city: donneesFormulaire["livraison-ville"] ?? "",
company: "",
country: "FR",
first_name: donneesFormulaire["livraison-prenom"] ?? "",
last_name: donneesFormulaire["livraison-nom"] ?? "",
phone: donneesFormulaire["livraison-telephone"] ?? "",
postcode: donneesFormulaire["livraison-code-postal"] ?? "",
state: donneesFormulaire["livraison-region-etat"] ?? ""
},
shipping_lines: [
{
method_id: methodeLivraison.method_id,
method_title: methodeLivraison.name,
total: methodeLivraison.price
}
]
};
eitherParse(argumentsFormulaire, WCV3OrdersArgsSchema).map(async (args) => {
await postBackend({
authString: ETATS_PAGE.authString,
corps: JSON.stringify(args),
nonce: ETATS_PAGE.nonce,
route: ROUTE_API_NOUVELLE_COMMANDES
}).then(async (reponse) => {
if (estReponse500(reponse)) leveServerError("500 Server Error");
pipe(
// Récupère la Réponse
await reponse.json(),
// Traite tous les codes HTTP possibles
(corpsReponse) => {
console.debug(corpsReponse);
return eitherParse(corpsReponse, WCV3OrderSchema);
},
(reponse2) => reponse2.ifRight((r) => {
const url = new URL(`https://${window.location.host}/checkout`);
url.searchParams.append("order_key", r.order_key);
url.searchParams.append("order_id", String(r.id));
window.location = url;
}),
(reponse2) => reponse2.ifLeft((a) => console.error(a.issues))
);
});
}).ifLeft((a) => console.error(a.issues));
});
});
};
document.addEventListener("DOMContentLoaded", () => {
initialiseMajEntreesPanier();
initialiseMajConteneurPanier();
initialiseMajContenuPanier();
initialiseMajFormulairesPanier();
initialiseBoutonActions();
});
//# sourceMappingURL=scripts-page-panier.js.map