feat(mall): live flash-sale page and activity price snapshots

The flash-sale page loads active sessions and their items through the shared
client with live sale price, remaining activity stock, sell-through, and a
countdown, and adds the SKU to the existing cart so checkout resolves the
authoritative price. Payment and order detail tag and render the snapshotted
activity unit price.

The flash-sale fixtures leave the page; the fixed-data adapter still serves the
domain as the rollback path.
This commit is contained in:
2026-09-18 12:53:26 +00:00
parent 393e7f7209
commit 2125ae437f
10 changed files with 283 additions and 60 deletions
+4
View File
@@ -11,6 +11,8 @@ export default {
originalPrice: "Original price",
progress: "Sold {n}%",
buyNow: "Grab now",
grabFailed: "Unable to add this item right now.",
flashTag: "Flash sale",
noSeckillProducts: "No flash-sale products right now.",
collectiveTitle: "Group deals",
collectiveBreadcrumb: "Group deals",
@@ -69,6 +71,8 @@ export default {
originalPrice: "原价",
progress: "已抢 {n}%",
buyNow: "马上抢",
grabFailed: "加入购物车失败,请稍后重试。",
flashTag: "秒杀价",
noSeckillProducts: "当前暂无秒杀商品。",
collectiveTitle: "拼团购",
collectiveBreadcrumb: "拼团",
+57
View File
@@ -15,6 +15,10 @@ import type {
Coupon,
CouponTemplate,
CouponTemplateInput,
FlashSaleItem,
FlashSaleItemInput,
FlashSaleSession,
FlashSaleSessionInput,
HomeContent,
IntegralOrder,
IntegralProduct,
@@ -23,6 +27,7 @@ import type {
InvoiceKind,
Order,
Product,
PublicFlashSaleSession,
RedeemPointsBody,
Shipment,
ShopProfile,
@@ -43,9 +48,11 @@ import {
USER_STATS,
MOCK_ADDRESSES,
defaultAddress,
lowestSku,
mockConvertMinor,
productById,
searchMockProducts,
seckillProducts,
seedOrders,
storeById,
} from "./data";
@@ -150,6 +157,46 @@ function seedPointsProducts(): IntegralProduct[] {
}));
}
/** One synthesized active session covering the fixed seckill fixtures. */
function mockFlashSales(): PublicFlashSaleSession[] {
const now = Date.now();
const items = seckillProducts().map((entry, index) => {
const sku = lowestSku(entry.product);
const stock = sku?.stock ?? 100;
const sold = Math.round((stock * entry.soldPct) / 100);
return {
id: `fsi${index + 1}`,
session_id: "fs1",
sku_id: sku?.id ?? "",
product_id: entry.product.id,
product_slug: entry.product.slug,
product_name: entry.product.name,
image: entry.product.images[0] ?? null,
sku_code: sku?.sku_code ?? "",
sale_price_minor: entry.seckillPriceMinor,
currency: sku?.currency ?? BASE_CURRENCY,
original_price_minor: sku?.price_minor ?? entry.seckillPriceMinor,
original_currency: sku?.currency ?? BASE_CURRENCY,
reserved_stock: Math.max(stock - sold, 0),
sold_count: sold,
per_customer_limit: 2,
};
});
return [
{
id: "fs1",
shop_id: MOCK_STORES[0].id,
label: { en: "Flash sale", zh: "限时秒杀" },
starts_at: new Date(now - 3_600_000).toISOString(),
ends_at: new Date(now + 6 * 3_600_000).toISOString(),
enabled: true,
created_at: "2026-01-01T00:00:00.000Z",
updated_at: "2026-01-01T00:00:00.000Z",
items,
},
];
}
function initialState(): MockState {
const persisted = loadPersisted();
// Coupons and points are session-only, so a restored snapshot re-seeds them.
@@ -397,6 +444,7 @@ export function createMockApi(): ApiClient {
unit_price_minor: i.unit_price_minor,
qty: i.qty,
image: i.image,
flash_sale_item_id: null,
})),
shipping_address: shippingAddress,
created_at: new Date().toISOString(),
@@ -630,6 +678,8 @@ export function createMockApi(): ApiClient {
state.pointsProducts.filter((p) => p.published).map((p) => ({ ...p })),
),
listFlashSales: () => Promise.resolve(mockFlashSales()),
listMyRedemptions: () => Promise.resolve(state.redemptions.map((o) => ({ ...o }))),
redeemPoints: (body: RedeemPointsBody) => {
@@ -693,6 +743,13 @@ export function createMockApi(): ApiClient {
createCouponTemplate: (_body: CouponTemplateInput) => unsupported(),
updateCouponTemplate: (_id: string, _body: CouponTemplateInput) => unsupported(),
deleteCouponTemplate: (_id: string) => unsupported(),
listFlashSales: () => unsupported(),
createFlashSale: (_body: FlashSaleSessionInput) => unsupported(),
updateFlashSale: (_id: string, _body: FlashSaleSessionInput) => unsupported(),
deleteFlashSale: (_id: string) => unsupported(),
addFlashSaleItem: (_sessionId: string, _body: FlashSaleItemInput) => unsupported(),
updateFlashSaleItem: (_id: string, _body: FlashSaleItemInput) => unsupported(),
deleteFlashSaleItem: (_id: string) => unsupported(),
},
admin: {
listUsers: () => unsupported(),
+1
View File
@@ -692,6 +692,7 @@ export function seedOrders(userId: string): MockOrderSeed {
unit_price_minor: sku.price_minor,
qty,
image: product.images[0] ?? null,
flash_sale_item_id: null,
};
});
const total = items.reduce((sum, it) => sum + it.unit_price_minor * it.qty, 0);
+1 -1
View File
@@ -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"],
liveDomains: ["catalog", "currency", "content", "shops", "brands", "auth", "account", "cart", "orders", "shipments", "invoices", "addresses", "coupons", "points", "flashSales"],
appName: "mall",
},
},
+8
View File
@@ -99,6 +99,7 @@ onMounted(() => void loadOrders());
<div class="item-info">
<strong>{{ pick(item.product_name, locale) }}</strong>
<span class="muted">{{ item.sku_code }}</span>
<span v-if="item.flash_sale_item_id" class="activity-tag">{{ t("marketing.flashTag") }}</span>
</div>
<PriceText :amount-minor="item.unit_price_minor" :currency="order.currency" />
<span class="qty">× {{ item.qty }}</span>
@@ -233,6 +234,13 @@ onMounted(() => void loadOrders());
.discount-value {
color: var(--mall-red);
}
.activity-tag {
align-self: flex-start;
padding: 1px 6px;
border: 1px solid var(--mall-red);
color: var(--mall-red);
font-size: 11px;
}
.payment-panel {
margin-top: 16px;
padding: 0 18px 16px;
+88 -58
View File
@@ -1,12 +1,16 @@
<script setup lang="ts">
import { t as pick } from "@vmall/shared";
import { lowestSku, SECKILL_SESSIONS, seckillProducts } from "~/mock/data";
import type { Product } from "@vmall/shared";
import type { PublicFlashSaleItem, PublicFlashSaleSession } from "@vmall/shared";
const { locale, t } = useI18n();
const { $api } = useNuxtApp();
const cart = useCartStore();
const sessions = ref<PublicFlashSaleSession[]>([]);
const activeSessionIndex = ref(0);
const remainingSeconds = ref(0);
const products = seckillProducts();
const loading = ref(true);
const addingSkuId = ref("");
const error = ref("");
let countdownTimer: ReturnType<typeof setInterval> | undefined;
const breadcrumb = computed(() => [
@@ -14,31 +18,20 @@ const breadcrumb = computed(() => [
{ label: t("marketing.seckillBreadcrumb") },
]);
const activeSession = computed(() => SECKILL_SESSIONS[activeSessionIndex.value] ?? SECKILL_SESSIONS[0]);
function setCurrentSession(): void {
const hour = new Date().getHours();
const index = SECKILL_SESSIONS.findIndex((session) => hour >= session.startHour && hour < session.endHour);
activeSessionIndex.value = index >= 0 ? index : 0;
}
const activeSession = computed<PublicFlashSaleSession | null>(
() => sessions.value[activeSessionIndex.value] ?? sessions.value[0] ?? null,
);
function updateCountdown(): void {
const now = new Date();
const session = activeSession.value;
const end = new Date(now);
if (session.endHour === 24) {
end.setDate(end.getDate() + 1);
end.setHours(0, 0, 0, 0);
} else {
end.setHours(session.endHour, 0, 0, 0);
}
const seconds = Math.max(0, Math.ceil((end.getTime() - now.getTime()) / 1000));
if (seconds === 0) {
setCurrentSession();
updateCountdown();
if (!session) {
remainingSeconds.value = 0;
return;
}
remainingSeconds.value = seconds;
remainingSeconds.value = Math.max(
0,
Math.ceil((new Date(session.ends_at).getTime() - Date.now()) / 1000),
);
}
function formatCountdown(seconds: number): string {
@@ -49,29 +42,42 @@ function formatCountdown(seconds: number): string {
return `${p(h)}:${p(m)}:${p(s)}`;
}
function sessionState(index: number): "current" | "upcoming" | "ended" {
if (index === activeSessionIndex.value) return "current";
return index < activeSessionIndex.value ? "ended" : "upcoming";
function soldPct(item: PublicFlashSaleItem): number {
const total = item.sold_count + item.reserved_stock;
if (total <= 0) return 100;
return Math.round((item.sold_count / total) * 100);
}
function sessionStateLabel(index: number): string {
const state = sessionState(index);
if (state === "current") return t("marketing.currentSession");
if (state === "ended") return t("marketing.ended");
return t("marketing.upcoming");
}
function priceMinorOf(product: Product): number {
return lowestSku(product)?.price_minor ?? 0;
// The listing price is display only: the shopper adds the SKU to the cart and
// checkout resolves the authoritative price server-side.
async function addToCart(item: PublicFlashSaleItem): Promise<void> {
addingSkuId.value = item.sku_id;
error.value = "";
try {
await $api.addCartItem(item.sku_id, 1);
await cart.refresh();
} catch {
error.value = t("marketing.grabFailed");
} finally {
addingSkuId.value = "";
}
}
function currencyOf(product: Product): string {
return lowestSku(product)?.currency ?? "USD";
async function load(): Promise<void> {
loading.value = true;
try {
sessions.value = await $api.listFlashSales();
activeSessionIndex.value = 0;
updateCountdown();
} catch {
sessions.value = [];
} finally {
loading.value = false;
}
}
onMounted(() => {
setCurrentSession();
updateCountdown();
onMounted(async () => {
await load();
countdownTimer = setInterval(updateCountdown, 1000);
});
@@ -89,37 +95,49 @@ onBeforeUnmount(() => {
</header>
<div class="session-tabs" role="tablist">
<button
v-for="(session, index) in SECKILL_SESSIONS"
:key="session.label"
v-for="(session, index) in sessions"
:key="session.id"
type="button"
class="session-tab"
:class="{ active: sessionState(index) === 'current', ended: sessionState(index) === 'ended' }"
:class="{ active: index === activeSessionIndex }"
role="tab"
:aria-selected="sessionState(index) === 'current'"
:aria-selected="index === activeSessionIndex"
@click="activeSessionIndex = index; updateCountdown()"
>
<strong>{{ session.label }}</strong>
<span>{{ sessionStateLabel(index) }}</span>
<strong>{{ pick(session.label, locale) }}</strong>
<span>{{ index === activeSessionIndex ? t("marketing.currentSession") : t("marketing.upcoming") }}</span>
</button>
</div>
<p class="countdown" aria-live="polite">{{ t("marketing.countdown", { time: formatCountdown(remainingSeconds) }) }}</p>
<p v-if="activeSession" class="countdown" aria-live="polite">
{{ t("marketing.countdown", { time: formatCountdown(remainingSeconds) }) }}
</p>
<p v-if="error" class="seckill-error" role="alert">{{ error }}</p>
<div v-if="products.length" class="seckill-grid">
<article v-for="item in products" :key="item.product.id" class="seckill-card hover-lift">
<NuxtLink :to="`/goods/${item.product.slug}`" class="product-image">
<img :src="item.product.images[0]" :alt="pick(item.product.name, locale)" loading="lazy" />
<div v-if="loading" class="muted">{{ t("common.loading") }}</div>
<div v-else-if="activeSession && activeSession.items.length" class="seckill-grid">
<article v-for="item in activeSession.items" :key="item.id" class="seckill-card hover-lift">
<NuxtLink :to="`/goods/${item.product_slug}`" class="product-image">
<img :src="item.image || '/mock/product-1.svg'" :alt="pick(item.product_name, locale)" loading="lazy" />
</NuxtLink>
<div class="product-body">
<NuxtLink :to="`/goods/${item.product.slug}`" class="product-name">{{ pick(item.product.name, locale) }}</NuxtLink>
<NuxtLink :to="`/goods/${item.product_slug}`" class="product-name">{{ pick(item.product_name, locale) }}</NuxtLink>
<p class="price-line">
<span class="sale-price"><PriceText :amount-minor="item.seckillPriceMinor" :currency="currencyOf(item.product)" /></span>
<s class="original-price"><PriceText :amount-minor="priceMinorOf(item.product)" :currency="currencyOf(item.product)" /></s>
<span class="sale-price"><PriceText :amount-minor="item.sale_price_minor" :currency="item.currency" /></span>
<s class="original-price"><PriceText :amount-minor="item.original_price_minor" :currency="item.original_currency" /></s>
</p>
<div class="progress-line">
<div class="progress-track"><span :style="{ width: `${item.soldPct}%` }"></span></div>
<span>{{ t("marketing.progress", { n: item.soldPct }) }}</span>
<div class="progress-track"><span :style="{ width: `${soldPct(item)}%` }"></span></div>
<span>{{ t("marketing.progress", { n: soldPct(item) }) }}</span>
</div>
<NuxtLink :to="`/goods/${item.product.slug}`" class="mbtn red grab-button">{{ t("marketing.buyNow") }}</NuxtLink>
<p class="stock-line">{{ t("marketing.stock", { n: item.reserved_stock }) }}</p>
<button
type="button"
class="mbtn red grab-button"
:disabled="item.reserved_stock <= 0 || addingSkuId === item.sku_id"
@click="addToCart(item)"
>
{{ addingSkuId === item.sku_id ? t("common.loading") : t("marketing.buyNow") }}
</button>
</div>
</article>
</div>
@@ -191,6 +209,18 @@ onBeforeUnmount(() => {
.session-tab.ended strong {
color: var(--mall-faint);
}
.seckill-error {
margin: 12px 0 0;
padding: 10px 14px;
color: #b42318;
background: #fff1f0;
border: 1px solid #ffd6d2;
}
.stock-line {
margin: 8px 0 10px;
color: var(--mall-faint);
font-size: 12px;
}
.countdown {
margin: 0;
border: 1px solid var(--mall-line);
+8
View File
@@ -111,6 +111,7 @@ onMounted(() => {
<td class="prod-col">
<img :src="item.image || '/mock/product-1.svg'" :alt="pick(item.product_name, locale)" />
<span>{{ pick(item.product_name, locale) }}</span>
<span v-if="item.flash_sale_item_id" class="activity-tag">{{ t("marketing.flashTag") }}</span>
</td>
<td><PriceText :amount-minor="item.unit_price_minor" :currency="order.currency" /></td>
<td>{{ item.qty }}</td>
@@ -228,6 +229,13 @@ onMounted(() => {
font-size: 13px;
color: var(--mall-red);
}
.activity-tag {
margin-left: 6px;
padding: 1px 6px;
border: 1px solid var(--mall-red);
color: var(--mall-red);
font-size: 11px;
}
.order-total {
margin: 16px 0 0;
text-align: right;
+4 -1
View File
@@ -21,7 +21,8 @@ type LiveDomain =
| "invoices"
| "addresses"
| "coupons"
| "points";
| "points"
| "flashSales";
/**
* Explicit per-domain method picks rather than a string allowlist: indexing
@@ -78,6 +79,7 @@ const LIVE_PICKS = {
listMyRedemptions: a.listMyRedemptions,
redeemPoints: a.redeemPoints,
}),
flashSales: (a: ApiClient) => ({ listFlashSales: a.listFlashSales }),
} satisfies Record<LiveDomain, (a: ApiClient) => Partial<ApiClient>>;
const KNOWN_DOMAINS = Object.keys(LIVE_PICKS) as LiveDomain[];
@@ -98,6 +100,7 @@ const DEFAULT_LIVE_DOMAINS: LiveDomain[] = [
"addresses",
"coupons",
"points",
"flashSales",
];
export default defineNuxtPlugin(() => {