import type { GenericResponse } from "~/types"; import type { Customer } from "~/types/user"; export const useUserStore = defineStore("userStore", () => { const store = useStore(); const menuStore = useMenuStore(); const checkoutStore = useCheckoutStore(); const { $toast } = useNuxtApp(); const fullUserData = ref(null); const isLogged = ref(true); const user = ref(null); async function checkIsLogged() { try { const { data } = await useMyFetch>( `/api/public/user`, { headers: { "Content-Type": "application/json", }, onErrorOccured: async (_, status) => { throw createError({ statusCode: status, statusMessage: `HTTP error: ${status}`, }); }, } ); if ("loggedin" in data && data.loggedin === true) { isLogged.value = true; user.value = `${data.first_name} ${data.last_name}` as any; fullUserData.value = data; checkoutStore.accountPhoneNumber = fullUserData.value.phone_number; } else { isLogged.value = false; user.value = null; fullUserData.value = null; } } catch (error) { console.error("checkIsLogged error:", error); } } // login const email = ref(); const password = ref(); const vLogin = ref(true); const vCodeVerify = ref(false); const vCode = ref(null); async function logIn() { try { const data = await useMyFetch>( `/api/public/user/session/start`, { method: "POST", body: JSON.stringify({ mail: email.value, password: password.value, }), headers: { "Content-Type": "application/json", }, onErrorOccured: (_, status) => { throw new Error(`HTTP error: ${status}`); }, } ); if (data.status === 200 || data.status === 201) { console.log(vCodeVerify.value); $toast.success("Code successfully sent to your email", { autoClose: 5000, dangerouslyHTMLString: true, }); vLogin.value = false; vCodeVerify.value = true; } else { $toast.error("Failed to sent code to your email. Please try again.", { autoClose: 5000, dangerouslyHTMLString: true, }); } store.minValue = data; } catch (error) { console.error("getList error:", error); } } const sendFormCode = async (redirect?: boolean) => { try { const data = await useMyFetch>( `/api/public/user/session/confirm`, { method: "POST", body: JSON.stringify({ code: vCode.value, mail: email.value, }), headers: { "Content-Type": "application/json", }, onErrorOccured: (_, status) => { throw new Error(`HTTP error: ${status}`); }, } ); await checkIsLogged(); if (isLogged.value) { if (redirect) { console.log(isLogged.value); menuStore.navigateToItem(); } else { // window.location.href = atob(redirect); } } else { useNuxtApp().$toast.error(`Error occurred: Failed to confirm code`, { autoClose: 5000, dangerouslyHTMLString: true, }); } } catch (e) { useNuxtApp().$toast.error(`Invalid code provided`, { autoClose: 5000, dangerouslyHTMLString: true, }); } }; return { isLogged, user, fullUserData, vCodeVerify, vCode, email, password, logIn, checkIsLogged, sendFormCode, }; });