// Adapted from legacy henza_pwa/src/Mixins/favorite.ts + the `favorits` slice of // myDataStore. Legacy kept favourites on the server (POST add-to-fav / // get-favorites, table major_favorites); so does this, through // /customer/me/favorites (FAV-01). It used to be memory-only, so favourites // vanished on reload and the ones imported from legacy were never shown. import { defineStore } from 'pinia' import { ref, watch } from 'vue' import { api } from '../api/client' import { useSessionStore } from './session' export const useFavoritesStore = defineStore('favorites', () => { const ids = ref([]) const session = useSessionStore() async function load() { try { ids.value = (await api.getFavorites()).ids } catch (e) { // Offline or a dead session (the client already handles 401): keep what we have. console.warn('favorites: load failed', e) } } // Loaded for whoever is signed in, cleared on logout — never another user's // list. `actingAs` is watched alongside the token because «ورود به حساب // مشتری» changes whose favourites these are WITHOUT changing the token: a // sales expert entering a customer's account would otherwise see their own // hearts on the customer's products, and tapping one would write to the // customer's list. watch( () => [session.token, session.actingAs?.id ?? null] as const, ([token]) => { ids.value = [] if (token) void load() }, { immediate: true }, ) /** Flips at once on screen, then confirms with the server (legacy toggled the same way). */ async function toggle(id: string) { const was = ids.value.includes(id) ids.value = was ? ids.value.filter((x) => x !== id) : [id, ...ids.value] try { const { favorite } = await api.toggleFavorite(id) const has = ids.value.includes(id) if (favorite && !has) ids.value = [id, ...ids.value] if (!favorite && has) ids.value = ids.value.filter((x) => x !== id) } catch (e) { // Put it back so the heart never shows a state the server does not hold. ids.value = was ? [id, ...ids.value.filter((x) => x !== id)] : ids.value.filter((x) => x !== id) console.warn('favorites: toggle failed', e) } } function isFavorite(id: string) { return ids.value.includes(id) } return { ids, load, toggle, isFavorite } })