feat: persist customer product and shop favorites through the live API
Replace mall fixture favorites with customer-scoped endpoints, and send signed-out shoppers back to the page they left after sign-in. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Cursor
parent
94a64ec712
commit
6c1357ec4d
@@ -0,0 +1,10 @@
|
||||
import { signInPath } from "~/utils/auth";
|
||||
|
||||
/** Send a signed-out shopper to sign in and back to the page they were on. */
|
||||
export function useSignInRedirect() {
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
return async function signInThenReturn(): Promise<void> {
|
||||
await router.push(signInPath(route.fullPath));
|
||||
};
|
||||
}
|
||||
@@ -24,6 +24,8 @@ export default {
|
||||
addedCart: "Added to cart",
|
||||
favorite: "Favorite",
|
||||
unfavorite: "Unfavorite",
|
||||
favoriteFailed: "Unable to update favorite",
|
||||
favoriteLoadFailed: "Unable to load favorite state",
|
||||
noStock: "Out of stock",
|
||||
unavailable: "This combination is unavailable",
|
||||
store: "Store",
|
||||
@@ -72,6 +74,8 @@ export default {
|
||||
addedCart: "已加入购物车",
|
||||
favorite: "收藏",
|
||||
unfavorite: "取消收藏",
|
||||
favoriteFailed: "收藏更新失败",
|
||||
favoriteLoadFailed: "无法加载收藏状态",
|
||||
noStock: "暂时缺货",
|
||||
unavailable: "该规格暂不可用",
|
||||
store: "店铺",
|
||||
|
||||
@@ -18,6 +18,10 @@ export default {
|
||||
speed: "Delivery",
|
||||
favorite: "Follow store",
|
||||
favorited: "Following",
|
||||
favoriteFailed: "Unable to update store favorite",
|
||||
favoriteLoadFailed: "Unable to load store favorite",
|
||||
notice: "Store notice",
|
||||
afterSale: "After-sales policy",
|
||||
salesRank: "Top sellers",
|
||||
storeProducts: "Store products",
|
||||
sortPrice: "Price",
|
||||
@@ -47,6 +51,10 @@ export default {
|
||||
speed: "发货速度",
|
||||
favorite: "收藏店铺",
|
||||
favorited: "已收藏",
|
||||
favoriteFailed: "店铺收藏更新失败",
|
||||
favoriteLoadFailed: "无法加载店铺收藏",
|
||||
notice: "店铺公告",
|
||||
afterSale: "售后服务",
|
||||
salesRank: "本店销量排行",
|
||||
storeProducts: "店内商品",
|
||||
sortPrice: "价格",
|
||||
|
||||
@@ -77,6 +77,8 @@ export default {
|
||||
removeFavorite: "Remove favorite",
|
||||
enterStore: "Enter store",
|
||||
noFavoriteStores: "No favorite stores yet.",
|
||||
favoriteLoadFailed: "Unable to load favorites",
|
||||
favoriteRemoveFailed: "Unable to remove favorite",
|
||||
couponsTitle: "My coupons",
|
||||
couponTitle: "Coupon",
|
||||
amount: "Amount",
|
||||
@@ -174,6 +176,8 @@ export default {
|
||||
removeFavorite: "取消收藏",
|
||||
enterStore: "进入店铺",
|
||||
noFavoriteStores: "暂无关注店铺。",
|
||||
favoriteLoadFailed: "收藏加载失败",
|
||||
favoriteRemoveFailed: "取消收藏失败",
|
||||
couponsTitle: "我的优惠券",
|
||||
couponTitle: "优惠券",
|
||||
amount: "优惠金额",
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
export default defineNuxtRouteMiddleware(async () => {
|
||||
import { signInPath } from "~/utils/auth";
|
||||
|
||||
export default defineNuxtRouteMiddleware(async (to) => {
|
||||
if (import.meta.server) return;
|
||||
// The requested page, not the current one, is where the shopper should land
|
||||
// after signing in — deep links into the buyer centre must survive.
|
||||
const signIn = signInPath(to.fullPath);
|
||||
const session = useSessionStore();
|
||||
if (!session.token) session.hydrate();
|
||||
if (!session.token) return navigateTo("/login");
|
||||
if (!session.token) return navigateTo(signIn);
|
||||
// Trust the auth API's answer rather than whatever localStorage claims; a
|
||||
// rejected token clears the session inside validate().
|
||||
if (!(await session.validate())) return navigateTo("/login");
|
||||
if (session.user?.role !== "customer") return navigateTo("/login");
|
||||
if (!(await session.validate())) return navigateTo(signIn);
|
||||
if (session.user?.role !== "customer") return navigateTo(signIn);
|
||||
});
|
||||
|
||||
+154
-3
@@ -15,6 +15,9 @@ import type {
|
||||
Coupon,
|
||||
CouponTemplate,
|
||||
CouponTemplateInput,
|
||||
Favorite,
|
||||
FavoriteListQuery,
|
||||
FavoriteProductSummary,
|
||||
FlashSaleItem,
|
||||
FlashSaleItemInput,
|
||||
FlashSaleSession,
|
||||
@@ -45,6 +48,7 @@ import {
|
||||
MOCK_CATEGORIES,
|
||||
MOCK_COUPONS,
|
||||
MOCK_CURRENCIES,
|
||||
MOCK_FAVORITES,
|
||||
INTEGRAL_PRODUCTS,
|
||||
MOCK_PROMOS,
|
||||
MOCK_QUICK_LINKS,
|
||||
@@ -71,19 +75,26 @@ interface MockState {
|
||||
addresses: AddressBookEntry[];
|
||||
/** In-memory only: claims made during this browser session. */
|
||||
coupons: Coupon[];
|
||||
/** Persisted customer favorites for fixed-adapter reload parity. */
|
||||
favorites: Favorite[];
|
||||
/** In-memory points catalog and redemptions for the fixed-data path. */
|
||||
pointsProducts: IntegralProduct[];
|
||||
redemptions: IntegralOrder[];
|
||||
addressSeq: number;
|
||||
favoriteSeq: number;
|
||||
orderSeq: number;
|
||||
invoiceSeq: number;
|
||||
redemptionSeq: number;
|
||||
}
|
||||
|
||||
// v3: address book joined the persisted state.
|
||||
const STORAGE_KEY = "vmall.mock.state.v3";
|
||||
// v4: customer favorites joined the persisted rollback state.
|
||||
const STORAGE_KEY = "vmall.mock.state.v4";
|
||||
|
||||
type PersistedState = Pick<MockState, "cart" | "orders" | "shipments" | "invoices" | "addresses" | "orderSeq" | "invoiceSeq" | "addressSeq">;
|
||||
type PersistedState = Pick<
|
||||
MockState,
|
||||
"cart" | "orders" | "shipments" | "invoices" | "addresses" | "favorites" |
|
||||
"orderSeq" | "invoiceSeq" | "addressSeq" | "favoriteSeq"
|
||||
>;
|
||||
|
||||
// Load cart/order session state persisted by a previous page load (client only).
|
||||
function loadPersisted(): PersistedState | null {
|
||||
@@ -98,6 +109,7 @@ function loadPersisted(): PersistedState | null {
|
||||
if (!Array.isArray(p.shipments) || !Array.isArray(p.invoices)) return null;
|
||||
if (typeof p.orderSeq !== "number" || typeof p.invoiceSeq !== "number") return null;
|
||||
if (!Array.isArray(p.addresses) || typeof p.addressSeq !== "number") return null;
|
||||
if (!Array.isArray(p.favorites) || typeof p.favoriteSeq !== "number") return null;
|
||||
return p as PersistedState;
|
||||
} catch {
|
||||
return null;
|
||||
@@ -145,6 +157,64 @@ function seedCoupons(): Coupon[] {
|
||||
return MOCK_COUPONS.map(mockOwnedCoupon);
|
||||
}
|
||||
|
||||
function clampPage(page?: number): number {
|
||||
return Math.max(1, page ?? 1);
|
||||
}
|
||||
|
||||
function clampPerPage(perPage?: number): number {
|
||||
return Math.min(100, Math.max(1, perPage ?? 20));
|
||||
}
|
||||
|
||||
function productSummary(product: Product): FavoriteProductSummary {
|
||||
const sku = lowestSku(product);
|
||||
return {
|
||||
id: product.id,
|
||||
shop_id: product.shop_id,
|
||||
slug: product.slug,
|
||||
name: product.name,
|
||||
image: product.images[0] ?? null,
|
||||
price_minor: sku?.price_minor ?? null,
|
||||
currency: sku?.currency ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function hydrateProductFavorite(id: string, createdAt: string, product: Product): Favorite {
|
||||
return {
|
||||
kind: "product",
|
||||
id,
|
||||
user_id: MOCK_USER.id,
|
||||
created_at: createdAt,
|
||||
product: productSummary(product),
|
||||
};
|
||||
}
|
||||
|
||||
function hydrateShopFavorite(id: string, createdAt: string, store: MockStoreRecord): Favorite {
|
||||
return {
|
||||
kind: "shop",
|
||||
id,
|
||||
user_id: MOCK_USER.id,
|
||||
created_at: createdAt,
|
||||
shop: toShopProfile(store),
|
||||
};
|
||||
}
|
||||
|
||||
function seedFavorites(): Favorite[] {
|
||||
const rows: Favorite[] = [];
|
||||
for (const item of MOCK_FAVORITES) {
|
||||
const created = `${item.createdAt}T09:00:00.000Z`;
|
||||
if (item.kind === "product") {
|
||||
const product = productById(item.refId);
|
||||
if (product && product.status === "published") {
|
||||
rows.push(hydrateProductFavorite(item.id, created, product));
|
||||
}
|
||||
} else {
|
||||
const store = storeById(item.refId);
|
||||
if (store) rows.push(hydrateShopFavorite(item.id, created, store));
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function seedPointsProducts(): IntegralProduct[] {
|
||||
return INTEGRAL_PRODUCTS.map((p) => ({
|
||||
id: p.id,
|
||||
@@ -277,9 +347,11 @@ function initialState(): MockState {
|
||||
invoices: seed.invoices,
|
||||
addresses: seededAddresses,
|
||||
coupons: seedCoupons(),
|
||||
favorites: seedFavorites(),
|
||||
pointsProducts: seedPointsProducts(),
|
||||
redemptions: [],
|
||||
addressSeq: 100,
|
||||
favoriteSeq: 200,
|
||||
orderSeq: 100,
|
||||
invoiceSeq: 100,
|
||||
redemptionSeq: 0,
|
||||
@@ -335,6 +407,8 @@ export function createMockApi(): ApiClient {
|
||||
invoiceSeq: state.invoiceSeq,
|
||||
addresses: state.addresses,
|
||||
addressSeq: state.addressSeq,
|
||||
favorites: state.favorites,
|
||||
favoriteSeq: state.favoriteSeq,
|
||||
};
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(snapshot));
|
||||
} catch {
|
||||
@@ -722,6 +796,83 @@ export function createMockApi(): ApiClient {
|
||||
return Promise.resolve({ ...entry });
|
||||
},
|
||||
|
||||
listFavorites: (q: FavoriteListQuery) => {
|
||||
const page = clampPage(q.page);
|
||||
const perPage = clampPerPage(q.per_page);
|
||||
const visible = state.favorites
|
||||
.map((row) => {
|
||||
if (row.kind === "product") {
|
||||
const product = productById(row.product.id);
|
||||
if (!product || product.status !== "published") return null;
|
||||
return hydrateProductFavorite(row.id, row.created_at, product);
|
||||
}
|
||||
const store = storeById(row.shop.id);
|
||||
if (!store) return null;
|
||||
return hydrateShopFavorite(row.id, row.created_at, store);
|
||||
})
|
||||
.filter((row): row is Favorite => row !== null)
|
||||
.filter((row) => row.kind === q.kind)
|
||||
.filter((row) => {
|
||||
if (!q.target_id) return true;
|
||||
return row.kind === "product" ? row.product.id === q.target_id : row.shop.id === q.target_id;
|
||||
})
|
||||
.sort((a, b) => b.created_at.localeCompare(a.created_at));
|
||||
const total = visible.length;
|
||||
const start = (page - 1) * perPage;
|
||||
return Promise.resolve({
|
||||
items: visible.slice(start, start + perPage),
|
||||
total,
|
||||
page,
|
||||
per_page: perPage,
|
||||
});
|
||||
},
|
||||
|
||||
addProductFavorite: (productId: string) => {
|
||||
const product = productById(productId);
|
||||
if (!product || product.status !== "published") {
|
||||
return Promise.reject(new ApiError(404, "NOT_FOUND", "product"));
|
||||
}
|
||||
const existing = state.favorites.find(
|
||||
(row) => row.kind === "product" && row.product.id === productId,
|
||||
);
|
||||
if (existing) {
|
||||
return Promise.resolve(hydrateProductFavorite(existing.id, existing.created_at, product));
|
||||
}
|
||||
state.favoriteSeq += 1;
|
||||
const row = hydrateProductFavorite(`f-${state.favoriteSeq}`, new Date().toISOString(), product);
|
||||
state.favorites.push(row);
|
||||
persist();
|
||||
return Promise.resolve(row);
|
||||
},
|
||||
|
||||
removeProductFavorite: (productId: string) => {
|
||||
state.favorites = state.favorites.filter(
|
||||
(row) => !(row.kind === "product" && row.product.id === productId),
|
||||
);
|
||||
persist();
|
||||
return Promise.resolve();
|
||||
},
|
||||
|
||||
addShopFavorite: (shopId: string) => {
|
||||
const store = storeById(shopId);
|
||||
if (!store) return Promise.reject(new ApiError(404, "NOT_FOUND", "shop"));
|
||||
const existing = state.favorites.find((row) => row.kind === "shop" && row.shop.id === shopId);
|
||||
if (existing) {
|
||||
return Promise.resolve(hydrateShopFavorite(existing.id, existing.created_at, store));
|
||||
}
|
||||
state.favoriteSeq += 1;
|
||||
const row = hydrateShopFavorite(`f-${state.favoriteSeq}`, new Date().toISOString(), store);
|
||||
state.favorites.push(row);
|
||||
persist();
|
||||
return Promise.resolve(row);
|
||||
},
|
||||
|
||||
removeShopFavorite: (shopId: string) => {
|
||||
state.favorites = state.favorites.filter((row) => !(row.kind === "shop" && row.shop.id === shopId));
|
||||
persist();
|
||||
return Promise.resolve();
|
||||
},
|
||||
|
||||
listShopCouponTemplates: (shopId: string) =>
|
||||
Promise.resolve(MOCK_COUPONS.map((t) => mockTemplate(t, shopId))),
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export default defineNuxtConfig({
|
||||
// Domains served by the live backend; every other domain stays on the
|
||||
// fixed-data adapter. Override with NUXT_PUBLIC_LIVE_DOMAINS='["catalog"]'.
|
||||
// See openspec/changes/replace-mock-api-wave-1/design.md and waves 2-3.
|
||||
liveDomains: ["catalog", "currency", "content", "shops", "brands", "auth", "account", "cart", "orders", "shipments", "invoices", "addresses", "coupons", "points", "flashSales", "groupBuying"],
|
||||
liveDomains: ["catalog", "currency", "content", "shops", "brands", "auth", "account", "cart", "orders", "shipments", "invoices", "addresses", "coupons", "points", "flashSales", "groupBuying", "favorites"],
|
||||
appName: "mall",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -7,6 +7,7 @@ const { $api } = useNuxtApp();
|
||||
const session = useSessionStore();
|
||||
const cart = useCartStore();
|
||||
const router = useRouter();
|
||||
const signInThenReturn = useSignInRedirect();
|
||||
const activities = ref<GroupBuyingActivityView[]>([]);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
@@ -42,7 +43,7 @@ function joined(activity: GroupBuyingActivityView, groupId: string): string {
|
||||
// intent; the server prices and validates it at checkout.
|
||||
async function start(activity: GroupBuyingActivityView, open: boolean): Promise<void> {
|
||||
if (!session.isLoggedIn) {
|
||||
await navigateTo("/login");
|
||||
await signInThenReturn();
|
||||
return;
|
||||
}
|
||||
error.value = "";
|
||||
|
||||
@@ -14,6 +14,7 @@ const { locale, t } = useI18n();
|
||||
const { $api } = useNuxtApp();
|
||||
const cart = useCartStore();
|
||||
const session = useSessionStore();
|
||||
const signInThenReturn = useSignInRedirect();
|
||||
|
||||
const routeId = computed(() => {
|
||||
const value = route.params.id;
|
||||
@@ -72,7 +73,7 @@ const claimedIds = ref<Set<string>>(new Set());
|
||||
|
||||
async function claim(coupon: CouponTemplate): Promise<void> {
|
||||
if (!session.isLoggedIn) {
|
||||
await navigateTo("/login");
|
||||
await signInThenReturn();
|
||||
return;
|
||||
}
|
||||
claimingId.value = coupon.id;
|
||||
@@ -92,6 +93,10 @@ const selectedAttributes = reactive<Record<string, string>>({});
|
||||
const quantity = ref(1);
|
||||
const galleryIndex = ref(0);
|
||||
const favorite = ref(false);
|
||||
const favoriteLoading = ref(false);
|
||||
const favoriteBusy = ref(false);
|
||||
const favoriteError = ref("");
|
||||
let favoriteRequestVersion = 0;
|
||||
const cartSuccess = ref(false);
|
||||
const activeTab = ref("detail");
|
||||
|
||||
@@ -116,7 +121,6 @@ watch(
|
||||
if (initial) Object.assign(selectedAttributes, initial.attributes);
|
||||
quantity.value = 1;
|
||||
galleryIndex.value = 0;
|
||||
favorite.value = false;
|
||||
cartSuccess.value = false;
|
||||
activeTab.value = "detail";
|
||||
},
|
||||
@@ -176,7 +180,7 @@ const addToCart = async (): Promise<boolean> => {
|
||||
} catch (error) {
|
||||
// A live cart needs a token; send a signed-out shopper to sign in and back.
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
await router.push(`/login?redirect=${encodeURIComponent(route.fullPath)}`);
|
||||
await signInThenReturn();
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
@@ -198,6 +202,66 @@ const addCart = async (): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [product.value?.id, session.isLoggedIn] as const,
|
||||
async ([id, loggedIn]) => {
|
||||
const version = ++favoriteRequestVersion;
|
||||
favorite.value = false;
|
||||
favoriteLoading.value = Boolean(id && loggedIn);
|
||||
favoriteBusy.value = false;
|
||||
favoriteError.value = "";
|
||||
if (!id || !loggedIn) return;
|
||||
try {
|
||||
const page = await $api.listFavorites({ kind: "product", target_id: id, per_page: 1 });
|
||||
if (version === favoriteRequestVersion && product.value?.id === id) {
|
||||
favorite.value = page.items.length > 0;
|
||||
}
|
||||
} catch {
|
||||
if (version === favoriteRequestVersion && product.value?.id === id) {
|
||||
favoriteError.value = t("product.favoriteLoadFailed");
|
||||
}
|
||||
} finally {
|
||||
if (version === favoriteRequestVersion) favoriteLoading.value = false;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const toggleFavorite = async (): Promise<void> => {
|
||||
const current = product.value;
|
||||
if (!current || favoriteLoading.value || favoriteBusy.value) return;
|
||||
if (!session.isLoggedIn) {
|
||||
await signInThenReturn();
|
||||
return;
|
||||
}
|
||||
const version = ++favoriteRequestVersion;
|
||||
favoriteBusy.value = true;
|
||||
favoriteError.value = "";
|
||||
try {
|
||||
if (favorite.value) {
|
||||
await $api.removeProductFavorite(current.id);
|
||||
if (version === favoriteRequestVersion && product.value?.id === current.id) {
|
||||
favorite.value = false;
|
||||
}
|
||||
} else {
|
||||
await $api.addProductFavorite(current.id);
|
||||
if (version === favoriteRequestVersion && product.value?.id === current.id) {
|
||||
favorite.value = true;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
await signInThenReturn();
|
||||
return;
|
||||
}
|
||||
if (version === favoriteRequestVersion && product.value?.id === current.id) {
|
||||
favoriteError.value = t("product.favoriteFailed");
|
||||
}
|
||||
} finally {
|
||||
if (version === favoriteRequestVersion) favoriteBusy.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// No reviews tab: there is no reviews capability, and the mall will not present
|
||||
// invented reviewers and ratings as fact. See the wave-6 design.
|
||||
const tabs = computed(() => [
|
||||
@@ -256,10 +320,12 @@ const detailImages = computed(() => product.value?.images ?? []);
|
||||
type="button"
|
||||
class="favorite"
|
||||
:class="{ active: favorite }"
|
||||
:disabled="favoriteLoading || favoriteBusy"
|
||||
:aria-label="favorite ? t('product.unfavorite') : t('product.favorite')"
|
||||
@click="favorite = !favorite"
|
||||
@click="toggleFavorite"
|
||||
>{{ favorite ? "♥" : "♡" }}</button>
|
||||
</div>
|
||||
<p v-if="favoriteError" class="favorite-error">{{ favoriteError }}</p>
|
||||
<div class="price-panel">
|
||||
<span class="price-label">{{ t("product.currentPrice") }}</span>
|
||||
<strong v-if="matchedSku" class="price"><PriceText :amount-minor="matchedSku.price_minor" :currency="matchedSku.currency" /></strong>
|
||||
@@ -489,9 +555,14 @@ h1 {
|
||||
padding: 13px 0;
|
||||
}
|
||||
.summary-meta .soldout,
|
||||
.stock-warning {
|
||||
.stock-warning,
|
||||
.favorite-error {
|
||||
color: var(--mall-red);
|
||||
}
|
||||
.favorite-error {
|
||||
margin: 6px 0 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
.coupon-row,
|
||||
.attribute-row,
|
||||
.quantity-row {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { ApiError, t as pick } from "@vmall/shared";
|
||||
const { locale, t } = useI18n();
|
||||
const { $api } = useNuxtApp();
|
||||
const session = useSessionStore();
|
||||
const signInThenReturn = useSignInRedirect();
|
||||
const stats = ref<AccountSummary | null>(null);
|
||||
const products = ref<IntegralProduct[]>([]);
|
||||
const redemptions = ref<IntegralOrder[]>([]);
|
||||
@@ -85,7 +86,7 @@ function addressForRedemption(): Address | null {
|
||||
|
||||
async function redeem(product: IntegralProduct): Promise<void> {
|
||||
if (!session.isLoggedIn) {
|
||||
await navigateTo("/login");
|
||||
await signInThenReturn();
|
||||
return;
|
||||
}
|
||||
const address = addressForRedemption();
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { ApiError } from "@vmall/shared";
|
||||
import { t as pick } from "@vmall/shared";
|
||||
import type { Paged, Product } from "@vmall/shared";
|
||||
import { lowestSku } from "~/utils/product";
|
||||
import { useSessionStore } from "~/stores/session";
|
||||
|
||||
const route = useRoute();
|
||||
const { locale, t } = useI18n();
|
||||
const { $api } = useNuxtApp();
|
||||
const session = useSessionStore();
|
||||
const signInThenReturn = useSignInRedirect();
|
||||
|
||||
const slug = computed(() => {
|
||||
const raw = route.params.id;
|
||||
@@ -21,6 +25,10 @@ const { data: shop } = await useAsyncData("shop-profile", () => $api.getShop(slu
|
||||
const store = computed(() => shop.value);
|
||||
|
||||
const favorite = ref(false);
|
||||
const favoriteLoading = ref(false);
|
||||
const favoriteBusy = ref(false);
|
||||
const favoriteError = ref("");
|
||||
let favoriteRequestVersion = 0;
|
||||
// Only sorts the catalog model can answer; sales and comments have no model.
|
||||
const sortMode = ref<"default" | "price">("default");
|
||||
const sortOrder = ref<"asc" | "desc">("desc");
|
||||
@@ -80,6 +88,67 @@ function chooseSort(mode: "default" | "price"): void {
|
||||
}
|
||||
page.value = 1;
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [store.value?.id, session.isLoggedIn] as const,
|
||||
async ([id, loggedIn]) => {
|
||||
const version = ++favoriteRequestVersion;
|
||||
favorite.value = false;
|
||||
favoriteLoading.value = Boolean(id && loggedIn);
|
||||
favoriteBusy.value = false;
|
||||
favoriteError.value = "";
|
||||
if (!id || !loggedIn) return;
|
||||
try {
|
||||
const result = await $api.listFavorites({ kind: "shop", target_id: id, per_page: 1 });
|
||||
if (version === favoriteRequestVersion && store.value?.id === id) {
|
||||
favorite.value = result.items.length > 0;
|
||||
}
|
||||
} catch {
|
||||
if (version === favoriteRequestVersion && store.value?.id === id) {
|
||||
favoriteError.value = t("stores.favoriteLoadFailed");
|
||||
}
|
||||
} finally {
|
||||
if (version === favoriteRequestVersion) favoriteLoading.value = false;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const toggleFavorite = async (): Promise<void> => {
|
||||
const current = store.value;
|
||||
if (!current || favoriteLoading.value || favoriteBusy.value) return;
|
||||
if (!session.isLoggedIn) {
|
||||
await signInThenReturn();
|
||||
return;
|
||||
}
|
||||
const version = ++favoriteRequestVersion;
|
||||
favoriteBusy.value = true;
|
||||
favoriteError.value = "";
|
||||
try {
|
||||
if (favorite.value) {
|
||||
await $api.removeShopFavorite(current.id);
|
||||
if (version === favoriteRequestVersion && store.value?.id === current.id) {
|
||||
favorite.value = false;
|
||||
}
|
||||
} else {
|
||||
await $api.addShopFavorite(current.id);
|
||||
if (version === favoriteRequestVersion && store.value?.id === current.id) {
|
||||
favorite.value = true;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
await signInThenReturn();
|
||||
return;
|
||||
}
|
||||
if (version === favoriteRequestVersion && store.value?.id === current.id) {
|
||||
favoriteError.value = t("stores.favoriteFailed");
|
||||
}
|
||||
} finally {
|
||||
if (version === favoriteRequestVersion) favoriteBusy.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -112,9 +181,16 @@ function chooseSort(mode: "default" | "price"): void {
|
||||
<div v-if="store.region"><dt>{{ t("stores.region") }}</dt><dd>{{ store.region }}</dd></div>
|
||||
<div v-if="store.address"><dt>{{ t("stores.address") }}</dt><dd>{{ pick(store.address, locale) }}</dd></div>
|
||||
</dl>
|
||||
<button type="button" class="mbtn favorite-button" :class="{ selected: favorite }" @click="favorite = !favorite">
|
||||
<button
|
||||
type="button"
|
||||
class="mbtn favorite-button"
|
||||
:class="{ selected: favorite }"
|
||||
:disabled="favoriteLoading || favoriteBusy"
|
||||
@click="toggleFavorite"
|
||||
>
|
||||
{{ favorite ? t("stores.favorited") : t("stores.favorite") }}
|
||||
</button>
|
||||
<p v-if="favoriteError" class="favorite-error">{{ favoriteError }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="store.notice || store.after_sale" class="mpanel notice-card">
|
||||
@@ -253,6 +329,11 @@ function chooseSort(mode: "default" | "price"): void {
|
||||
border-color: var(--mall-red);
|
||||
color: var(--mall-red);
|
||||
}
|
||||
.favorite-error {
|
||||
margin: 6px 0 0;
|
||||
color: var(--mall-red);
|
||||
font-size: 12px;
|
||||
}
|
||||
.rail-title {
|
||||
margin: 0 0 12px;
|
||||
border-left: 3px solid var(--mall-red);
|
||||
|
||||
@@ -1,69 +1,117 @@
|
||||
<script setup lang="ts">
|
||||
import type { Product } from "@vmall/shared";
|
||||
import type { Favorite, Paged, ProductFavorite, ShopFavorite } from "@vmall/shared";
|
||||
import { t as pick } from "@vmall/shared";
|
||||
import { MOCK_FAVORITES, lowestSku, productById, storeById } from "~/mock/data";
|
||||
|
||||
definePageMeta({ middleware: "auth" });
|
||||
|
||||
const { locale, t } = useI18n();
|
||||
const { $api } = useNuxtApp();
|
||||
|
||||
const activeTab = ref<"product" | "store">("product");
|
||||
const favorites = ref(MOCK_FAVORITES.map((item) => ({ ...item })));
|
||||
const activeTab = ref<"product" | "shop">("product");
|
||||
const page = ref(1);
|
||||
const perPage = 12;
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const removingId = ref("");
|
||||
const emptyPage: Paged<Favorite> = { items: [], total: 0, page: 1, per_page: perPage };
|
||||
const result = ref<Paged<Favorite>>({ ...emptyPage });
|
||||
let loadVersion = 0;
|
||||
|
||||
const tabs = computed(() => [
|
||||
{ key: "product", label: t("user.favoriteProductsTab") },
|
||||
{ key: "store", label: t("user.favoriteStoresTab") },
|
||||
{ key: "shop", label: t("user.favoriteStoresTab") },
|
||||
]);
|
||||
|
||||
const productRows = computed(() =>
|
||||
favorites.value
|
||||
.filter((favorite) => favorite.kind === "product")
|
||||
.map((favorite) => productById(favorite.refId))
|
||||
.filter((product): product is Product => product !== null)
|
||||
.map((product) => {
|
||||
const sku = lowestSku(product);
|
||||
return {
|
||||
product,
|
||||
amountMinor: sku?.price_minor ?? null,
|
||||
currency: sku?.currency ?? null,
|
||||
};
|
||||
}),
|
||||
result.value.items.filter((row): row is ProductFavorite => row.kind === "product"),
|
||||
);
|
||||
|
||||
const storeRows = computed(() =>
|
||||
favorites.value
|
||||
.filter((favorite) => favorite.kind === "store")
|
||||
.map((favorite) => storeById(favorite.refId))
|
||||
.filter((store): store is NonNullable<ReturnType<typeof storeById>> => store !== null),
|
||||
result.value.items.filter((row): row is ShopFavorite => row.kind === "shop"),
|
||||
);
|
||||
|
||||
function removeProductFavorite(productId: string): void {
|
||||
favorites.value = favorites.value.filter((item) => !(item.kind === "product" && item.refId === productId));
|
||||
async function load(): Promise<Paged<Favorite> | null> {
|
||||
const version = ++loadVersion;
|
||||
const requestedKind = activeTab.value;
|
||||
const requestedPage = page.value;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const next = await $api.listFavorites({
|
||||
kind: requestedKind,
|
||||
page: requestedPage,
|
||||
per_page: perPage,
|
||||
});
|
||||
if (version !== loadVersion || activeTab.value !== requestedKind || page.value !== requestedPage) {
|
||||
return null;
|
||||
}
|
||||
result.value = next;
|
||||
return next;
|
||||
} catch {
|
||||
if (version === loadVersion && activeTab.value === requestedKind && page.value === requestedPage) {
|
||||
error.value = t("user.favoriteLoadFailed");
|
||||
result.value = { ...emptyPage };
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
if (version === loadVersion) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function removeStoreFavorite(storeId: string): void {
|
||||
favorites.value = favorites.value.filter((item) => !(item.kind === "store" && item.refId === storeId));
|
||||
watch(activeTab, () => {
|
||||
page.value = 1;
|
||||
});
|
||||
|
||||
watch([activeTab, page], () => {
|
||||
void load();
|
||||
}, { immediate: true });
|
||||
|
||||
async function removeProductFavorite(productId: string): Promise<void> {
|
||||
if (removingId.value) return;
|
||||
removingId.value = productId;
|
||||
try {
|
||||
await $api.removeProductFavorite(productId);
|
||||
const next = await load();
|
||||
if (next) page.value = Math.min(page.value, Math.max(1, Math.ceil(next.total / next.per_page)));
|
||||
} catch {
|
||||
error.value = t("user.favoriteRemoveFailed");
|
||||
} finally {
|
||||
removingId.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function removeStoreFavorite(storeId: string): Promise<void> {
|
||||
if (removingId.value) return;
|
||||
removingId.value = storeId;
|
||||
try {
|
||||
await $api.removeShopFavorite(storeId);
|
||||
const next = await load();
|
||||
if (next) page.value = Math.min(page.value, Math.max(1, Math.ceil(next.total / next.per_page)));
|
||||
} catch {
|
||||
error.value = t("user.favoriteRemoveFailed");
|
||||
} finally {
|
||||
removingId.value = "";
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="mpanel favorites-panel">
|
||||
<h1 class="mpanel-title">{{ t("user.favoritesTitle") }}</h1>
|
||||
<p v-if="error" class="muted">{{ error }}</p>
|
||||
<UiTabs v-model="activeTab" :tabs="tabs">
|
||||
<template #default>
|
||||
<div v-if="activeTab === 'product'">
|
||||
<div v-if="loading" class="muted">{{ t("common.loading") }}</div>
|
||||
<div v-else-if="activeTab === 'product'">
|
||||
<UiEmptyState v-if="productRows.length === 0" :text="t('user.noFavorites')" />
|
||||
<div v-else class="product-grid">
|
||||
<article v-for="item in productRows" :key="item.product.id" class="product-card hover-lift">
|
||||
<article v-for="item in productRows" :key="item.id" class="product-card hover-lift">
|
||||
<NuxtLink :to="`/goods/${item.product.slug}`" class="cover">
|
||||
<img :src="item.product.images[0] || '/mock/product-1.svg'" :alt="pick(item.product.name, locale)" />
|
||||
<img :src="item.product.image || '/mock/product-1.svg'" :alt="pick(item.product.name, locale)" />
|
||||
</NuxtLink>
|
||||
<div class="content">
|
||||
<NuxtLink :to="`/goods/${item.product.slug}`" class="name">{{ pick(item.product.name, locale) }}</NuxtLink>
|
||||
<PriceText v-if="item.amountMinor !== null && item.currency" :amount-minor="item.amountMinor" :currency="item.currency" />
|
||||
<button class="mbtn" type="button" @click="removeProductFavorite(item.product.id)">{{ t("user.removeFavorite") }}</button>
|
||||
<PriceText v-if="item.product.price_minor !== null && item.product.currency" :amount-minor="item.product.price_minor" :currency="item.product.currency" />
|
||||
<button class="mbtn" type="button" :disabled="removingId === item.product.id" @click="removeProductFavorite(item.product.id)">{{ t("user.removeFavorite") }}</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
@@ -72,19 +120,27 @@ function removeStoreFavorite(storeId: string): void {
|
||||
<div v-else>
|
||||
<UiEmptyState v-if="storeRows.length === 0" :text="t('user.noFavoriteStores')" />
|
||||
<div v-else class="store-list">
|
||||
<article v-for="store in storeRows" :key="store.id" class="store-row">
|
||||
<img :src="store.logo" :alt="pick(store.name, locale)" />
|
||||
<article v-for="item in storeRows" :key="item.id" class="store-row">
|
||||
<img v-if="item.shop.logo" :src="item.shop.logo" :alt="pick(item.shop.name, locale)" />
|
||||
<span v-else class="store-logo-placeholder">{{ pick(item.shop.name, locale).slice(0, 1) }}</span>
|
||||
<div class="store-main">
|
||||
<strong>{{ pick(store.name, locale) }}</strong>
|
||||
<span>{{ store.company }}</span>
|
||||
<strong>{{ pick(item.shop.name, locale) }}</strong>
|
||||
<span>{{ item.shop.company }}</span>
|
||||
</div>
|
||||
<div class="store-actions">
|
||||
<NuxtLink class="mbtn" :to="`/stores/${store.slug}`">{{ t("user.enterStore") }}</NuxtLink>
|
||||
<button class="mbtn" type="button" @click="removeStoreFavorite(store.id)">{{ t("user.removeFavorite") }}</button>
|
||||
<NuxtLink class="mbtn" :to="`/stores/${item.shop.slug}`">{{ t("user.enterStore") }}</NuxtLink>
|
||||
<button class="mbtn" type="button" :disabled="removingId === item.shop.id" @click="removeStoreFavorite(item.shop.id)">{{ t("user.removeFavorite") }}</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
<UiPagination
|
||||
v-if="!loading && result.total > result.per_page"
|
||||
:page="result.page"
|
||||
:total="result.total"
|
||||
:per-page="result.per_page"
|
||||
@change="page = $event"
|
||||
/>
|
||||
</template>
|
||||
</UiTabs>
|
||||
</section>
|
||||
@@ -147,13 +203,22 @@ function removeStoreFavorite(storeId: string): void {
|
||||
.store-row:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.store-row img {
|
||||
.store-row img,
|
||||
.store-logo-placeholder {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
border: 1px solid var(--mall-line);
|
||||
border-radius: 4px;
|
||||
object-fit: cover;
|
||||
}
|
||||
.store-logo-placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #fafafa;
|
||||
color: var(--mall-muted);
|
||||
font-size: 18px;
|
||||
}
|
||||
.store-main {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccountSummary, Order, Product } from "@vmall/shared";
|
||||
import type { AccountSummary, Order, ProductFavorite } from "@vmall/shared";
|
||||
import { t as pick } from "@vmall/shared";
|
||||
import { MOCK_FAVORITES, lowestSku, productById } from "~/mock/data";
|
||||
|
||||
definePageMeta({ middleware: "auth" });
|
||||
|
||||
@@ -9,6 +8,8 @@ const { locale, t } = useI18n();
|
||||
const { $api } = useNuxtApp();
|
||||
const orders = ref<Order[]>([]);
|
||||
const stats = ref<AccountSummary | null>(null);
|
||||
const favoriteProducts = ref<ProductFavorite[]>([]);
|
||||
const favoriteProductTotal = ref(0);
|
||||
const loading = ref(true);
|
||||
|
||||
async function loadOrders(): Promise<void> {
|
||||
@@ -30,9 +31,23 @@ async function loadStats(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFavorites(): Promise<void> {
|
||||
try {
|
||||
const page = await $api.listFavorites({ kind: "product", page: 1, per_page: 8 });
|
||||
favoriteProducts.value = page.items.filter(
|
||||
(row): row is ProductFavorite => row.kind === "product",
|
||||
);
|
||||
favoriteProductTotal.value = page.total;
|
||||
} catch {
|
||||
favoriteProducts.value = [];
|
||||
favoriteProductTotal.value = 0;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadOrders();
|
||||
void loadStats();
|
||||
void loadFavorites();
|
||||
});
|
||||
|
||||
const counts = computed(() => ({
|
||||
@@ -50,20 +65,6 @@ const statusLinks = computed(() => [
|
||||
{ key: "completed", label: t("user.completed"), count: counts.value.completed, to: "/user/orders?status=completed" },
|
||||
{ key: "afterSale", label: t("user.afterSale"), count: counts.value.afterSale, to: "/user/orders?status=after-sale" },
|
||||
]);
|
||||
|
||||
const favoriteProducts = computed(() =>
|
||||
MOCK_FAVORITES.filter((favorite) => favorite.kind === "product")
|
||||
.map((favorite) => productById(favorite.refId))
|
||||
.filter((product): product is Product => product !== null)
|
||||
.map((product) => {
|
||||
const sku = lowestSku(product);
|
||||
return {
|
||||
product,
|
||||
amountMinor: sku?.price_minor ?? null,
|
||||
currency: sku?.currency ?? null,
|
||||
};
|
||||
}),
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -123,13 +124,13 @@ const favoriteProducts = computed(() =>
|
||||
</section>
|
||||
|
||||
<section class="mpanel">
|
||||
<h2 class="mpanel-title">{{ t("user.favoriteProducts") }}</h2>
|
||||
<h2 class="mpanel-title">{{ t("user.favoriteProducts") }} ({{ favoriteProductTotal }})</h2>
|
||||
<UiEmptyState v-if="favoriteProducts.length === 0" :text="t('user.noFavorites')" />
|
||||
<div v-else class="favorite-grid">
|
||||
<NuxtLink v-for="item in favoriteProducts" :key="item.product.id" :to="`/goods/${item.product.slug}`" class="favorite-card hover-lift">
|
||||
<img :src="item.product.images[0] || '/mock/product-1.svg'" :alt="pick(item.product.name, locale)" />
|
||||
<NuxtLink v-for="item in favoriteProducts" :key="item.id" :to="`/goods/${item.product.slug}`" class="favorite-card hover-lift">
|
||||
<img :src="item.product.image || '/mock/product-1.svg'" :alt="pick(item.product.name, locale)" />
|
||||
<span>{{ pick(item.product.name, locale) }}</span>
|
||||
<PriceText v-if="item.amountMinor !== null && item.currency" :amount-minor="item.amountMinor" :currency="item.currency" />
|
||||
<PriceText v-if="item.product.price_minor !== null && item.product.currency" :amount-minor="item.product.price_minor" :currency="item.product.currency" />
|
||||
</NuxtLink>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -23,7 +23,8 @@ type LiveDomain =
|
||||
| "coupons"
|
||||
| "points"
|
||||
| "flashSales"
|
||||
| "groupBuying";
|
||||
| "groupBuying"
|
||||
| "favorites";
|
||||
|
||||
/**
|
||||
* Explicit per-domain method picks rather than a string allowlist: indexing
|
||||
@@ -84,6 +85,13 @@ const LIVE_PICKS = {
|
||||
groupBuying: (a: ApiClient) => ({
|
||||
listGroupBuyingActivities: a.listGroupBuyingActivities,
|
||||
}),
|
||||
favorites: (a: ApiClient) => ({
|
||||
listFavorites: a.listFavorites,
|
||||
addProductFavorite: a.addProductFavorite,
|
||||
removeProductFavorite: a.removeProductFavorite,
|
||||
addShopFavorite: a.addShopFavorite,
|
||||
removeShopFavorite: a.removeShopFavorite,
|
||||
}),
|
||||
} satisfies Record<LiveDomain, (a: ApiClient) => Partial<ApiClient>>;
|
||||
|
||||
const KNOWN_DOMAINS = Object.keys(LIVE_PICKS) as LiveDomain[];
|
||||
@@ -106,6 +114,7 @@ const DEFAULT_LIVE_DOMAINS: LiveDomain[] = [
|
||||
"points",
|
||||
"flashSales",
|
||||
"groupBuying",
|
||||
"favorites",
|
||||
];
|
||||
|
||||
export default defineNuxtPlugin(() => {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Sign-in URL that returns the shopper to `fullPath` afterwards. `login.vue`
|
||||
* only honours a same-origin absolute path, and a redirect back to the sign-in
|
||||
* page itself would loop, so that case drops the parameter.
|
||||
*/
|
||||
export function signInPath(fullPath: string): string {
|
||||
if (!fullPath.startsWith("/") || fullPath.startsWith("//") || fullPath.startsWith("/login")) {
|
||||
return "/login";
|
||||
}
|
||||
return `/login?redirect=${encodeURIComponent(fullPath)}`;
|
||||
}
|
||||
Reference in New Issue
Block a user