feat(mall): read the store directory from the API

Wave 5: the store directory, store home and product-page store card stop reading
MOCK_STORES, and the payment and order surfaces name their shop.

- a `shop_profiles` table beside `shops`, so the identity model both consoles
  consume is untouched, with a public `GET /api/shops` and `GET /api/shops/{slug}`
  and an admin `PUT /api/admin/shops/{id}/profile`
- a shop with no profile is still listed, with the fields absent rather than
  invented; the pages guard every block, and a missing logo renders an
  initial-letter placeholder
- `scripts/seed-demo.mjs` upserts a profile per demo shop, since profiles hang
  off shops that script creates
- payment and order pages resolve shop ids to names from one cached shop read,
  retiring the generic "Shop" label
- three things went rather than being faked, following the wave-1 precedent:
  `distanceKm` and its sort (no geo model), the store home's sales/comments
  sorts, and its "best sellers" rail (no sales model)
- `lowestSku` moved out of the fixed-data module into `apps/mall/utils/product.ts`
  and re-exported, so live pages stop importing the mock module for a pure
  helper

Verified: 28 backend tests green including five new shop tests; all three
frontends build; the directory, store home, store card and order cards all render
real data with no distance or sales claims; the fixed-data rollback still renders
the store surfaces with the backend stopped.

Note: `nuxt build` does not typecheck in this repo (no `typescript.typeCheck`,
no `vue-tsc`), which AGENTS.md implies it does. A re-export used here created no
local binding and broke internal callers at runtime while the build stayed green;
`docs/TBD-migrate-wave.md` records the gap.

OpenSpec change: openspec/changes/replace-mock-api-wave-5
This commit is contained in:
2026-09-17 17:13:32 +00:00
parent 51f8bb7c1d
commit d0b6350d2d
19 changed files with 666 additions and 130 deletions
@@ -0,0 +1,22 @@
-- Buyer-facing shop profile, kept beside `shops` rather than widening it, so the
-- identity/status model both consoles already consume stays untouched.
--
-- Schema only: a profile hangs off a shop, and the demo shops are created by
-- scripts/seed-demo.mjs, so the demo profile content lives there.
CREATE TABLE shop_profiles (
shop_id UUID PRIMARY KEY REFERENCES shops (id) ON DELETE CASCADE,
logo TEXT,
banner TEXT,
company TEXT,
region TEXT,
address JSONB,
notice JSONB,
after_sale JSONB,
-- Platform-set profile scores. There is no review model behind them.
score_rating DOUBLE PRECISION,
score_agreement DOUBLE PRECISION,
score_service DOUBLE PRECISION,
score_speed DOUBLE PRECISION,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+3
View File
@@ -10,6 +10,7 @@ pub mod orders;
pub mod shop;
pub mod shop_catalog;
pub mod shop_orders;
pub mod shops;
use axum::Router;
@@ -27,6 +28,8 @@ pub fn api_router(state: AppState) -> Router<AppState> {
.merge(cart::router(state.clone()))
.merge(orders::router(state.clone()))
.merge(shop::router(state.clone()))
.merge(shops::router(state.clone()))
.merge(shops::admin_router(state.clone()))
.merge(shop_catalog::router(state.clone()))
.merge(shop_orders::router(state.clone()))
.merge(admin::router(state))
+170
View File
@@ -0,0 +1,170 @@
use axum::{
extract::{Path, State},
routing::{get, put},
Json, Router,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;
use crate::auth::AuthUser;
use crate::error::{ApiError, ApiResult};
use crate::models::UserRole;
use crate::state::AppState;
/// A shop plus whatever profile it has. Every profile field is optional: a shop
/// without a `shop_profiles` row still renders, with nothing invented.
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct ShopProfileView {
pub id: Uuid,
pub slug: String,
pub name: Value,
pub company: Option<String>,
pub region: Option<String>,
pub address: Option<Value>,
pub logo: Option<String>,
pub banner: Option<String>,
pub notice: Option<Value>,
pub after_sale: Option<Value>,
pub score_rating: Option<f64>,
pub score_agreement: Option<f64>,
pub score_service: Option<f64>,
pub score_speed: Option<f64>,
}
const SELECT_PROFILE: &str = "SELECT s.id, s.slug, s.name,
p.company, p.region, p.address, p.logo, p.banner, p.notice, p.after_sale,
p.score_rating, p.score_agreement, p.score_service, p.score_speed
FROM shops s
LEFT JOIN shop_profiles p ON p.shop_id = s.id";
pub fn router(_state: AppState) -> Router<AppState> {
Router::new()
.route("/shops", get(list_shops))
.route("/shops/{slug}", get(get_shop))
}
pub fn admin_router(_state: AppState) -> Router<AppState> {
Router::new().route("/admin/shops/{id}/profile", put(set_shop_profile))
}
async fn list_shops(State(state): State<AppState>) -> ApiResult<Json<Vec<ShopProfileView>>> {
let shops = sqlx::query_as::<_, ShopProfileView>(&format!(
"{SELECT_PROFILE} WHERE s.status = 'active' ORDER BY s.created_at, s.slug"
))
.fetch_all(&state.db)
.await?;
Ok(Json(shops))
}
async fn get_shop(
State(state): State<AppState>,
Path(slug): Path<String>,
) -> ApiResult<Json<ShopProfileView>> {
let shop = sqlx::query_as::<_, ShopProfileView>(&format!(
"{SELECT_PROFILE} WHERE s.slug = $1 AND s.status = 'active'"
))
.bind(&slug)
.fetch_optional(&state.db)
.await?
.ok_or_else(|| ApiError::NotFound("shop".into()))?;
Ok(Json(shop))
}
#[derive(Debug, Deserialize)]
struct ProfileBody {
logo: Option<String>,
banner: Option<String>,
company: Option<String>,
region: Option<String>,
address: Option<Value>,
notice: Option<Value>,
after_sale: Option<Value>,
score_rating: Option<f64>,
score_agreement: Option<f64>,
score_service: Option<f64>,
score_speed: Option<f64>,
}
fn bilingual(label: &Value, field: &str) -> ApiResult<()> {
let ok = ["en", "zh"].iter().all(|code| {
label
.get(code)
.and_then(Value::as_str)
.is_some_and(|s| !s.trim().is_empty())
});
if !ok {
return Err(ApiError::BadRequest(format!(
"{field} needs non-empty en and zh"
)));
}
Ok(())
}
async fn set_shop_profile(
State(state): State<AppState>,
auth: AuthUser,
Path(id): Path<Uuid>,
Json(body): Json<ProfileBody>,
) -> ApiResult<Json<ShopProfileView>> {
auth.require(&[UserRole::PlatformAdmin])?;
for (value, field) in [
(&body.address, "address"),
(&body.notice, "notice"),
(&body.after_sale, "after_sale"),
] {
if let Some(label) = value {
bilingual(label, field)?;
}
}
let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM shops WHERE id = $1)")
.bind(id)
.fetch_one(&state.db)
.await?;
if !exists {
return Err(ApiError::NotFound("shop".into()));
}
sqlx::query(
"INSERT INTO shop_profiles (shop_id, logo, banner, company, region, address, notice,
after_sale, score_rating, score_agreement, score_service,
score_speed, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, now())
ON CONFLICT (shop_id) DO UPDATE SET
logo = EXCLUDED.logo,
banner = EXCLUDED.banner,
company = EXCLUDED.company,
region = EXCLUDED.region,
address = EXCLUDED.address,
notice = EXCLUDED.notice,
after_sale = EXCLUDED.after_sale,
score_rating = EXCLUDED.score_rating,
score_agreement = EXCLUDED.score_agreement,
score_service = EXCLUDED.score_service,
score_speed = EXCLUDED.score_speed,
updated_at = now()",
)
.bind(id)
.bind(&body.logo)
.bind(&body.banner)
.bind(&body.company)
.bind(&body.region)
.bind(&body.address)
.bind(&body.notice)
.bind(&body.after_sale)
.bind(body.score_rating)
.bind(body.score_agreement)
.bind(body.score_service)
.bind(body.score_speed)
.execute(&state.db)
.await?;
let shop = sqlx::query_as::<_, ShopProfileView>(&format!("{SELECT_PROFILE} WHERE s.id = $1"))
.bind(id)
.fetch_optional(&state.db)
.await?
.ok_or_else(|| ApiError::NotFound("shop".into()))?;
Ok(Json(shop))
}
+165
View File
@@ -0,0 +1,165 @@
mod common;
use common::{client, create_shop, login_admin, make_shop_owner, register_customer, spawn_app};
use serial_test::serial;
/// The suite shares one database and creating shops is additive, so each test
/// works on shops it creates itself and never asserts on a global count.
async fn list_shops(app: &common::TestApp) -> serde_json::Value {
let res = client().get(app.url("/api/shops")).send().await.unwrap();
assert_eq!(res.status(), 200, "the directory must be unauthenticated");
res.json().await.unwrap()
}
fn find<'a>(shops: &'a serde_json::Value, id: &str) -> Option<&'a serde_json::Value> {
shops
.as_array()
.unwrap()
.iter()
.find(|s| s["id"] == id)
}
async fn set_profile(
app: &common::TestApp,
token: &str,
shop_id: &str,
body: serde_json::Value,
) -> reqwest::Response {
client()
.put(app.url(&format!("/api/admin/shops/{shop_id}/profile")))
.bearer_auth(token)
.json(&body)
.send()
.await
.unwrap()
}
#[tokio::test]
#[serial]
async fn shop_without_a_profile_is_still_listed() {
let app = spawn_app().await;
let admin = login_admin(&app).await;
let shop_id = create_shop(&app, &admin, "shop-noprofile").await;
let shops = list_shops(&app).await;
let shop = find(&shops, &shop_id).expect("a shop with no profile must still be listed");
assert!(shop["name"]["en"].is_string());
assert!(shop["logo"].is_null(), "nothing may be invented for a missing profile");
assert!(shop["score_rating"].is_null());
}
#[tokio::test]
#[serial]
async fn profile_upsert_round_trips_to_the_public_read() {
let app = spawn_app().await;
let admin = login_admin(&app).await;
let shop_id = create_shop(&app, &admin, "shop-profile").await;
let body = serde_json::json!({
"logo": "/mock/store-1.svg",
"company": "Profile Co.",
"region": "California",
"address": {"en": "1 Market Street", "zh": "市场街 1 号"},
"notice": {"en": "Free shipping over $99.", "zh": "满 99 免运费。"},
"after_sale": {"en": "7-day returns.", "zh": "7 天退货。"},
"score_rating": 4.9,
"score_agreement": 4.8,
"score_service": 4.7,
"score_speed": 4.6
});
let res = set_profile(&app, &admin, &shop_id, body).await;
assert_eq!(res.status(), 200, "{:?}", res.text().await);
let shop = find(&list_shops(&app).await, &shop_id).unwrap().clone();
assert_eq!(shop["company"], "Profile Co.");
assert_eq!(shop["address"]["zh"], "市场街 1 号");
assert_eq!(shop["score_rating"], 4.9);
// Public read by slug returns the same composed profile.
let slug = shop["slug"].as_str().unwrap();
let res = client()
.get(app.url(&format!("/api/shops/{slug}")))
.send()
.await
.unwrap();
assert_eq!(res.status(), 200);
let by_slug: serde_json::Value = res.json().await.unwrap();
assert_eq!(by_slug["id"], shop_id);
assert_eq!(by_slug["notice"]["en"], "Free shipping over $99.");
}
#[tokio::test]
#[serial]
async fn suspended_or_unknown_shops_are_not_public() {
let app = spawn_app().await;
let admin = login_admin(&app).await;
let shop_id = create_shop(&app, &admin, "shop-suspended").await;
let shops = list_shops(&app).await;
let slug = find(&shops, &shop_id).unwrap()["slug"].as_str().unwrap().to_string();
client()
.put(app.url(&format!("/api/admin/shops/{shop_id}/status")))
.bearer_auth(&admin)
.json(&serde_json::json!({ "status": "suspended" }))
.send()
.await
.unwrap();
assert!(find(&list_shops(&app).await, &shop_id).is_none(), "suspended shops are hidden");
let res = client()
.get(app.url(&format!("/api/shops/{slug}")))
.send()
.await
.unwrap();
assert_eq!(res.status(), 404);
let res = client()
.get(app.url("/api/shops/no-such-shop-at-all"))
.send()
.await
.unwrap();
assert_eq!(res.status(), 404, "an unknown slug is a 404, not an empty profile");
}
#[tokio::test]
#[serial]
async fn incomplete_bilingual_text_is_refused_without_writing() {
let app = spawn_app().await;
let admin = login_admin(&app).await;
let shop_id = create_shop(&app, &admin, "shop-bilingual").await;
let good = serde_json::json!({
"company": "Kept Co.",
"notice": {"en": "Original notice", "zh": "原始公告"}
});
assert_eq!(set_profile(&app, &admin, &shop_id, good).await.status(), 200);
let bad = serde_json::json!({
"company": "Changed Co.",
"notice": {"en": "Only English"}
});
let res = set_profile(&app, &admin, &shop_id, bad).await;
assert_eq!(res.status(), 400, "a label missing zh must be refused");
let shop = find(&list_shops(&app).await, &shop_id).unwrap().clone();
assert_eq!(shop["company"], "Kept Co.", "the rejected write changed nothing");
assert_eq!(shop["notice"]["zh"], "原始公告");
}
#[tokio::test]
#[serial]
async fn profile_writes_require_a_platform_admin() {
let app = spawn_app().await;
let admin = login_admin(&app).await;
let shop_id = create_shop(&app, &admin, "shop-profile-auth").await;
let owner = make_shop_owner(&app, &admin, &shop_id).await;
let (customer, _) = register_customer(&app, "shop-profile-cust").await;
let body = serde_json::json!({ "company": "Nope" });
for token in [&owner, &customer] {
let res = set_profile(&app, token, &shop_id, body.clone()).await;
assert_eq!(res.status(), 403, "only platform admins may write a profile");
}
}
+31
View File
@@ -15,6 +15,7 @@ import type {
Order,
Product,
Shipment,
ShopProfile,
User,
} from "@vmall/shared";
import {
@@ -87,6 +88,28 @@ function unsupported(): never {
throw new ApiError(501, "MOCK_UNSUPPORTED", "This admin/shop endpoint is not part of the mall mock.");
}
type MockStoreRecord = NonNullable<ReturnType<typeof storeById>>;
/** Mock stores carry a nested `rate`; the API exposes flat score fields. */
function toShopProfile(store: MockStoreRecord): ShopProfile {
return {
id: store.id,
slug: store.slug,
name: store.name,
company: store.company,
region: store.region,
address: store.address,
logo: store.logo,
banner: store.banner,
notice: store.notice,
after_sale: store.afterSale,
score_rating: store.rate.score,
score_agreement: store.rate.agree,
score_service: store.rate.service,
score_speed: store.rate.speed,
};
}
function skuIndex(): Record<string, { product: Product; skuId: string }> {
const index: Record<string, { product: Product; skuId: string }> = {};
@@ -352,6 +375,13 @@ export function createMockApi(): ApiClient {
})),
}),
listShops: (): Promise<ShopProfile[]> => Promise.resolve(MOCK_STORES.map(toShopProfile)),
getShop: (slug) => {
const store = storeById(slug);
if (!store) return Promise.reject(new ApiError(404, "NOT_FOUND", "Shop not found"));
return Promise.resolve(toShopProfile(store));
},
shop: {
getMyShop: () => unsupported(),
listMyProducts: () => unsupported(),
@@ -381,6 +411,7 @@ export function createMockApi(): ApiClient {
setRate: () => unsupported(),
getContent: () => unsupported(),
replaceContent: () => unsupported(),
setShopProfile: () => unsupported(),
},
};
}
+4 -9
View File
@@ -491,15 +491,10 @@ export function storeById(idOrSlug: string): MockStore | null {
return MOCK_STORES.find((s) => s.id === idOrSlug || s.slug === idOrSlug) ?? null;
}
export function lowestSku(product: Product): Sku | null {
const active = (product.skus ?? []).filter((s) => s.active && s.stock > 0);
return (
active.reduce<Sku | null>(
(low, s) => (low === null || s.price_minor < low.price_minor ? s : low),
null,
) ?? (product.skus ?? []).find((s) => s.active) ?? null
);
}
import { lowestSku } from "~/utils/product";
/** Kept for the mock-era pages; live pages import it from `~/utils/product`. */
export { lowestSku };
export interface MockSearchQuery {
q?: string;
+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", "auth", "cart", "orders", "shipments", "invoices"],
liveDomains: ["catalog", "currency", "content", "shops", "auth", "cart", "orders", "shipments", "invoices"],
appName: "mall",
},
},
+8 -2
View File
@@ -9,6 +9,13 @@ const { locale, t } = useI18n();
const { currency } = usePrefs();
const router = useRouter();
const pendingOrderIds = useState<string[]>("checkout-orders", () => []);
// Shared with the store directory; orders carry only a shop id.
const { data: shops } = await useAsyncData("shops", () => $api.listShops(), { default: () => [] });
function shopName(shopId: string): string {
const shop = shops.value.find((entry) => entry.id === shopId);
return shop ? pick(shop.name, locale.value) : t("checkout.shop");
}
const orders = ref<Order[]>([]);
const paymentMethod = ref("balance");
@@ -85,8 +92,7 @@ onMounted(() => void loadOrders());
<article v-for="order in orders" :key="order.id" class="mpanel order-card">
<header class="order-heading">
<span>{{ t("checkout.orderNo") }}: {{ order.order_no }}</span>
<!-- Store names need the public store read; see docs/TBD-migrate-wave.md. -->
<span class="shop-name">{{ t("checkout.shop") }}</span>
<span class="shop-name">{{ shopName(order.shop_id) }}</span>
</header>
<div v-for="item in order.items" :key="item.id" class="order-item">
<img :src="imageFor(item.image)" :alt="pick(item.product_name, locale)" />
+29 -25
View File
@@ -2,15 +2,8 @@
import { t as pick } from "@vmall/shared";
import { ApiError } from "@vmall/shared";
import type { Category, Product, Sku } from "@vmall/shared";
import {
MOCK_COUPONS,
MOCK_STORES,
commentStats,
commentsFor,
lowestSku,
salesOf,
storeById,
} from "~/mock/data";
import { MOCK_COUPONS, commentStats, commentsFor, salesOf } from "~/mock/data";
import { lowestSku } from "~/utils/product";
import { useCartStore } from "~/stores/cart";
type AttributeGroup = { key: string; values: string[] };
@@ -51,12 +44,16 @@ const { data: pageData } = await useAsyncData(
const product = computed(() => pageData.value?.product ?? null);
const related = computed<Product[]>(() => pageData.value?.related ?? []);
// Shared with the store directory and the order surfaces.
const { data: shops } = await useAsyncData("shops", () => $api.listShops(), { default: () => [] });
const detail = computed(() => {
const current = product.value;
if (!current) return null;
return {
product: current,
store: storeById(current.shop_id) ?? MOCK_STORES[0],
// Null when the shop has no public profile; the card is then not rendered.
store: shops.value.find((shop) => shop.id === current.shop_id) ?? null,
comments: commentsFor(current.id),
commentStats: commentStats(current.id),
coupons: MOCK_COUPONS,
@@ -183,14 +180,19 @@ const tabs = computed(() => [
{ key: "service", label: t("product.tabsAfterSale") },
]);
/** Only the scores the platform actually set; nothing is defaulted. */
const rateRows = computed(() => {
const rate = store.value?.rate;
return [
{ key: "overall", value: rate?.score ?? 0, label: t("product.overall") },
{ key: "service", value: rate?.service ?? 0, label: t("product.service") },
{ key: "delivery", value: rate?.speed ?? 0, label: t("product.delivery") },
{ key: "agree", value: rate?.agree ?? 0, label: t("product.quality") },
const profile = store.value;
if (!profile) return [];
const rows = [
{ key: "overall", value: profile.score_rating, label: t("product.overall") },
{ key: "service", value: profile.score_service, label: t("product.service") },
{ key: "delivery", value: profile.score_speed, label: t("product.delivery") },
{ key: "agree", value: profile.score_agreement, label: t("product.quality") },
];
return rows.filter(
(row): row is { key: string; value: number; label: string } => typeof row.value === "number",
);
});
const detailImages = computed(() => product.value?.images ?? []);
@@ -283,20 +285,22 @@ const detailImages = computed(() => product.value?.images ?? []);
<section class="below-grid">
<aside class="left-rail">
<div class="store-card mpanel">
<div v-if="detail.store" class="store-card mpanel">
<h2>{{ t("product.store") }}</h2>
<div class="store-heading">
<img :src="detail.store.logo" :alt="pick(detail.store.name, locale)" />
<img v-if="detail.store.logo" :src="detail.store.logo" :alt="pick(detail.store.name, locale)" />
<strong>{{ pick(detail.store.name, locale) }}</strong>
</div>
<dl>
<div><dt>{{ t("product.company") }}</dt><dd>{{ detail.store.company }}</dd></div>
<div><dt>{{ t("product.region") }}</dt><dd>{{ detail.store.region }}</dd></div>
<div v-if="detail.store.company"><dt>{{ t("product.company") }}</dt><dd>{{ detail.store.company }}</dd></div>
<div v-if="detail.store.region"><dt>{{ t("product.region") }}</dt><dd>{{ detail.store.region }}</dd></div>
</dl>
<h3>{{ t("product.rates") }}</h3>
<div v-for="row in rateRows" :key="row.key" class="rate-row">
<span>{{ row.label }}</span><UiRatingStars :value="row.value" :size="13" />
</div>
<template v-if="rateRows.length">
<h3>{{ t("product.rates") }}</h3>
<div v-for="row in rateRows" :key="row.key" class="rate-row">
<span>{{ row.label }}</span><UiRatingStars :value="row.value" :size="13" />
</div>
</template>
<div class="store-actions">
<NuxtLink class="store-button" :to="`/stores/${detail.store.slug}`">{{ t("product.enterStore") }}</NuxtLink>
<button type="button" class="store-button" disabled>{{ t("product.contact") }}</button>
@@ -336,7 +340,7 @@ const detailImages = computed(() => product.value?.images ?? []);
</div>
<div v-else class="service-content">
<h2>{{ t("product.tabsAfterSale") }}</h2>
<p>{{ pick(detail.store.afterSale, locale) }}</p>
<p v-if="detail.store?.after_sale">{{ pick(detail.store.after_sale, locale) }}</p>
</div>
</template>
</UiTabs>
+60 -44
View File
@@ -1,31 +1,48 @@
<script setup lang="ts">
import { t as pick } from "@vmall/shared";
import { lowestSku, salesOf, searchMockProducts, storeDetail } from "~/mock/data";
import type { Paged, Product } from "@vmall/shared";
import { lowestSku } from "~/utils/product";
const route = useRoute();
const { locale, t } = useI18n();
const storeId = computed(() => {
const { $api } = useNuxtApp();
const slug = computed(() => {
const raw = route.params.id;
return typeof raw === "string" ? raw : raw?.[0] ?? "";
});
const detail = computed(() => storeDetail(storeId.value));
const store = computed(() => detail.value?.store ?? null);
// A rejected read (unknown or suspended slug) leaves this null, which renders
// the "unknown store" branch rather than an invented profile.
const { data: shop } = await useAsyncData("shop-profile", () => $api.getShop(slug.value), {
watch: [slug],
default: () => null,
});
const store = computed(() => shop.value);
const favorite = ref(false);
const sortMode = ref<"default" | "price" | "sales" | "comments">("default");
// 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");
const page = ref(1);
const perPage = 12;
const emptyPage: Paged<Product> = { items: [], total: 0, page: 1, per_page: perPage };
const productResult = computed(() => {
if (!store.value) return { items: [], total: 0, page: 1, per_page: perPage };
return searchMockProducts({
shopId: store.value.id,
sort: sortMode.value,
order: sortOrder.value,
page: page.value,
perPage,
});
});
const { data: productResult } = await useAsyncData(
"shop-products",
() => {
const current = store.value;
if (!current) return Promise.resolve(emptyPage);
return $api.listProducts({
shop_id: current.id,
sort: sortMode.value === "price" ? "price" : undefined,
order: sortMode.value === "price" ? sortOrder.value : undefined,
page: page.value,
per_page: perPage,
});
},
{ watch: [store, sortMode, sortOrder, page], default: () => emptyPage },
);
const breadcrumb = computed(() => [
{ label: t("stores.breadcrumbHome"), to: "/" },
@@ -33,26 +50,28 @@ const breadcrumb = computed(() => [
{ label: store.value ? pick(store.value.name, locale.value) : t("stores.unknownStore") },
]);
/** Only the scores the platform actually set; nothing is defaulted. */
const rateRows = computed(() => {
if (!store.value) return [];
return [
{ label: t("stores.score"), value: store.value.rate.score },
{ label: t("stores.agreement"), value: store.value.rate.agree },
{ label: t("stores.service"), value: store.value.rate.service },
{ label: t("stores.speed"), value: store.value.rate.speed },
const current = store.value;
if (!current) return [];
const rows = [
{ label: t("stores.score"), value: current.score_rating },
{ label: t("stores.agreement"), value: current.score_agreement },
{ label: t("stores.service"), value: current.score_service },
{ label: t("stores.speed"), value: current.score_speed },
];
return rows.filter((row): row is { label: string; value: number } => typeof row.value === "number");
});
function priceMinorOf(product: Parameters<typeof lowestSku>[0]): number {
function priceMinorOf(product: Product): number {
return lowestSku(product)?.price_minor ?? 0;
}
function currencyOf(product: Parameters<typeof lowestSku>[0]): string {
function currencyOf(product: Product): string {
return lowestSku(product)?.currency ?? "USD";
}
const salesRank = computed(() => detail.value?.salesRank ?? []);
function chooseSort(mode: "default" | "price" | "sales" | "comments"): void {
function chooseSort(mode: "default" | "price"): void {
if (sortMode.value === mode && mode !== "default") {
sortOrder.value = sortOrder.value === "asc" ? "desc" : "asc";
} else {
@@ -67,20 +86,21 @@ function chooseSort(mode: "default" | "price" | "sales" | "comments"): void {
<div class="store-page">
<UiBreadcrumb :items="breadcrumb" />
<template v-if="store">
<div class="w1200 store-banner">
<div v-if="store.banner" class="w1200 store-banner">
<img :src="store.banner" :alt="pick(store.name, locale)" />
</div>
<div class="w1200 store-layout">
<aside class="store-rail">
<section class="mpanel store-card">
<div class="store-heading">
<img :src="store.logo" :alt="pick(store.name, locale)" />
<img v-if="store.logo" :src="store.logo" :alt="pick(store.name, locale)" />
<span v-else class="store-logo-placeholder" aria-hidden="true">{{ pick(store.name, locale).slice(0, 1) }}</span>
<div>
<h1>{{ pick(store.name, locale) }}</h1>
<p>{{ t("stores.positiveRate") }}</p>
</div>
</div>
<div class="rate-list">
<div v-if="rateRows.length" class="rate-list">
<div v-for="row in rateRows" :key="row.label" class="rate-row">
<span>{{ row.label }}</span>
<UiRatingStars :value="row.value" :size="13" />
@@ -88,26 +108,24 @@ function chooseSort(mode: "default" | "price" | "sales" | "comments"): void {
</div>
</div>
<dl class="store-info">
<div><dt>{{ t("stores.company") }}</dt><dd>{{ store.company }}</dd></div>
<div><dt>{{ t("stores.region") }}</dt><dd>{{ store.region }}</dd></div>
<div><dt>{{ t("stores.address") }}</dt><dd>{{ pick(store.address, locale) }}</dd></div>
<div v-if="store.company"><dt>{{ t("stores.company") }}</dt><dd>{{ store.company }}</dd></div>
<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">
{{ favorite ? t("stores.favorited") : t("stores.favorite") }}
</button>
</section>
<section class="mpanel sales-card">
<h2 class="rail-title">{{ t("stores.salesRank") }}</h2>
<NuxtLink v-for="(product, index) in salesRank" :key="product.id" :to="`/goods/${product.slug}`" class="rank-item">
<span class="rank-number">{{ index + 1 }}</span>
<img :src="product.images[0]" :alt="pick(product.name, locale)" loading="lazy" />
<span class="rank-copy">
<span class="rank-name">{{ pick(product.name, locale) }}</span>
<span class="rank-sales">{{ t("product.salesCount", { n: salesOf(product) }) }}</span>
</span>
<span class="rank-price"><PriceText :amount-minor="priceMinorOf(product)" :currency="currencyOf(product)" /></span>
</NuxtLink>
<section v-if="store.notice || store.after_sale" class="mpanel notice-card">
<template v-if="store.notice">
<h2 class="rail-title">{{ t("stores.notice") }}</h2>
<p>{{ pick(store.notice, locale) }}</p>
</template>
<template v-if="store.after_sale">
<h2 class="rail-title">{{ t("stores.afterSale") }}</h2>
<p>{{ pick(store.after_sale, locale) }}</p>
</template>
</section>
</aside>
@@ -117,8 +135,6 @@ function chooseSort(mode: "default" | "price" | "sales" | "comments"): void {
<div class="product-sorts" role="tablist">
<button type="button" :class="{ active: sortMode === 'default' }" @click="chooseSort('default')">{{ t("stores.sortDefault") }}</button>
<button type="button" :class="{ active: sortMode === 'price' }" @click="chooseSort('price')">{{ t("stores.sortPrice") }}</button>
<button type="button" :class="{ active: sortMode === 'sales' }" @click="chooseSort('sales')">{{ t("stores.sortSales") }}</button>
<button type="button" :class="{ active: sortMode === 'comments' }" @click="chooseSort('comments')">{{ t("stores.sortComments") }}</button>
</div>
</header>
<div v-if="productResult.items.length" class="product-grid">
+21 -29
View File
@@ -1,15 +1,12 @@
<script setup lang="ts">
import { t as pick } from "@vmall/shared";
import { MOCK_STORES } from "~/mock/data";
const { locale, t } = useI18n();
const sortMode = ref<"default" | "distance">("default");
const { $api } = useNuxtApp();
const stores = computed(() => {
const list = [...MOCK_STORES];
if (sortMode.value === "distance") list.sort((a, b) => a.distanceKm - b.distanceKm);
return list;
});
// Shared with the order surfaces, which resolve shop ids to names from it.
const { data: shops } = await useAsyncData("shops", () => $api.listShops(), { default: () => [] });
const stores = computed(() => shops.value);
const breadcrumb = computed(() => [
{ label: t("stores.breadcrumbHome"), to: "/" },
@@ -23,40 +20,24 @@ const breadcrumb = computed(() => [
<section class="w1200 store-directory">
<header class="sort-row">
<h1>{{ t("stores.directory") }}</h1>
<div class="sort-options" role="tablist">
<button
type="button"
:class="{ active: sortMode === 'default' }"
role="tab"
:aria-selected="sortMode === 'default'"
@click="sortMode = 'default'"
>{{ t("stores.sortDefault") }}</button>
<button
type="button"
:class="{ active: sortMode === 'distance' }"
role="tab"
:aria-selected="sortMode === 'distance'"
@click="sortMode = 'distance'"
>{{ t("stores.sortDistance") }}</button>
</div>
</header>
<div v-if="stores.length" class="store-list">
<article v-for="store in stores" :key="store.id" class="store-row hover-lift">
<NuxtLink :to="`/stores/${store.slug}`" class="store-logo-link">
<img class="store-logo" :src="store.logo" :alt="pick(store.name, locale)" loading="lazy" />
<img v-if="store.logo" class="store-logo" :src="store.logo" :alt="pick(store.name, locale)" loading="lazy" />
<span v-else class="store-logo store-logo-placeholder" aria-hidden="true">{{ pick(store.name, locale).slice(0, 1) }}</span>
</NuxtLink>
<div class="store-main">
<NuxtLink :to="`/stores/${store.slug}`" class="store-name">{{ pick(store.name, locale) }}</NuxtLink>
<p class="store-company">{{ store.company }}</p>
<p class="store-location">
<span>{{ t("stores.region") }}{{ store.region }}</span>
<span>{{ t("stores.address") }}{{ pick(store.address, locale) }}</span>
<p v-if="store.company" class="store-company">{{ store.company }}</p>
<p v-if="store.region || store.address" class="store-location">
<span v-if="store.region">{{ t("stores.region") }}{{ store.region }}</span>
<span v-if="store.address">{{ t("stores.address") }}{{ pick(store.address, locale) }}</span>
</p>
</div>
<div class="store-rating">{{ t("stores.positiveRate") }}</div>
<div class="store-actions">
<span class="distance">{{ t("stores.distance", { n: store.distanceKm.toFixed(1) }) }}</span>
<NuxtLink :to="`/stores/${store.slug}`" class="mbtn red">{{ t("stores.visitStore") }}</NuxtLink>
</div>
</article>
@@ -138,6 +119,17 @@ h1 {
height: 72px;
object-fit: contain;
}
/* A shop with no profile still needs a mark, without inventing a logo. */
.store-logo-placeholder {
display: flex;
align-items: center;
justify-content: center;
background: var(--mall-line);
color: var(--mall-muted);
font-size: 28px;
font-weight: 700;
text-transform: uppercase;
}
.store-main {
min-width: 0;
flex: 1;
+10 -4
View File
@@ -8,8 +8,15 @@ const { locale, t } = useI18n();
const { $api } = useNuxtApp();
const route = useRoute();
const activeFilter = ref("all");
const orders = ref<Order[]>([]);
// Shared with the store directory; orders carry only a shop id.
const { data: shops } = await useAsyncData("shops", () => $api.listShops(), { default: () => [] });
function shopName(shopId: string): string {
const shop = shops.value.find((entry) => entry.id === shopId);
return shop ? pick(shop.name, locale.value) : t("user.shop");
}
const activeFilter = ref("all");const orders = ref<Order[]>([]);
const page = ref(1);
const total = ref(0);
const perPage = ref(10);
@@ -105,8 +112,7 @@ onMounted(() => {
<article v-for="order in filteredOrders" :key="order.id" class="order-card">
<header class="order-header">
<div>
<!-- Store names need the public store read; see docs/TBD-migrate-wave.md. -->
<strong>{{ t("user.shop") }}</strong>
<strong>{{ shopName(order.shop_id) }}</strong>
<span>{{ t("user.orderNo") }} {{ order.order_no }}</span>
<span>{{ t("user.createdAt") }} {{ order.created_at.slice(0, 10) }}</span>
</div>
+3
View File
@@ -12,6 +12,7 @@ type LiveDomain =
| "catalog"
| "currency"
| "content"
| "shops"
| "cart"
| "orders"
| "shipments"
@@ -31,6 +32,7 @@ const LIVE_PICKS = {
}),
currency: (a: ApiClient) => ({ listCurrencies: a.listCurrencies, convert: a.convert }),
content: (a: ApiClient) => ({ getHomeContent: a.getHomeContent }),
shops: (a: ApiClient) => ({ listShops: a.listShops, getShop: a.getShop }),
cart: (a: ApiClient) => ({
getCart: a.getCart,
addCartItem: a.addCartItem,
@@ -61,6 +63,7 @@ const DEFAULT_LIVE_DOMAINS: LiveDomain[] = [
"catalog",
"currency",
"content",
"shops",
"auth",
"cart",
"orders",
+15
View File
@@ -0,0 +1,15 @@
import type { Product, Sku } from "@vmall/shared";
/**
* Cheapest active SKU, preferring one that is in stock. A pure helper over a
* `Product`, so it lives here rather than in the fixed-data module.
*/
export function lowestSku(product: Product): Sku | null {
const active = (product.skus ?? []).filter((sku) => sku.active && sku.stock > 0);
return (
active.reduce<Sku | null>(
(low, sku) => (low === null || sku.price_minor < low.price_minor ? sku : low),
null,
) ?? (product.skus ?? []).find((sku) => sku.active) ?? null
);
}
+7 -1
View File
@@ -49,7 +49,7 @@ leaves the mock half reading state the live half never populates:
Each is a new backend capability rather than a domain flip.
- [x] **Storefront content** — banners, promos, quick links and floor advert art. Done in `replace-mock-api-wave-4`: four tables seeded from the existing assets, a public `GET /api/content/home`, and an admin read/replace pair.
- [ ] **Public store read** — a buyer-facing shop endpoint so `stores/index`, `stores/[id]` and the cart's shop grouping leave mock. Small: products already carry `shop_id`, and the public catalog already joins shops for the active check.
- [x] **Public store read** — a buyer-facing shop endpoint so `stores/index`, `stores/[id]` and the cart's shop grouping leave mock. Done in `replace-mock-api-wave-5`: a `shop_profiles` table, `GET /api/shops` + `GET /api/shops/{slug}`, an admin upsert, and the order surfaces now name their shop. Two things went rather than being faked: `distanceKm` (no geo model) and the store home's "best sellers" rail plus its sales/comments sorts (no sales model).
- [ ] **Brand model + sales/comments sorts** — restores the brand facet and the sorts removed in Wave 1. Needs a `brands` table (`products.brand_id` + i18n) plus sales and comments data, neither of which exists today.
- [ ] Extend the `ORDER BY` whitelist if more sorts are wanted beyond the `sort=price` added in Wave 1.
- [ ] *(adjacent, not part of the migration)* Move the session token to a cookie so SSR knows whether anyone is signed in. Today a full page load of a guarded route renders the page and then redirects on the client, which logs a hydration mismatch; it is pre-existing (verified identical before Wave 2) and harmless, but it is the real fix for the `ClientOnly` workarounds in `components/shell/TopBar.vue` and `pages/user.vue`.
@@ -70,3 +70,9 @@ These have no API contract and no backend model. Leaving them on `~/mock/data` i
- A migration wave must not change what the UI claims: facets without a backing model are removed rather than left matching nothing.
- The mall is the last mock holdout; `shop-admin` and `admin` already run live against the same backend.
- Auth flips independently, but the transaction domains do not: the mock's shared cart/order/shipment state makes any partial flip fail loudly.
## Known gap: the frontend builds do not typecheck
`pnpm --filter @vmall/<app> build` runs `nuxt build`, which does **not** typecheck: `nuxt.config.ts` sets no `typescript.typeCheck` and `vue-tsc` is not installed. AGENTS.md describes the build as the type gate, so a passing build has been read as type-safe across waves 15; it is not. Wave 5 found this the hard way — `export { lowestSku } from "~/utils/product"` creates no local binding, so every internal caller broke at runtime while the build stayed green.
Cheap fix when someone wants it: add `vue-tsc` + `typescript` as devDependencies, set `typescript: { typeCheck: true }`, and expect a backlog of pre-existing errors on first run. Until then treat the browser check, not the build, as the thing that proves a page works.
@@ -2,31 +2,32 @@
## 1. Schema
- [ ] 1.1 Add a migration creating `shop_profiles` keyed 1:1 to `shops` (`shop_id` primary key, `logo`, `banner`, `company`, `region`, `address` JSONB, `notice` JSONB, `after_sale` JSONB, four score columns, `updated_at`); verify the table exists after `cargo run -p vmall-api`
- [x] 1.1 Add a migration creating `shop_profiles` keyed 1:1 to `shops` (`shop_id` primary key, `logo`, `banner`, `company`, `region`, `address` JSONB, `notice` JSONB, `after_sale` JSONB, four score columns, `updated_at`); verified the table exists after `cargo run -p vmall-api`
## 2. Shared contract
- [ ] 2.1 Add `ShopProfile` (shop identity plus the optional profile fields) and a `ShopProfileInput` to `packages/shared/src/types.ts`; verify all three frontends build
- [ ] 2.2 Add `listShops()` / `getShop(slug)` to the `ApiClient` and `createApi`, plus `admin.setShopProfile(id, body)`; give the fixed-data adapter matching implementations built from `MOCK_STORES` so the rollback path still renders; verify the mall build
- [x] 2.1 Add `ShopProfile` and `ShopProfileInput` to `packages/shared/src/types.ts`, with every profile field nullable; verified all three frontends build
- [x] 2.2 Add `listShops()` / `getShop(slug)`, `admin.setShopProfile(id, body)` and fixed-data implementations built from `MOCK_STORES`; also registered a `shops` domain in the per-domain switch. Unlike wave 4, where that registration was missed and only the browser caught it, here the domain was added alongside the methods
## 3. Public shop read
- [ ] 3.1 Add `GET /api/shops` returning active shops with their profile, and `GET /api/shops/{slug}` returning one, both unauthenticated and both tolerating a missing profile row; verify a suspended shop is absent from the list and an unknown slug is a 404
- [ ] 3.2 Add `PUT /api/admin/shops/{id}/profile` upserting the profile, validating non-empty `en`/`zh` on bilingual fields and gated to `platform_admin`; verify a bad payload is refused without changing the stored row
- [x] 3.1 Add unauthenticated `GET /api/shops` and `GET /api/shops/{slug}`, both tolerating a missing profile row; verified a suspended shop is absent from the list and that a suspended or unknown slug is a 404
- [x] 3.2 Add `PUT /api/admin/shops/{id}/profile` upserting the profile, refusing bilingual fields without non-empty `en`/`zh` and gated to `platform_admin`; verified a rejected payload leaves the stored profile untouched
## 4. Demo profiles
- [ ] 4.1 Teach `scripts/seed-demo.mjs` to set a profile for each demo shop using the existing `/mock/store-N.svg` assets and bilingual copy; verify a re-run is idempotent and `GET /api/shops` returns a profile for every shop
- [x] 4.1 Teach `scripts/seed-demo.mjs` to upsert a profile per demo shop; verified a re-run is idempotent and `GET /api/shops` returns all four with logos, companies and scores
## 5. Mall store surfaces
- [ ] 5.1 `pages/stores/index.vue`: list from `GET /api/shops` and drop the distance column and its sort; verify the directory renders every active shop and no "km" text remains
- [ ] 5.2 `pages/stores/[id].vue`: load the shop by slug and its products from the catalog API by `shop_id`, drop the mock sales ranking in favour of the same shop-scoped product call; verify a store page renders its profile and products
- [ ] 5.3 `pages/goods/[id].vue`: read the store card from the shop API instead of `storeById`, keeping the existing guards for a missing profile
- [ ] 5.4 `pages/checkout/pay.vue` and `pages/user/orders/index.vue`: resolve shop names from the cached shop read, removing the generic "Shop" placeholder
- [x] 5.1 `pages/stores/index.vue`: list from `GET /api/shops`, dropping the distance column, its sort and the whole two-option sort control that existed only to offer it; verified four shops render with their logos and no "km" text. A shop with no logo renders an initial-letter placeholder rather than an invented image
- [x] 5.2 `pages/stores/[id].vue`: load the shop by slug and its products from the catalog API by `shop_id`; verified the profile, its score rows and six products render. Two removals were needed beyond the plan, both following the wave-1 precedent that a UI must not claim what no model backs: the sort is now default + price only (sales and comments have no model), and the "best sellers" rail is gone because nothing ranks by sales
- [x] 5.3 `pages/goods/[id].vue`: read the store card from the shared shop read instead of `storeById`, guarding every field and dropping the card entirely when a shop has no profile
- [x] 5.4 `pages/checkout/pay.vue` and `pages/user/orders/index.vue`: resolve shop names from the same cached shop read; verified order cards name Terra Grocery, Aurora Digital and Demo Store instead of the placeholder
- [x] 5.5 Moved the pure `lowestSku` helper out of the fixed-data module into `apps/mall/utils/product.ts`, re-exported for the mock-era pages, so the live store and product pages no longer import `~/mock/data` for it. A first attempt used `export { lowestSku } from "~/utils/product"`, which creates no local binding and broke every internal caller at runtime
## 6. Verification
- [ ] 6.1 Run the mall, shop-admin and admin builds, since the shared contract changed; verify all three pass and `cargo test -p vmall-api` stays green
- [ ] 6.2 With the backend seeded, verify in a browser that the store directory lists the demo shops, a store home renders its profile and products, the product page's store card shows a real name, and the cart/payment/order surfaces name the shop; confirm no console errors beyond deliberate failed responses
- [ ] 6.3 Verify the rollback: with every domain on fixed data and the backend stopped, the store directory and store home still render
- [x] 6.1 `cargo test -p vmall-api` green at 28 tests (five new shop tests), and all three frontends build. **Caveat worth recording:** `nuxt build` does not typecheck — there is no `typescript.typeCheck` in `nuxt.config.ts` and no `vue-tsc` installed — so a build passing is not the type gate AGENTS.md describes. The `lowestSku is not defined` bug above passed the build and only failed in the browser, which is how it was found
- [x] 6.2 Verified in a browser: the directory lists the four demo shops with real logos and no distance text, a store home shows its profile and six products with default/price sorts, the product page's store card names Aurora Digital and links to its store, and order cards name their shop. Console showed only the header's signed-out cart 401, once per page load
- [x] 6.3 Verified the rollback: with every domain on fixed data and the backend stopped, the directory renders the four mock stores with their logos and a mock store home renders its profile and products
+8
View File
@@ -17,6 +17,8 @@ import type {
ProductStatus,
Shipment,
Shop,
ShopProfile,
ShopProfileInput,
Sku,
User,
} from "./types";
@@ -165,6 +167,9 @@ export interface ApiClient {
listMyInvoices(): Promise<Invoice[]>;
/** Public home-page marketing content: banners, promos, quick links, floor adverts. */
getHomeContent(): Promise<HomeContent>;
/** Public store directory: active shops with whatever profile they have. */
listShops(): Promise<ShopProfile[]>;
getShop(slug: string): Promise<ShopProfile>;
shop: {
getMyShop(): Promise<Shop>;
listMyProducts(q?: ShopProductQuery): Promise<Paged<Product>>;
@@ -237,6 +242,8 @@ export function createApi(opts: ApiClientOptions): ApiClient {
r("POST", `/orders/${orderId}/invoice`, { title, tax_no: taxNo, kind }),
listMyInvoices: () => r("GET", "/invoices"),
getHomeContent: () => r("GET", "/content/home"),
listShops: () => r("GET", "/shops"),
getShop: (slug) => r("GET", `/shops/${slug}`),
shop: {
getMyShop: () => r("GET", "/shop/profile"),
listMyProducts: (q = {}) => r("GET", "/shop/products", undefined, { ...q }),
@@ -274,6 +281,7 @@ export function createApi(opts: ApiClientOptions): ApiClient {
}),
getContent: () => r("GET", "/admin/content"),
replaceContent: (kind, items) => r("PUT", `/admin/content/${kind}`, items),
setShopProfile: (id, body) => r("PUT", `/admin/shops/${id}/profile`, body),
},
};
}
+35 -1
View File
@@ -234,7 +234,6 @@ export interface HomeContent {
}
export type ContentKind = "banners" | "promos" | "quick-links" | "floor-adverts";
/** Request payload per kind for `replaceContent`; ids and positions are assigned server-side. */
export interface ContentInputByKind {
banners: { image: string; url: string; active?: boolean }[];
@@ -243,3 +242,38 @@ export interface ContentInputByKind {
"floor-adverts": { image: string; active?: boolean }[];
}
// ---- store directory ----
/** A shop plus whatever profile it has; every profile field is optional. */
export interface ShopProfile {
id: string;
slug: string;
name: LocalizedText;
company: string | null;
region: string | null;
address: LocalizedText | null;
logo: string | null;
banner: string | null;
notice: LocalizedText | null;
after_sale: LocalizedText | null;
/** Platform-set profile scores; there is no review model behind them. */
score_rating: number | null;
score_agreement: number | null;
score_service: number | null;
score_speed: number | null;
}
export interface ShopProfileInput {
logo?: string | null;
banner?: string | null;
company?: string | null;
region?: string | null;
address?: LocalizedText | null;
notice?: LocalizedText | null;
after_sale?: LocalizedText | null;
score_rating?: number | null;
score_agreement?: number | null;
score_service?: number | null;
score_speed?: number | null;
}
+60 -1
View File
@@ -42,27 +42,79 @@ let r = await call("POST", "/auth/login", {
if (r.status !== 200) fail("admin login", r);
const admin = r.data.token;
// 2. shops with their own owner accounts
// 2. shops with their own owner accounts and public profiles
const SHOPS = [
{
slug: "demo-store",
name: { en: "Demo Store", zh: "演示店铺" },
owner: { email: "shop@vmall.local", password: "shop12345", displayName: "Demo Owner" },
profile: {
logo: "/mock/store-1.svg",
banner: "/mock/banner-1.svg",
company: "Demo Commerce Co., Ltd.",
region: "California",
address: { en: "1 Market Street, San Francisco", zh: "旧金山市场街 1 号" },
notice: { en: "Free shipping on orders over $99.", zh: "满 99 美元免运费。" },
after_sale: { en: "7-day returns, 1-year warranty.", zh: "支持 7 天退货,一年质保。" },
score_rating: 4.9,
score_agreement: 4.8,
score_service: 4.9,
score_speed: 4.7,
},
},
{
slug: "aurora-digital",
name: { en: "Aurora Digital", zh: "极光数码" },
owner: { email: "aurora@vmall.local", password: "shop12345", displayName: "Aurora Owner" },
profile: {
logo: "/mock/store-2.svg",
banner: "/mock/banner-2.svg",
company: "Aurora Technology Co., Ltd.",
region: "New York",
address: { en: "88 Hudson Yards, New York", zh: "纽约哈德逊城市广场 88 号" },
notice: { en: "Same-day dispatch before 3 PM.", zh: "下午 3 点前下单当天发货。" },
after_sale: { en: "Nationwide warranty, support 9:00-21:00.", zh: "全国联保,客服 9:00-21:00。" },
score_rating: 4.7,
score_agreement: 4.6,
score_service: 4.8,
score_speed: 4.6,
},
},
{
slug: "nordwind-home",
name: { en: "Nordwind Home", zh: "北风家居" },
owner: { email: "nordwind@vmall.local", password: "shop12345", displayName: "Nordwind Owner" },
profile: {
logo: "/mock/store-3.svg",
banner: "/mock/banner-3.svg",
company: "Nordwind Trading LLC",
region: "Texas",
address: { en: "1200 Congress Avenue, Austin", zh: "奥斯汀国会大道 1200 号" },
notice: { en: "Free installation on large appliances.", zh: "大家电免费上门安装。" },
after_sale: { en: "30-day returns on unopened goods.", zh: "未拆封商品 30 天可退。" },
score_rating: 4.8,
score_agreement: 4.7,
score_service: 4.6,
score_speed: 4.8,
},
},
{
slug: "terra-grocery",
name: { en: "Terra Grocery", zh: "大地生鲜" },
owner: { email: "terra@vmall.local", password: "shop12345", displayName: "Terra Owner" },
profile: {
logo: "/mock/store-4.svg",
banner: "/mock/promo-1.svg",
company: "Terra Foods Inc.",
region: "Oregon",
address: { en: "45 Willamette Loop, Portland", zh: "波特兰威拉米特环路 45 号" },
notice: { en: "Cold-chain delivery, next-day slots.", zh: "全程冷链,次日达时段可选。" },
after_sale: { en: "Fresh items refunded on delivery issues.", zh: "生鲜配送问题可直接退款。" },
score_rating: 4.6,
score_agreement: 4.5,
score_service: 4.7,
score_speed: 4.5,
},
},
];
@@ -79,6 +131,13 @@ async function ensureShop(def) {
shopId = shops.data.find((s) => s.slug === def.slug).id;
} else fail(`create shop ${def.slug}`, r);
// Upsert, so re-running the seed refreshes the profile rather than failing.
r = await call("PUT", `/admin/shops/${shopId}/profile`, {
token: admin,
body: def.profile,
});
if (r.status !== 200) fail(`shop profile ${def.slug}`, r);
await call("POST", "/auth/register", {
body: {
email: def.owner.email,