From 357f27163953039a67bc4adc309a74fe739e7fc5 Mon Sep 17 00:00:00 2001 From: que01 Date: Mon, 12 Oct 2026 03:37:05 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=20API=20Client?= =?UTF-8?q?=20=E8=B5=84=E6=BA=90=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/api-client/src/client/request.ts | 59 + packages/api-client/src/index.ts | 1177 ++++------------- packages/api-client/src/resources/booking.ts | 55 + packages/api-client/src/resources/brand.ts | 98 ++ packages/api-client/src/resources/inquiry.ts | 58 + packages/api-client/src/resources/media.ts | 18 + packages/api-client/src/resources/offering.ts | 32 + packages/api-client/src/resources/public.ts | 38 + packages/api-client/src/resources/session.ts | 26 + packages/api-client/src/resources/template.ts | 150 +++ packages/api-client/src/resources/trust.ts | 26 + packages/api-client/src/types/booking.ts | 51 + packages/api-client/src/types/brand.ts | 56 + packages/api-client/src/types/capability.ts | 9 + packages/api-client/src/types/common.ts | 5 + packages/api-client/src/types/field.ts | 11 + packages/api-client/src/types/inquiry.ts | 30 + packages/api-client/src/types/media.ts | 11 + packages/api-client/src/types/offering.ts | 52 + .../src/types/template-definition.ts | 27 + packages/api-client/src/types/template.ts | 80 ++ packages/api-client/src/types/trust.ts | 22 + packages/api-client/src/types/workspace.ts | 76 ++ packages/api-client/test/exports.test.ts | 18 + 24 files changed, 1280 insertions(+), 905 deletions(-) create mode 100644 packages/api-client/src/client/request.ts create mode 100644 packages/api-client/src/resources/booking.ts create mode 100644 packages/api-client/src/resources/brand.ts create mode 100644 packages/api-client/src/resources/inquiry.ts create mode 100644 packages/api-client/src/resources/media.ts create mode 100644 packages/api-client/src/resources/offering.ts create mode 100644 packages/api-client/src/resources/public.ts create mode 100644 packages/api-client/src/resources/session.ts create mode 100644 packages/api-client/src/resources/template.ts create mode 100644 packages/api-client/src/resources/trust.ts create mode 100644 packages/api-client/src/types/booking.ts create mode 100644 packages/api-client/src/types/brand.ts create mode 100644 packages/api-client/src/types/capability.ts create mode 100644 packages/api-client/src/types/common.ts create mode 100644 packages/api-client/src/types/field.ts create mode 100644 packages/api-client/src/types/inquiry.ts create mode 100644 packages/api-client/src/types/media.ts create mode 100644 packages/api-client/src/types/offering.ts create mode 100644 packages/api-client/src/types/template-definition.ts create mode 100644 packages/api-client/src/types/template.ts create mode 100644 packages/api-client/src/types/trust.ts create mode 100644 packages/api-client/src/types/workspace.ts create mode 100644 packages/api-client/test/exports.test.ts diff --git a/packages/api-client/src/client/request.ts b/packages/api-client/src/client/request.ts new file mode 100644 index 0000000..bc2bf51 --- /dev/null +++ b/packages/api-client/src/client/request.ts @@ -0,0 +1,59 @@ +import type { ApiErrorBody } from "../types/common.js"; + +export interface FetchResponse { + readonly status: number; + readonly ok: boolean; + json(): Promise; +} + +export type FetchLike = ( + input: string, + init?: { method?: string; headers?: Record; body?: string }, +) => Promise; + +export interface ApiClientOptions { + baseUrl: string; + fetcher: FetchLike; + token?: string; +} + +export type RequestFn = ( + path: string, + options?: { method?: string; body?: unknown }, +) => Promise; + +export async function request( + state: { baseUrl: string; fetcher: FetchLike; token?: string | undefined }, + path: string, + options: { method?: string; body?: unknown } = {}, +): Promise { + const headers: Record = { accept: "application/json" }; + if (options.body !== undefined) headers["content-type"] = "application/json"; + if (state.token) headers.authorization = `Bearer ${state.token}`; + const response = await state.fetcher(`${state.baseUrl}${path}`, { + method: options.method ?? "GET", + headers, + ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }), + }); + const body = await response.json(); + if (!response.ok) throw new ApiClientError(response.status, body as ApiErrorBody); + return body as T; +} + +export class ApiClientError extends Error { + constructor( + readonly status: number, + readonly body: ApiErrorBody, + ) { + super(body.error.message); + this.name = "ApiClientError"; + } + + get code(): string { + return this.body.error.code; + } + + get requestId(): string | null { + return this.body.requestId; + } +} diff --git a/packages/api-client/src/index.ts b/packages/api-client/src/index.ts index ccafa17..0325d48 100644 --- a/packages/api-client/src/index.ts +++ b/packages/api-client/src/index.ts @@ -1,914 +1,281 @@ -import type { - BookingRequestType, - BookingStatus, - ContactPreference, - FulfillmentType, - PublicOffering, - BrandTemplateKey, - RuntimeCapability, - RuntimeInquiryForm, - RuntimeOffering, - RuntimeWorkspace, - RuntimeTrustItem, - ThemeManifest, -} from "@personal-brand/types"; +export { ApiClientError } from "./client/request.js"; +export type { ApiClientOptions, FetchLike, FetchResponse, RequestFn } from "./client/request.js"; +export type { + AdminBooking, + Booking, + BookingItemInput, + BookingSummary, + BookingTag, + CreateBookingInput, +} from "./types/booking.js"; +export type { + AdminBrandMember, + AdminBrandMembership, + BrandPresentationUpdate, + BrandProfile, + BrandReleaseSummary, + BrandUpdate, +} from "./types/brand.js"; +export type { CapabilityInstallation } from "./types/capability.js"; +export type { ApiErrorBody } from "./types/common.js"; +export type { BrandFieldDefinition } from "./types/field.js"; +export type { InquiryForm, InquirySubmission } from "./types/inquiry.js"; +export type { PresignedUpload, UploadConfig } from "./types/media.js"; +export type { + Offering, + OfferingCta, + OfferingMedia, + OfferingSection, + OfferingUpdate, +} from "./types/offering.js"; +export type { BrandTemplateDefinition } from "./types/template-definition.js"; +export type { + AdminTemplateContent, + TemplateAdminField, + TemplateAdminSection, +} from "./types/template.js"; +export type { TrustContent, TrustContentInput } from "./types/trust.js"; +export type { PublicWorkspace } from "./types/workspace.js"; export { projectBrandAliases, projectTrustPresentation } from "@personal-brand/types"; -export type { PublicOffering } from "@personal-brand/types"; -export type { BookingStatus } from "@personal-brand/types"; -export type { BrandTemplateKey } from "@personal-brand/types"; +export type { PublicOffering, BookingStatus, BrandTemplateKey } from "@personal-brand/types"; export type { EditorPreviewFrameMessage, EditorPreviewHostMessage, RuntimeWorkspace, } from "@personal-brand/types"; - -export interface BrandProfile { - id: string; - slug?: string; - name: string; - templateKey: BrandTemplateKey; - tagline: string | null; - description: string | null; - avatarUrl: string | null; - coverUrl: string | null; - hours: string | null; - address: string | null; - deliveryNote: string | null; - contactPhone: string | null; - contactWechat: string | null; - config?: Record | null; -} -export interface AdminBrandMembership { - id: string; - role: string; - brand: Pick & { slug?: string }; -} -export interface AdminBrandMember { - id: string; - role: string; - isEnabled: boolean; - adminUser: { - id: string; - username: string; - displayName: string; - isEnabled: boolean; - }; -} - -export interface UploadConfig { - configured: boolean; - status: "ok" | "unavailable" | "unconfigured"; - bucket?: string; -} - -export interface PresignedUpload { - uploadUrl: string; - key: string; - publicUrl: string; -} -export type BrandUpdate = Partial>; -export interface BrandReleaseSummary { - id: string; - version: number; - status: string; - note: string | null; - actorId: string; - createdAt: string; - revokedAt: string | null; - revokedBy?: string | null; -} -export type BrandPresentationUpdate = Partial< - Record< - "identity" | "home" | "offerings" | "detail" | "profile" | "inquiry" | "success" | "records", - Record - > ->; - -export interface TemplateAdminField { - key: string; - page?: string; - binding: string; - label: string; - help?: string; - input: - | "text" - | "textarea" - | "phone" - | "image" - | "number" - | "boolean" - | "select" - | "multi-select" - | "list"; - itemFields?: Array<{ - key: string; - label: string; - input?: "text" | "textarea"; - required?: boolean; - }>; - itemValueKey?: string; - required?: boolean; - maxLength?: number; - placeholder?: string; - options?: Array<{ value: string; label: string }>; - previewTarget?: string; -} - -export interface TemplateAdminSection { - key: string; - title: string; - description: string; - page: string; - target: "brand" | "offering" | "trust" | "inquiry"; - previewTargets?: Array<{ - key: string; - label: string; - composite?: boolean; - children?: string[]; - }>; - fields: TemplateAdminField[]; -} - -export interface AdminTemplateContent { - displayName: string; - admin: { sections: TemplateAdminSection[] }; - navigation: Array<{ key: string; label: string; page: string }>; - templateFields?: TemplateAdminField[]; - trustContentTypes?: Array<{ - type: string; - label: string; - adminFields: { - title: string; - summary: string; - content: string; - summaryHelp?: string; - summaryPlaceholder?: string; - }; - pages?: string[]; - help?: string; - placeholder?: string; - required?: boolean; - configFields?: TemplateAdminField[]; - previewTargets?: Array<{ key: string; label: string; page?: string }>; - maxPublishedItems?: number; - hideStandardFields?: Array<"summary" | "content">; - }>; - assetSlots: Array<{ - key: string; - binding: string; - target: "brand" | "offering" | "trust"; - label: string; - help: string; - required: boolean; - kind: "image" | "logo" | "portrait" | "texture"; - aspectRatio?: string; - }>; -} -export interface OfferingUpdate { - name?: string; - description?: string; - coverUrl?: string; - priceText?: string; - priceAmount?: number; - sortOrder?: number; - bookingEnabled?: boolean; - isEnabled?: boolean; - categoryKey?: string; - config?: Record; -} -export interface TrustContent { - id: string; - type: string; - title: string; - summary?: string | null; - content: string; - coverUrl?: string | null; - sortOrder: number; - isPublished: boolean; - config?: Record | null; -} -export interface TrustContentInput { - type: string; - title: string; - summary?: string; - content: string; - coverUrl?: string; - sortOrder?: number; - isPublished?: boolean; - config?: Record; -} - -export interface BookingItemInput { - offeringId: string; - quantity: number; -} -export interface CreateBookingInput { - requestType: BookingRequestType; - customerName: string; - phone?: string; - wechatId?: string; - contactPreference: ContactPreference; - fulfillmentType?: FulfillmentType; - offeringId?: string; - requestedDate?: string; - requestedTime?: string; - deliveryAddress?: string; - note?: string; - extraData?: Record; - items: BookingItemInput[]; -} -export interface BookingSummary { - bookingNo: string; - status: BookingStatus; - estimatedAmount: number | null; - createdAt: string; -} -export interface Booking extends BookingSummary { - id: string; - customerName: string; - adminNote?: string | null; -} -export interface BookingTag { - id: string; - name: string; - isPreset: boolean; - isEnabled: boolean; -} -export interface AdminBooking extends Booking { - tags?: Array<{ tag: BookingTag }>; -} -export interface ApiErrorBody { - data: null; - error: { code: string; message: string }; - requestId: string | null; -} -export interface BrandTemplateDefinition { - key: "personal" | "food" | "doors"; - version: string; - name: string; - description: string; - serviceCategories: string[]; - trustContentTypes: string[]; - modules: Array<{ - key: string; - type: string; - title: string; - required: boolean; - }>; - fields: Array<{ - scope: string; - key: string; - label: string; - type: string; - required: boolean; - }>; - capabilities: string[]; - runtimeCapabilities: Array<{ - key: string; - version: string; - workflowKey?: string; - }>; -} -export interface OfferingSection { - type: "text" | "image-list" | "timeline" | "faq"; - title: string; - content?: string; - items?: unknown[]; -} -export interface OfferingMedia { - url: string; - alt?: string; - type?: "image" | "video"; -} -export interface OfferingCta { - type: "inquiry" | "booking" | "contact" | "external-link"; - label: string; - config?: Record; -} -export interface BrandFieldDefinition { - id: string; - scope: string; - key: string; - label: string; - type: string; - required: boolean; - isVisible: boolean; - sortOrder: number; - source: string; -} -export interface InquiryForm { - id: string; - name: string; - offeringId?: string | null; - version: number; - isEnabled: boolean; - fieldsSnapshot: unknown[]; - purpose: "inquiry" | "booking" | "quote-request"; - targetType: "brand" | "offering"; - submissionAction: "create-inquiry" | "create-booking" | "create-quote"; -} -export interface InquirySubmission { - id: string; - inquiryFormId: string; - formVersion: number; - fieldsSnapshot: unknown[]; - values: Record; - activeFields: Record; - createdAt: string; - status: "new" | "reviewing" | "replied" | "qualified" | "converted" | "closed"; - adminNote?: string | null; - inquiryForm?: { name: string }; - offering?: { id: string; name: string } | null; - statusHistory?: Array<{ - fromStatus?: string | null; - toStatus: string; - createdAt: string; - }>; -} -export interface CapabilityInstallation { - id: string | null; - capabilityKey: string; - capabilityVersion: string; - status: "enabled" | "disabled" | "degraded"; - config?: Record | null; - updatedAt: string | null; - source?: "template" | "brand"; -} -export interface PublicWorkspace { - schemaVersion: string; - contractVersion: string; - publication: { - status: "published" | "unpublished"; - version: number | null; - publishedAt?: string; - }; - brand: (BrandProfile & Record) | null; - template: { key: BrandTemplateKey; version: string; name: string } | null; - visualTemplate: { - key: string; - version: string; - name: string; - supportedIndustryTemplates: BrandTemplateKey[]; - variants: Record; - } | null; - visualTemplateManifest?: { - schemaVersion: "1.0"; - key: string; - version: string; - name: string; - brandFirst: true; - tokens: { - colors: Record; - spacing: Record; - typography: Record; - radius: Record; - shadows?: Record; - }; - pages: Array<{ - key: string; - title: string; - modules: Array<{ - key: string; - type: string; - variant: string; - required: boolean; - dataSlots?: string[]; - assetSlots?: string[]; - capability?: string; - }>; - }>; - assets: Array>; - dataSlots: Array>; - capabilities: string[]; - }; - capabilities: RuntimeCapability[]; - offerings: RuntimeOffering[]; - inquiryForms: RuntimeInquiryForm[]; - trustItems: RuntimeTrustItem[]; - navigation: { tabs: Array<{ key: string; label: string; page: string }> }; - trustPresentation: Record; - theme: ThemeManifest; - layout?: { home: string[]; offerings: string[]; detail: string[]; profile: string[] }; - plugins?: Array<{ - key: string; - version: string; - displayName: string; - purpose: string; - requiredModules: string[]; - apiContract: string; - configSchema: string; - status: string; - }>; -} -export interface Offering { - id: string; - brandId?: string; - kind: "service" | "product" | "package" | "subscription"; - name: string; - summary?: string | null; - description?: string | null; - coverUrl?: string | null; - priceText?: string | null; - priceAmount?: number | null; - isEnabled: boolean; - sortOrder: number; - config?: Record | null; - sections?: OfferingSection[]; - media?: OfferingMedia[]; - cta?: OfferingCta; - inquiryForms?: Array>; -} - -export class ApiClientError extends Error { - constructor( - readonly status: number, - readonly body: ApiErrorBody, - ) { - super(body.error.message); - this.name = "ApiClientError"; - } - get code(): string { - return this.body.error.code; - } - get requestId(): string | null { - return this.body.requestId; - } -} - -export interface FetchResponse { - readonly status: number; - readonly ok: boolean; - json(): Promise; -} -export type FetchLike = ( - input: string, - init?: { method?: string; headers?: Record; body?: string }, -) => Promise; -export interface ApiClientOptions { - baseUrl: string; - fetcher: FetchLike; - token?: string; -} - -export class ApiClient { - private readonly baseUrl: string; - private readonly fetcher: FetchLike; - private token: string | undefined; - - constructor(options: ApiClientOptions) { - this.baseUrl = options.baseUrl.replace(/\/$/, ""); - this.fetcher = options.fetcher; - this.token = options.token; - } - setToken(token: string | undefined): void { - this.token = token; - } - getBrand(): Promise { - return this.request("/public/brand"); - } - listOfferings(): Promise { - return this.request("/public/offerings"); - } - getPublicWorkspace(): Promise { - return this.request("/public/workspace"); - } - getPublicInquiryForm(id: string): Promise { - return this.request(`/public/inquiry-forms/${encodeURIComponent(id)}`); - } - createCustomerInquirySubmission( - formId: string, - values: Record, - ): Promise { - return this.request("/customer/inquiry-submissions", { - method: "POST", - body: { formId, values }, - }); - } - listCustomerInquirySubmissions(): Promise { - return this.request("/customer/inquiry-submissions"); - } - getCustomerInquirySubmission(id: string): Promise { - return this.request(`/customer/inquiry-submissions/${encodeURIComponent(id)}`); - } - createCustomerSession(code: string): Promise<{ token: string }> { - return this.request("/customer/session/wechat", { method: "POST", body: { code } }); - } - listCustomerBookings(): Promise { - return this.request("/customer/bookings"); - } - createCustomerBooking(input: CreateBookingInput): Promise { - return this.request("/customer/bookings", { method: "POST", body: input }); - } - cancelCustomerBooking(id: string): Promise { - return this.request(`/customer/bookings/${encodeURIComponent(id)}/cancel`, { method: "POST" }); - } - loginAdmin( - username: string, - password: string, - ): Promise<{ - token: string; - displayName: string; - mustChangePassword: boolean; - role: string; - }> { - return this.request("/admin/session/login", { method: "POST", body: { username, password } }); - } - changeAdminPassword(currentPassword: string, newPassword: string): Promise<{ changed: true }> { - return this.request("/admin/session/change-password", { - method: "POST", - body: { currentPassword, newPassword }, - }); - } - listAdminBookings( - filters: { status?: BookingStatus; unreadOnly?: boolean; tagId?: string } = {}, - ): Promise { - const params: string[] = []; - if (filters.status) params.push(`status=${encodeURIComponent(filters.status)}`); - if (filters.unreadOnly !== undefined) params.push(`unreadOnly=${filters.unreadOnly}`); - if (filters.tagId) params.push(`tagId=${encodeURIComponent(filters.tagId)}`); - const query = params.join("&"); - return this.request(`/admin/bookings${query ? `?${query}` : ""}`); - } - getAdminBooking(id: string): Promise { - return this.request(`/admin/bookings/${encodeURIComponent(id)}`); - } - getAdminUnreadCount(): Promise<{ count: number }> { - return this.request("/admin/bookings/unread-count"); - } - updateAdminBookingStatus( - id: string, - status: BookingStatus, - adminNote?: string, - ): Promise { - return this.request(`/admin/bookings/${encodeURIComponent(id)}/status`, { - method: "POST", - body: { status, ...(adminNote === undefined ? {} : { adminNote }) }, - }); - } - markAdminBookingRead(id: string): Promise { - return this.request(`/admin/bookings/${encodeURIComponent(id)}/read`, { method: "POST" }); - } - listAdminTags(): Promise { - return this.request("/admin/bookings/tags"); - } - createAdminTag(name: string): Promise { - return this.request("/admin/bookings/tags", { method: "POST", body: { name } }); - } - getAdminBrand(): Promise { - return this.request("/admin/config/brand"); - } - listAdminBrands(): Promise { - return this.request("/admin/brands"); - } - switchAdminBrand( - brandId: string, - ): Promise<{ token: string; brand: AdminBrandMembership["brand"] }> { - return this.request(`/admin/brands/${encodeURIComponent(brandId)}/switch`, { method: "POST" }); - } - listAdminMembers(): Promise { - return this.request("/admin/brands/members"); - } - createAdminMember(body: { - username: string; - displayName: string; - password: string; - role: "owner" | "editor"; - }): Promise { - return this.request("/admin/brands/members", { method: "POST", body }); - } - updateAdminMember( - id: string, - body: Partial>, - ): Promise { - return this.request(`/admin/brands/members/${encodeURIComponent(id)}`, { - method: "PATCH", - body, - }); - } - getAdminVisualTemplatePreview(): Promise<{ - current: { - key: string; - version: string; - name: string; - theme: { colors: Record }; - variants: Record; - } | null; - available: string[]; - }> { - return this.request("/admin/config/visual-template/preview"); - } - getAdminVisualTemplateHistory(): Promise<{ - history: Array<{ visualTemplateKey: string; savedAt: string }>; - }> { - return this.request("/admin/config/visual-template/history"); - } - rollbackAdminVisualTemplate(): Promise<{ visualTemplateKey: string; rolledBack: boolean }> { - return this.request("/admin/config/visual-template/rollback", { method: "POST" }); - } - updateAdminBrand(body: BrandUpdate): Promise { - return this.request("/admin/config/brand", { method: "PATCH", body }); - } - updateAdminBrandPresentation(body: BrandPresentationUpdate): Promise<{ - visualPresentation: Record>; - }> { - return this.request("/admin/config/presentation", { method: "PATCH", body }); - } - getPublicTemplate(key: BrandTemplateKey): Promise { - return this.request(`/public/templates/${key}`); - } - listPublicTemplates(): Promise<{ - industries: BrandTemplateDefinition[]; - visuals: Array<{ - key: string; - version: string; - name: string; - description: string; - supportedIndustryTemplates: BrandTemplateKey[]; - variants: Record; - theme: { colors: Record }; - }>; - }> { - return this.request<{ - industries: BrandTemplateDefinition[]; - visuals: Array<{ - key: string; - version: string; - name: string; - description: string; - supportedIndustryTemplates?: unknown; - variants?: unknown; - theme?: unknown; - }>; - }>("/public/templates").then((catalog) => ({ - industries: Array.isArray(catalog.industries) ? catalog.industries : [], - visuals: Array.isArray(catalog.visuals) - ? catalog.visuals.map((visual) => ({ - key: String(visual.key ?? ""), - version: String(visual.version ?? ""), - name: String(visual.name ?? "未命名视觉模板"), - description: String(visual.description ?? ""), - supportedIndustryTemplates: Array.isArray(visual.supportedIndustryTemplates) - ? visual.supportedIndustryTemplates.filter( - (item): item is BrandTemplateKey => - item === "personal" || item === "food" || item === "doors", - ) - : [], - variants: - visual.variants && typeof visual.variants === "object" - ? (visual.variants as Record) - : {}, - theme: - visual.theme && typeof visual.theme === "object" - ? (visual.theme as { colors: Record }) - : { colors: {} }, - })) - : [], - })); - } - previewPublicTemplateCombination( - industry: string, - visual: string, - ): Promise<{ - industry: BrandTemplateDefinition; - visual: { - key: string; - version: string; - name: string; - description: string; - supportedIndustryTemplates: BrandTemplateKey[]; - variants: Record; - theme: { colors: Record }; - }; - runtime: { - schemaVersion: string; - capabilities: Array<{ key: string; version: string }>; - theme: unknown; - }; - }> { - return this.request( - `/public/templates/preview?industry=${encodeURIComponent(industry)}&visual=${encodeURIComponent(visual)}`, - ); - } - getPublicOffering(id: string): Promise { - return this.request(`/public/offerings/${encodeURIComponent(id)}`); - } - listPublicOfferings(): Promise { - return this.request("/public/offerings"); - } - getAdminWorkspace(): Promise<{ - brand: BrandProfile; - visualTemplate?: { - key: string; - version: string; - name: string; - supportedIndustryTemplates: BrandTemplateKey[]; - variants: Record; - } | null; - installations: Array<{ id: string; templateKey: BrandTemplateKey; templateVersion: string }>; - fields: BrandFieldDefinition[]; - offerings: Offering[]; - forms: unknown[]; - templateContent: AdminTemplateContent | null; - }> { - return this.request("/admin/workspace"); - } - getAdminPreviewWorkspace(): Promise { - return this.request("/admin/workspace/preview"); - } - listAdminReleases(): Promise { - return this.request("/admin/releases"); - } - getAdminReleaseReadiness(): Promise<{ - ready: boolean; - checks: Array<{ - key: string; - label: string; - passed: boolean; - help?: string; - destination?: string; - }>; - }> { - return this.request("/admin/releases/readiness"); - } - publishAdminRelease(note?: string): Promise { - return this.request("/admin/releases/publish", { - method: "POST", - body: note === undefined ? {} : { note }, - }); - } - rollbackAdminRelease(version: number, note?: string): Promise { - return this.request(`/admin/releases/${version}/rollback`, { - method: "POST", - body: note === undefined ? {} : { note }, - }); - } - revokeAdminRelease(): Promise< - Pick - > { - return this.request("/admin/releases/revoke", { method: "POST" }); - } - installAdminTemplate(templateKey: "personal" | "food" | "doors"): Promise { - return this.request("/admin/workspace/install", { method: "POST", body: { templateKey } }); - } - listAdminCapabilities(): Promise { - return this.request("/admin/workspace/capabilities"); - } - updateAdminCapability( - key: string, - body: { - capabilityVersion: string; - status: CapabilityInstallation["status"]; - config?: Record; - }, - ): Promise { - return this.request(`/admin/workspace/capabilities/${encodeURIComponent(key)}`, { - method: "PATCH", - body, - }); - } - previewAdminSampleContent(): Promise<{ - templateKey: string; - alreadyImported: boolean; - counts: Record; - willCreateInquiryForm: boolean; - }> { - return this.request("/admin/workspace/sample-content/preview"); - } - importAdminSampleContent(): Promise<{ imported: boolean; counts: Record }> { - return this.request("/admin/workspace/sample-content/import", { method: "POST" }); - } - getAdminTemplateUpgradePreview(): Promise<{ - currentVersion: string; - latestVersion: string; - canUpgrade: boolean; - canRollback: boolean; - missingModules: unknown[]; - missingFields: unknown[]; - }> { - return this.request("/admin/workspace/template/preview"); - } - upgradeAdminTemplate(): Promise { - return this.request("/admin/workspace/template/upgrade", { method: "POST" }); - } - rollbackAdminTemplate(): Promise { - return this.request("/admin/workspace/template/rollback", { method: "POST" }); - } - createAdminField( - body: Omit, - ): Promise { - return this.request("/admin/workspace/fields", { method: "POST", body }); - } - deleteAdminField(id: string): Promise<{ deleted: boolean }> { - return this.request(`/admin/workspace/fields/${encodeURIComponent(id)}`, { method: "DELETE" }); - } - listAdminInquiryForms(): Promise { - return this.request("/admin/workspace/forms"); - } - listAdminInquirySubmissions(): Promise { - return this.request("/admin/workspace/submissions"); - } - updateAdminInquirySubmission( - id: string, - body: { status: InquirySubmission["status"]; adminNote?: string }, - ): Promise { - return this.request(`/admin/workspace/submissions/${encodeURIComponent(id)}`, { - method: "PATCH", - body, - }); - } - createAdminInquiryForm(body: { - name: string; - offeringId?: string; - fieldsSnapshot: unknown[]; - isEnabled?: boolean; - purpose?: InquiryForm["purpose"]; - targetType?: InquiryForm["targetType"]; - submissionAction?: InquiryForm["submissionAction"]; - }): Promise { - return this.request("/admin/workspace/forms", { method: "POST", body }); - } - updateAdminInquiryForm( - id: string, - body: Partial<{ - name: string; - offeringId: string; - fieldsSnapshot: unknown[]; - isEnabled: boolean; - purpose?: InquiryForm["purpose"]; - targetType?: InquiryForm["targetType"]; - submissionAction?: InquiryForm["submissionAction"]; - }>, - ): Promise { - return this.request(`/admin/workspace/forms/${encodeURIComponent(id)}`, { - method: "PATCH", - body, - }); - } - listAdminOfferings(): Promise { - return this.request("/admin/workspace/offerings"); - } - createAdminOffering(body: Omit): Promise { - return this.request("/admin/workspace/offerings", { method: "POST", body }); - } - updateAdminOffering( - id: string, - body: Partial>, - ): Promise { - return this.request(`/admin/workspace/offerings/${encodeURIComponent(id)}`, { - method: "PATCH", - body, - }); - } - deleteAdminOffering(id: string): Promise<{ deleted: boolean }> { - return this.request(`/admin/workspace/offerings/${encodeURIComponent(id)}`, { - method: "DELETE", - }); - } - listAdminTrustContent(): Promise { - return this.request("/admin/config/trust-content"); - } - createAdminTrustContent(body: TrustContentInput): Promise { - return this.request("/admin/config/trust-content", { method: "POST", body }); - } - updateAdminTrustContent(id: string, body: Partial): Promise { - return this.request(`/admin/config/trust-content/${encodeURIComponent(id)}`, { - method: "PATCH", - body, - }); - } - deleteAdminTrustContent(id: string): Promise<{ deleted: boolean }> { - return this.request(`/admin/config/trust-content/${encodeURIComponent(id)}`, { - method: "DELETE", - }); - } - getUploadConfig(): Promise { - return this.request("/admin/uploads/config"); - } - createPresignedUpload(body: { - fileName: string; - contentType: string; - scope?: "brand" | "offering" | "trust"; - }): Promise { - return this.request("/admin/uploads/presign", { method: "POST", body }); - } - private async request( - path: string, - options: { method?: string; body?: unknown } = {}, - ): Promise { - const headers: Record = { accept: "application/json" }; - if (options.body !== undefined) headers["content-type"] = "application/json"; - if (this.token) headers.authorization = `Bearer ${this.token}`; - const response = await this.fetcher(`${this.baseUrl}${path}`, { - method: options.method ?? "GET", - headers, - ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }), - }); - const body = await response.json(); - if (!response.ok) throw new ApiClientError(response.status, body as ApiErrorBody); - return body as T; - } -} +export { isTrustContentComplete } from "@personal-brand/types"; export const apiClientName = "personal-brand-api-client"; -export { isTrustContentComplete } from "@personal-brand/types"; +import { bookingMethods } from "./resources/booking.js"; +import { brandMethods } from "./resources/brand.js"; +import { request as createRequest, type ApiClientOptions } from "./client/request.js"; +import { inquiryMethods } from "./resources/inquiry.js"; +import { mediaMethods } from "./resources/media.js"; +import { offeringMethods } from "./resources/offering.js"; +import { publicMethods } from "./resources/public.js"; +import { sessionMethods } from "./resources/session.js"; +import { templateMethods } from "./resources/template.js"; +import { trustMethods } from "./resources/trust.js"; +import type { BookingMethods } from "./resources/booking.js"; +import type { BrandMethods } from "./resources/brand.js"; +import type { InquiryMethods } from "./resources/inquiry.js"; +import type { MediaMethods } from "./resources/media.js"; +import type { OfferingMethods } from "./resources/offering.js"; +import type { PublicMethods } from "./resources/public.js"; +import type { SessionMethods } from "./resources/session.js"; +import type { TemplateMethods } from "./resources/template.js"; +import type { TrustMethods } from "./resources/trust.js"; + +type ClientState = { + baseUrl: string; + fetcher: ApiClientOptions["fetcher"]; + token?: string | undefined; +}; + +export class ApiClient + implements + BookingMethods, + BrandMethods, + InquiryMethods, + MediaMethods, + OfferingMethods, + PublicMethods, + SessionMethods, + TemplateMethods, + TrustMethods +{ + private readonly state: ClientState; + private readonly requestFn: ( + path: string, + options?: { method?: string; body?: unknown }, + ) => Promise; + private resources!: { + booking: BookingMethods; + brand: BrandMethods; + inquiry: InquiryMethods; + media: MediaMethods; + offering: OfferingMethods; + public: PublicMethods; + session: SessionMethods; + template: TemplateMethods; + trust: TrustMethods; + }; + + constructor(options: ApiClientOptions) { + this.state = { + baseUrl: options.baseUrl.replace(/\/$/, ""), + fetcher: options.fetcher, + token: options.token, + }; + this.requestFn = (path, methodOptions) => createRequest(this.state, path, methodOptions); + this.resources = { + booking: bookingMethods({ request: this.requestFn }), + brand: brandMethods({ request: this.requestFn }), + inquiry: inquiryMethods({ request: this.requestFn }), + media: mediaMethods({ request: this.requestFn }), + offering: offeringMethods({ request: this.requestFn }), + public: publicMethods({ request: this.requestFn }), + session: sessionMethods({ request: this.requestFn }), + template: templateMethods({ request: this.requestFn }), + trust: trustMethods({ request: this.requestFn }), + }; + } + + setToken(token: string | undefined): void { + this.state.token = token; + } + + getBrand = (...arguments_: Parameters) => + this.resources.public.getBrand(...arguments_); + listOfferings = (...arguments_: Parameters) => + this.resources.public.listOfferings(...arguments_); + getPublicWorkspace = (...arguments_: Parameters) => + this.resources.public.getPublicWorkspace(...arguments_); + getPublicInquiryForm = (...arguments_: Parameters) => + this.resources.public.getPublicInquiryForm(...arguments_); + createCustomerInquirySubmission = ( + ...arguments_: Parameters + ) => this.resources.public.createCustomerInquirySubmission(...arguments_); + listCustomerInquirySubmissions = ( + ...arguments_: Parameters + ) => this.resources.public.listCustomerInquirySubmissions(...arguments_); + getCustomerInquirySubmission = ( + ...arguments_: Parameters + ) => this.resources.public.getCustomerInquirySubmission(...arguments_); + createCustomerSession = (...arguments_: Parameters) => + this.resources.public.createCustomerSession(...arguments_); + loginAdmin = (...arguments_: Parameters) => + this.resources.session.loginAdmin(...arguments_); + changeAdminPassword = (...arguments_: Parameters) => + this.resources.session.changeAdminPassword(...arguments_); + listCustomerBookings = (...arguments_: Parameters) => + this.resources.booking.listCustomerBookings(...arguments_); + createCustomerBooking = (...arguments_: Parameters) => + this.resources.booking.createCustomerBooking(...arguments_); + cancelCustomerBooking = (...arguments_: Parameters) => + this.resources.booking.cancelCustomerBooking(...arguments_); + listAdminBookings = (...arguments_: Parameters) => + this.resources.booking.listAdminBookings(...arguments_); + getAdminBooking = (...arguments_: Parameters) => + this.resources.booking.getAdminBooking(...arguments_); + getAdminUnreadCount = (...arguments_: Parameters) => + this.resources.booking.getAdminUnreadCount(...arguments_); + updateAdminBookingStatus = ( + ...arguments_: Parameters + ) => this.resources.booking.updateAdminBookingStatus(...arguments_); + markAdminBookingRead = (...arguments_: Parameters) => + this.resources.booking.markAdminBookingRead(...arguments_); + listAdminTags = (...arguments_: Parameters) => + this.resources.booking.listAdminTags(...arguments_); + createAdminTag = (...arguments_: Parameters) => + this.resources.booking.createAdminTag(...arguments_); + getAdminBrand = (...arguments_: Parameters) => + this.resources.brand.getAdminBrand(...arguments_); + listAdminBrands = (...arguments_: Parameters) => + this.resources.brand.listAdminBrands(...arguments_); + switchAdminBrand = (...arguments_: Parameters) => + this.resources.brand.switchAdminBrand(...arguments_); + listAdminMembers = (...arguments_: Parameters) => + this.resources.brand.listAdminMembers(...arguments_); + createAdminMember = (...arguments_: Parameters) => + this.resources.brand.createAdminMember(...arguments_); + updateAdminMember = (...arguments_: Parameters) => + this.resources.brand.updateAdminMember(...arguments_); + getAdminVisualTemplatePreview = ( + ...arguments_: Parameters + ) => this.resources.brand.getAdminVisualTemplatePreview(...arguments_); + getAdminVisualTemplateHistory = ( + ...arguments_: Parameters + ) => this.resources.brand.getAdminVisualTemplateHistory(...arguments_); + rollbackAdminVisualTemplate = ( + ...arguments_: Parameters + ) => this.resources.brand.rollbackAdminVisualTemplate(...arguments_); + updateAdminBrand = (...arguments_: Parameters) => + this.resources.brand.updateAdminBrand(...arguments_); + updateAdminBrandPresentation = ( + ...arguments_: Parameters + ) => this.resources.brand.updateAdminBrandPresentation(...arguments_); + listAdminReleases = (...arguments_: Parameters) => + this.resources.brand.listAdminReleases(...arguments_); + getAdminReleaseReadiness = ( + ...arguments_: Parameters + ) => this.resources.brand.getAdminReleaseReadiness(...arguments_); + publishAdminRelease = (...arguments_: Parameters) => + this.resources.brand.publishAdminRelease(...arguments_); + rollbackAdminRelease = (...arguments_: Parameters) => + this.resources.brand.rollbackAdminRelease(...arguments_); + revokeAdminRelease = (...arguments_: Parameters) => + this.resources.brand.revokeAdminRelease(...arguments_); + getPublicTemplate = (...arguments_: Parameters) => + this.resources.template.getPublicTemplate(...arguments_); + listPublicTemplates = (...arguments_: Parameters) => + this.resources.template.listPublicTemplates(...arguments_); + previewPublicTemplateCombination = ( + ...arguments_: Parameters + ) => this.resources.template.previewPublicTemplateCombination(...arguments_); + getAdminWorkspace = (...arguments_: Parameters) => + this.resources.template.getAdminWorkspace(...arguments_); + getAdminPreviewWorkspace = ( + ...arguments_: Parameters + ) => this.resources.template.getAdminPreviewWorkspace(...arguments_); + installAdminTemplate = (...arguments_: Parameters) => + this.resources.template.installAdminTemplate(...arguments_); + listAdminCapabilities = (...arguments_: Parameters) => + this.resources.template.listAdminCapabilities(...arguments_); + updateAdminCapability = (...arguments_: Parameters) => + this.resources.template.updateAdminCapability(...arguments_); + previewAdminSampleContent = ( + ...arguments_: Parameters + ) => this.resources.template.previewAdminSampleContent(...arguments_); + importAdminSampleContent = ( + ...arguments_: Parameters + ) => this.resources.template.importAdminSampleContent(...arguments_); + getAdminTemplateUpgradePreview = ( + ...arguments_: Parameters + ) => this.resources.template.getAdminTemplateUpgradePreview(...arguments_); + upgradeAdminTemplate = (...arguments_: Parameters) => + this.resources.template.upgradeAdminTemplate(...arguments_); + rollbackAdminTemplate = (...arguments_: Parameters) => + this.resources.template.rollbackAdminTemplate(...arguments_); + getPublicOffering = (...arguments_: Parameters) => + this.resources.offering.getPublicOffering(...arguments_); + listPublicOfferings = (...arguments_: Parameters) => + this.resources.offering.listPublicOfferings(...arguments_); + listAdminOfferings = (...arguments_: Parameters) => + this.resources.offering.listAdminOfferings(...arguments_); + createAdminOffering = (...arguments_: Parameters) => + this.resources.offering.createAdminOffering(...arguments_); + updateAdminOffering = (...arguments_: Parameters) => + this.resources.offering.updateAdminOffering(...arguments_); + deleteAdminOffering = (...arguments_: Parameters) => + this.resources.offering.deleteAdminOffering(...arguments_); + createAdminField = (...arguments_: Parameters) => + this.resources.inquiry.createAdminField(...arguments_); + deleteAdminField = (...arguments_: Parameters) => + this.resources.inquiry.deleteAdminField(...arguments_); + listAdminInquiryForms = (...arguments_: Parameters) => + this.resources.inquiry.listAdminInquiryForms(...arguments_); + listAdminInquirySubmissions = ( + ...arguments_: Parameters + ) => this.resources.inquiry.listAdminInquirySubmissions(...arguments_); + updateAdminInquirySubmission = ( + ...arguments_: Parameters + ) => this.resources.inquiry.updateAdminInquirySubmission(...arguments_); + createAdminInquiryForm = (...arguments_: Parameters) => + this.resources.inquiry.createAdminInquiryForm(...arguments_); + updateAdminInquiryForm = (...arguments_: Parameters) => + this.resources.inquiry.updateAdminInquiryForm(...arguments_); + listAdminTrustContent = (...arguments_: Parameters) => + this.resources.trust.listAdminTrustContent(...arguments_); + createAdminTrustContent = (...arguments_: Parameters) => + this.resources.trust.createAdminTrustContent(...arguments_); + updateAdminTrustContent = (...arguments_: Parameters) => + this.resources.trust.updateAdminTrustContent(...arguments_); + deleteAdminTrustContent = (...arguments_: Parameters) => + this.resources.trust.deleteAdminTrustContent(...arguments_); + getUploadConfig = (...arguments_: Parameters) => + this.resources.media.getUploadConfig(...arguments_); + createPresignedUpload = (...arguments_: Parameters) => + this.resources.media.createPresignedUpload(...arguments_); +} diff --git a/packages/api-client/src/resources/booking.ts b/packages/api-client/src/resources/booking.ts new file mode 100644 index 0000000..d55fa88 --- /dev/null +++ b/packages/api-client/src/resources/booking.ts @@ -0,0 +1,55 @@ +import type { BookingStatus } from "@personal-brand/types"; +import type { RequestFn } from "../client/request.js"; +import type { + AdminBooking, + Booking, + BookingTag, + CreateBookingInput, + BookingSummary, +} from "../types/booking.js"; + +export interface BookingMethods { + listCustomerBookings(): Promise; + createCustomerBooking(input: CreateBookingInput): Promise; + cancelCustomerBooking(id: string): Promise; + listAdminBookings(filters?: { + status?: BookingStatus; + unreadOnly?: boolean; + tagId?: string; + }): Promise; + getAdminBooking(id: string): Promise; + getAdminUnreadCount(): Promise<{ count: number }>; + updateAdminBookingStatus(id: string, status: BookingStatus, adminNote?: string): Promise; + markAdminBookingRead(id: string): Promise; + listAdminTags(): Promise; + createAdminTag(name: string): Promise; +} + +export function bookingMethods({ request }: { request: RequestFn }): BookingMethods { + return { + listCustomerBookings: () => request("/customer/bookings"), + createCustomerBooking: (input) => + request("/customer/bookings", { method: "POST", body: input }), + cancelCustomerBooking: (id) => + request(`/customer/bookings/${encodeURIComponent(id)}/cancel`, { method: "POST" }), + listAdminBookings: (filters = {}) => { + const params: string[] = []; + if (filters.status) params.push(`status=${encodeURIComponent(filters.status)}`); + if (filters.unreadOnly !== undefined) params.push(`unreadOnly=${filters.unreadOnly}`); + if (filters.tagId) params.push(`tagId=${encodeURIComponent(filters.tagId)}`); + const query = params.join("&"); + return request(`/admin/bookings${query ? `?${query}` : ""}`); + }, + getAdminBooking: (id) => request(`/admin/bookings/${encodeURIComponent(id)}`), + getAdminUnreadCount: () => request("/admin/bookings/unread-count"), + updateAdminBookingStatus: (id, status, adminNote) => + request(`/admin/bookings/${encodeURIComponent(id)}/status`, { + method: "POST", + body: { status, ...(adminNote === undefined ? {} : { adminNote }) }, + }), + markAdminBookingRead: (id) => + request(`/admin/bookings/${encodeURIComponent(id)}/read`, { method: "POST" }), + listAdminTags: () => request("/admin/bookings/tags"), + createAdminTag: (name) => request("/admin/bookings/tags", { method: "POST", body: { name } }), + }; +} diff --git a/packages/api-client/src/resources/brand.ts b/packages/api-client/src/resources/brand.ts new file mode 100644 index 0000000..1cc89c5 --- /dev/null +++ b/packages/api-client/src/resources/brand.ts @@ -0,0 +1,98 @@ +import type { RequestFn } from "../client/request.js"; +import type { + AdminBrandMember, + AdminBrandMembership, + BrandPresentationUpdate, + BrandProfile, + BrandReleaseSummary, + BrandUpdate, +} from "../types/brand.js"; + +export interface BrandMethods { + getAdminBrand(): Promise; + listAdminBrands(): Promise; + switchAdminBrand( + brandId: string, + ): Promise<{ token: string; brand: AdminBrandMembership["brand"] }>; + listAdminMembers(): Promise; + createAdminMember(body: { + username: string; + displayName: string; + password: string; + role: "owner" | "editor"; + }): Promise; + updateAdminMember( + id: string, + body: Partial>, + ): Promise; + getAdminVisualTemplatePreview(): Promise<{ + current: { + key: string; + version: string; + name: string; + theme: { colors: Record }; + variants: Record; + } | null; + available: string[]; + }>; + getAdminVisualTemplateHistory(): Promise<{ + history: Array<{ visualTemplateKey: string; savedAt: string }>; + }>; + rollbackAdminVisualTemplate(): Promise<{ visualTemplateKey: string; rolledBack: boolean }>; + updateAdminBrand(body: BrandUpdate): Promise; + updateAdminBrandPresentation(body: BrandPresentationUpdate): Promise<{ + visualPresentation: Record>; + }>; + listAdminReleases(): Promise; + getAdminReleaseReadiness(): Promise<{ + ready: boolean; + checks: Array<{ + key: string; + label: string; + passed: boolean; + help?: string; + destination?: string; + }>; + }>; + publishAdminRelease(note?: string): Promise; + rollbackAdminRelease(version: number, note?: string): Promise; + revokeAdminRelease(): Promise< + Pick + >; +} + +export function brandMethods({ request }: { request: RequestFn }): BrandMethods { + return { + getAdminBrand: () => request("/admin/config/brand"), + listAdminBrands: () => request("/admin/brands"), + switchAdminBrand: (brandId) => + request(`/admin/brands/${encodeURIComponent(brandId)}/switch`, { method: "POST" }), + listAdminMembers: () => request("/admin/brands/members"), + createAdminMember: (body) => request("/admin/brands/members", { method: "POST", body }), + updateAdminMember: (id, body) => + request(`/admin/brands/members/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }), + getAdminVisualTemplatePreview: () => request("/admin/config/visual-template/preview"), + getAdminVisualTemplateHistory: () => request("/admin/config/visual-template/history"), + rollbackAdminVisualTemplate: () => + request("/admin/config/visual-template/rollback", { method: "POST" }), + updateAdminBrand: (body) => request("/admin/config/brand", { method: "PATCH", body }), + updateAdminBrandPresentation: (body) => + request("/admin/config/presentation", { method: "PATCH", body }), + listAdminReleases: () => request("/admin/releases"), + getAdminReleaseReadiness: () => request("/admin/releases/readiness"), + publishAdminRelease: (note) => + request("/admin/releases/publish", { + method: "POST", + body: note === undefined ? {} : { note }, + }), + rollbackAdminRelease: (version, note) => + request(`/admin/releases/${version}/rollback`, { + method: "POST", + body: note === undefined ? {} : { note }, + }), + revokeAdminRelease: () => request("/admin/releases/revoke", { method: "POST" }), + }; +} diff --git a/packages/api-client/src/resources/inquiry.ts b/packages/api-client/src/resources/inquiry.ts new file mode 100644 index 0000000..71850da --- /dev/null +++ b/packages/api-client/src/resources/inquiry.ts @@ -0,0 +1,58 @@ +import type { RequestFn } from "../client/request.js"; +import type { BrandFieldDefinition } from "../types/field.js"; +import type { InquiryForm, InquirySubmission } from "../types/inquiry.js"; + +export interface InquiryMethods { + createAdminField( + body: Omit, + ): Promise; + deleteAdminField(id: string): Promise<{ deleted: boolean }>; + listAdminInquiryForms(): Promise; + listAdminInquirySubmissions(): Promise; + updateAdminInquirySubmission( + id: string, + body: { status: InquirySubmission["status"]; adminNote?: string }, + ): Promise; + createAdminInquiryForm(body: { + name: string; + offeringId?: string; + fieldsSnapshot: unknown[]; + isEnabled?: boolean; + purpose?: InquiryForm["purpose"]; + targetType?: InquiryForm["targetType"]; + submissionAction?: InquiryForm["submissionAction"]; + }): Promise; + updateAdminInquiryForm( + id: string, + body: Partial<{ + name: string; + offeringId: string; + fieldsSnapshot: unknown[]; + isEnabled: boolean; + purpose?: InquiryForm["purpose"]; + targetType?: InquiryForm["targetType"]; + submissionAction?: InquiryForm["submissionAction"]; + }>, + ): Promise; +} + +export function inquiryMethods({ request }: { request: RequestFn }): InquiryMethods { + return { + createAdminField: (body) => request("/admin/workspace/fields", { method: "POST", body }), + deleteAdminField: (id) => + request(`/admin/workspace/fields/${encodeURIComponent(id)}`, { method: "DELETE" }), + listAdminInquiryForms: () => request("/admin/workspace/forms"), + listAdminInquirySubmissions: () => request("/admin/workspace/submissions"), + updateAdminInquirySubmission: (id, body) => + request(`/admin/workspace/submissions/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }), + createAdminInquiryForm: (body) => request("/admin/workspace/forms", { method: "POST", body }), + updateAdminInquiryForm: (id, body) => + request(`/admin/workspace/forms/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }), + }; +} diff --git a/packages/api-client/src/resources/media.ts b/packages/api-client/src/resources/media.ts new file mode 100644 index 0000000..2a291dc --- /dev/null +++ b/packages/api-client/src/resources/media.ts @@ -0,0 +1,18 @@ +import type { RequestFn } from "../client/request.js"; +import type { PresignedUpload, UploadConfig } from "../types/media.js"; + +export interface MediaMethods { + getUploadConfig(): Promise; + createPresignedUpload(body: { + fileName: string; + contentType: string; + scope?: "brand" | "offering" | "trust"; + }): Promise; +} + +export function mediaMethods({ request }: { request: RequestFn }): MediaMethods { + return { + getUploadConfig: () => request("/admin/uploads/config"), + createPresignedUpload: (body) => request("/admin/uploads/presign", { method: "POST", body }), + }; +} diff --git a/packages/api-client/src/resources/offering.ts b/packages/api-client/src/resources/offering.ts new file mode 100644 index 0000000..715f4f2 --- /dev/null +++ b/packages/api-client/src/resources/offering.ts @@ -0,0 +1,32 @@ +import type { RequestFn } from "../client/request.js"; +import type { Offering } from "../types/offering.js"; + +export interface OfferingMethods { + getPublicOffering(id: string): Promise; + listPublicOfferings(): Promise; + listAdminOfferings(): Promise; + createAdminOffering(body: Omit): Promise; + updateAdminOffering( + id: string, + body: Partial>, + ): Promise; + deleteAdminOffering(id: string): Promise<{ deleted: boolean }>; +} + +export function offeringMethods({ request }: { request: RequestFn }): OfferingMethods { + return { + getPublicOffering: (id) => request(`/public/offerings/${encodeURIComponent(id)}`), + listPublicOfferings: () => request("/public/offerings"), + listAdminOfferings: () => request("/admin/workspace/offerings"), + createAdminOffering: (body) => request("/admin/workspace/offerings", { method: "POST", body }), + updateAdminOffering: (id, body) => + request(`/admin/workspace/offerings/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }), + deleteAdminOffering: (id) => + request(`/admin/workspace/offerings/${encodeURIComponent(id)}`, { + method: "DELETE", + }), + }; +} diff --git a/packages/api-client/src/resources/public.ts b/packages/api-client/src/resources/public.ts new file mode 100644 index 0000000..532f3d5 --- /dev/null +++ b/packages/api-client/src/resources/public.ts @@ -0,0 +1,38 @@ +import type { PublicOffering } from "@personal-brand/types"; +import type { RequestFn } from "../client/request.js"; +import type { BrandProfile } from "../types/brand.js"; +import type { InquiryForm, InquirySubmission } from "../types/inquiry.js"; +import type { PublicWorkspace } from "../types/workspace.js"; + +export interface PublicMethods { + getBrand(): Promise; + listOfferings(): Promise; + getPublicWorkspace(): Promise; + getPublicInquiryForm(id: string): Promise; + createCustomerInquirySubmission( + formId: string, + values: Record, + ): Promise; + listCustomerInquirySubmissions(): Promise; + getCustomerInquirySubmission(id: string): Promise; + createCustomerSession(code: string): Promise<{ token: string }>; +} + +export function publicMethods({ request }: { request: RequestFn }): PublicMethods { + return { + getBrand: () => request("/public/brand"), + listOfferings: () => request("/public/offerings"), + getPublicWorkspace: () => request("/public/workspace"), + getPublicInquiryForm: (id) => request(`/public/inquiry-forms/${encodeURIComponent(id)}`), + createCustomerInquirySubmission: (formId, values) => + request("/customer/inquiry-submissions", { + method: "POST", + body: { formId, values }, + }), + listCustomerInquirySubmissions: () => request("/customer/inquiry-submissions"), + getCustomerInquirySubmission: (id) => + request(`/customer/inquiry-submissions/${encodeURIComponent(id)}`), + createCustomerSession: (code) => + request("/customer/session/wechat", { method: "POST", body: { code } }), + }; +} diff --git a/packages/api-client/src/resources/session.ts b/packages/api-client/src/resources/session.ts new file mode 100644 index 0000000..ed89cbb --- /dev/null +++ b/packages/api-client/src/resources/session.ts @@ -0,0 +1,26 @@ +import type { RequestFn } from "../client/request.js"; + +export interface SessionMethods { + loginAdmin( + username: string, + password: string, + ): Promise<{ + token: string; + displayName: string; + mustChangePassword: boolean; + role: string; + }>; + changeAdminPassword(currentPassword: string, newPassword: string): Promise<{ changed: true }>; +} + +export function sessionMethods({ request }: { request: RequestFn }): SessionMethods { + return { + loginAdmin: (username, password) => + request("/admin/session/login", { method: "POST", body: { username, password } }), + changeAdminPassword: (currentPassword, newPassword) => + request("/admin/session/change-password", { + method: "POST", + body: { currentPassword, newPassword }, + }), + }; +} diff --git a/packages/api-client/src/resources/template.ts b/packages/api-client/src/resources/template.ts new file mode 100644 index 0000000..15483ee --- /dev/null +++ b/packages/api-client/src/resources/template.ts @@ -0,0 +1,150 @@ +import type { BrandTemplateKey, RuntimeWorkspace } from "@personal-brand/types"; +import type { RequestFn } from "../client/request.js"; +import type { BrandProfile } from "../types/brand.js"; +import type { CapabilityInstallation } from "../types/capability.js"; +import type { BrandFieldDefinition } from "../types/field.js"; +import type { Offering } from "../types/offering.js"; +import type { AdminTemplateContent } from "../types/template.js"; +import type { BrandTemplateDefinition } from "../types/template-definition.js"; + +export interface TemplateMethods { + getPublicTemplate(key: BrandTemplateKey): Promise; + listPublicTemplates(): Promise<{ + industries: BrandTemplateDefinition[]; + visuals: Array<{ + key: string; + version: string; + name: string; + description: string; + supportedIndustryTemplates: BrandTemplateKey[]; + variants: Record; + theme: { colors: Record }; + }>; + }>; + previewPublicTemplateCombination( + industry: string, + visual: string, + ): Promise<{ + industry: BrandTemplateDefinition; + visual: { + key: string; + version: string; + name: string; + description: string; + supportedIndustryTemplates: BrandTemplateKey[]; + variants: Record; + theme: { colors: Record }; + }; + runtime: { + schemaVersion: string; + capabilities: Array<{ key: string; version: string }>; + theme: unknown; + }; + }>; + getAdminWorkspace(): Promise<{ + brand: BrandProfile; + visualTemplate?: { + key: string; + version: string; + name: string; + supportedIndustryTemplates: BrandTemplateKey[]; + variants: Record; + } | null; + installations: Array<{ id: string; templateKey: BrandTemplateKey; templateVersion: string }>; + fields: BrandFieldDefinition[]; + offerings: Offering[]; + forms: unknown[]; + templateContent: AdminTemplateContent | null; + }>; + getAdminPreviewWorkspace(): Promise; + installAdminTemplate(templateKey: "personal" | "food" | "doors"): Promise; + listAdminCapabilities(): Promise; + updateAdminCapability( + key: string, + body: { + capabilityVersion: string; + status: CapabilityInstallation["status"]; + config?: Record; + }, + ): Promise; + previewAdminSampleContent(): Promise<{ + templateKey: string; + alreadyImported: boolean; + counts: Record; + willCreateInquiryForm: boolean; + }>; + importAdminSampleContent(): Promise<{ imported: boolean; counts: Record }>; + getAdminTemplateUpgradePreview(): Promise<{ + currentVersion: string; + latestVersion: string; + canUpgrade: boolean; + canRollback: boolean; + missingModules: unknown[]; + missingFields: unknown[]; + }>; + upgradeAdminTemplate(): Promise; + rollbackAdminTemplate(): Promise; +} + +export function templateMethods({ request }: { request: RequestFn }): TemplateMethods { + return { + getPublicTemplate: (key) => request(`/public/templates/${key}`), + listPublicTemplates: () => + request<{ + industries: BrandTemplateDefinition[]; + visuals: Array<{ + key: string; + version: string; + name: string; + description: string; + supportedIndustryTemplates?: unknown; + variants?: unknown; + theme?: unknown; + }>; + }>("/public/templates").then((catalog) => ({ + industries: Array.isArray(catalog.industries) ? catalog.industries : [], + visuals: Array.isArray(catalog.visuals) + ? catalog.visuals.map((visual) => ({ + key: String(visual.key ?? ""), + version: String(visual.version ?? ""), + name: String(visual.name ?? "未命名视觉模板"), + description: String(visual.description ?? ""), + supportedIndustryTemplates: Array.isArray(visual.supportedIndustryTemplates) + ? visual.supportedIndustryTemplates.filter( + (item): item is BrandTemplateKey => + item === "personal" || item === "food" || item === "doors", + ) + : [], + variants: + visual.variants && typeof visual.variants === "object" + ? (visual.variants as Record) + : {}, + theme: + visual.theme && typeof visual.theme === "object" + ? (visual.theme as { colors: Record }) + : { colors: {} }, + })) + : [], + })), + previewPublicTemplateCombination: (industry, visual) => + request( + `/public/templates/preview?industry=${encodeURIComponent(industry)}&visual=${encodeURIComponent(visual)}`, + ), + getAdminWorkspace: () => request("/admin/workspace"), + getAdminPreviewWorkspace: () => request("/admin/workspace/preview"), + installAdminTemplate: (templateKey) => + request("/admin/workspace/install", { method: "POST", body: { templateKey } }), + listAdminCapabilities: () => request("/admin/workspace/capabilities"), + updateAdminCapability: (key, body) => + request(`/admin/workspace/capabilities/${encodeURIComponent(key)}`, { + method: "PATCH", + body, + }), + previewAdminSampleContent: () => request("/admin/workspace/sample-content/preview"), + importAdminSampleContent: () => + request("/admin/workspace/sample-content/import", { method: "POST" }), + getAdminTemplateUpgradePreview: () => request("/admin/workspace/template/preview"), + upgradeAdminTemplate: () => request("/admin/workspace/template/upgrade", { method: "POST" }), + rollbackAdminTemplate: () => request("/admin/workspace/template/rollback", { method: "POST" }), + }; +} diff --git a/packages/api-client/src/resources/trust.ts b/packages/api-client/src/resources/trust.ts new file mode 100644 index 0000000..f7f9611 --- /dev/null +++ b/packages/api-client/src/resources/trust.ts @@ -0,0 +1,26 @@ +import type { RequestFn } from "../client/request.js"; +import type { TrustContent, TrustContentInput } from "../types/trust.js"; + +export interface TrustMethods { + listAdminTrustContent(): Promise; + createAdminTrustContent(body: TrustContentInput): Promise; + updateAdminTrustContent(id: string, body: Partial): Promise; + deleteAdminTrustContent(id: string): Promise<{ deleted: boolean }>; +} + +export function trustMethods({ request }: { request: RequestFn }): TrustMethods { + return { + listAdminTrustContent: () => request("/admin/config/trust-content"), + createAdminTrustContent: (body) => + request("/admin/config/trust-content", { method: "POST", body }), + updateAdminTrustContent: (id, body) => + request(`/admin/config/trust-content/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }), + deleteAdminTrustContent: (id) => + request(`/admin/config/trust-content/${encodeURIComponent(id)}`, { + method: "DELETE", + }), + }; +} diff --git a/packages/api-client/src/types/booking.ts b/packages/api-client/src/types/booking.ts new file mode 100644 index 0000000..d993849 --- /dev/null +++ b/packages/api-client/src/types/booking.ts @@ -0,0 +1,51 @@ +import type { + BookingRequestType, + BookingStatus, + ContactPreference, + FulfillmentType, +} from "@personal-brand/types"; + +export interface BookingItemInput { + offeringId: string; + quantity: number; +} + +export interface CreateBookingInput { + requestType: BookingRequestType; + customerName: string; + phone?: string; + wechatId?: string; + contactPreference: ContactPreference; + fulfillmentType?: FulfillmentType; + offeringId?: string; + requestedDate?: string; + requestedTime?: string; + deliveryAddress?: string; + note?: string; + extraData?: Record; + items: BookingItemInput[]; +} + +export interface BookingSummary { + bookingNo: string; + status: BookingStatus; + estimatedAmount: number | null; + createdAt: string; +} + +export interface Booking extends BookingSummary { + id: string; + customerName: string; + adminNote?: string | null; +} + +export interface BookingTag { + id: string; + name: string; + isPreset: boolean; + isEnabled: boolean; +} + +export interface AdminBooking extends Booking { + tags?: Array<{ tag: BookingTag }>; +} diff --git a/packages/api-client/src/types/brand.ts b/packages/api-client/src/types/brand.ts new file mode 100644 index 0000000..20d6b0c --- /dev/null +++ b/packages/api-client/src/types/brand.ts @@ -0,0 +1,56 @@ +import type { BrandTemplateKey } from "@personal-brand/types"; + +export interface BrandProfile { + id: string; + slug?: string; + name: string; + templateKey: BrandTemplateKey; + tagline: string | null; + description: string | null; + avatarUrl: string | null; + coverUrl: string | null; + hours: string | null; + address: string | null; + deliveryNote: string | null; + contactPhone: string | null; + contactWechat: string | null; + config?: Record | null; +} + +export interface AdminBrandMembership { + id: string; + role: string; + brand: Pick & { slug?: string }; +} + +export interface AdminBrandMember { + id: string; + role: string; + isEnabled: boolean; + adminUser: { + id: string; + username: string; + displayName: string; + isEnabled: boolean; + }; +} + +export type BrandUpdate = Partial>; + +export interface BrandReleaseSummary { + id: string; + version: number; + status: string; + note: string | null; + actorId: string; + createdAt: string; + revokedAt: string | null; + revokedBy?: string | null; +} + +export type BrandPresentationUpdate = Partial< + Record< + "identity" | "home" | "offerings" | "detail" | "profile" | "inquiry" | "success" | "records", + Record + > +>; diff --git a/packages/api-client/src/types/capability.ts b/packages/api-client/src/types/capability.ts new file mode 100644 index 0000000..53b5f09 --- /dev/null +++ b/packages/api-client/src/types/capability.ts @@ -0,0 +1,9 @@ +export interface CapabilityInstallation { + id: string | null; + capabilityKey: string; + capabilityVersion: string; + status: "enabled" | "disabled" | "degraded"; + config?: Record | null; + updatedAt: string | null; + source?: "template" | "brand"; +} diff --git a/packages/api-client/src/types/common.ts b/packages/api-client/src/types/common.ts new file mode 100644 index 0000000..e23973e --- /dev/null +++ b/packages/api-client/src/types/common.ts @@ -0,0 +1,5 @@ +export interface ApiErrorBody { + data: null; + error: { code: string; message: string }; + requestId: string | null; +} diff --git a/packages/api-client/src/types/field.ts b/packages/api-client/src/types/field.ts new file mode 100644 index 0000000..243180f --- /dev/null +++ b/packages/api-client/src/types/field.ts @@ -0,0 +1,11 @@ +export interface BrandFieldDefinition { + id: string; + scope: string; + key: string; + label: string; + type: string; + required: boolean; + isVisible: boolean; + sortOrder: number; + source: string; +} diff --git a/packages/api-client/src/types/inquiry.ts b/packages/api-client/src/types/inquiry.ts new file mode 100644 index 0000000..a8d695a --- /dev/null +++ b/packages/api-client/src/types/inquiry.ts @@ -0,0 +1,30 @@ +export interface InquiryForm { + id: string; + name: string; + offeringId?: string | null; + version: number; + isEnabled: boolean; + fieldsSnapshot: unknown[]; + purpose: "inquiry" | "booking" | "quote-request"; + targetType: "brand" | "offering"; + submissionAction: "create-inquiry" | "create-booking" | "create-quote"; +} + +export interface InquirySubmission { + id: string; + inquiryFormId: string; + formVersion: number; + fieldsSnapshot: unknown[]; + values: Record; + activeFields: Record; + createdAt: string; + status: "new" | "reviewing" | "replied" | "qualified" | "converted" | "closed"; + adminNote?: string | null; + inquiryForm?: { name: string }; + offering?: { id: string; name: string } | null; + statusHistory?: Array<{ + fromStatus?: string | null; + toStatus: string; + createdAt: string; + }>; +} diff --git a/packages/api-client/src/types/media.ts b/packages/api-client/src/types/media.ts new file mode 100644 index 0000000..b69f4b5 --- /dev/null +++ b/packages/api-client/src/types/media.ts @@ -0,0 +1,11 @@ +export interface UploadConfig { + configured: boolean; + status: "ok" | "unavailable" | "unconfigured"; + bucket?: string; +} + +export interface PresignedUpload { + uploadUrl: string; + key: string; + publicUrl: string; +} diff --git a/packages/api-client/src/types/offering.ts b/packages/api-client/src/types/offering.ts new file mode 100644 index 0000000..93597e2 --- /dev/null +++ b/packages/api-client/src/types/offering.ts @@ -0,0 +1,52 @@ +import type { InquiryForm } from "./inquiry.js"; + +export interface OfferingSection { + type: "text" | "image-list" | "timeline" | "faq"; + title: string; + content?: string; + items?: unknown[]; +} + +export interface OfferingMedia { + url: string; + alt?: string; + type?: "image" | "video"; +} + +export interface OfferingCta { + type: "inquiry" | "booking" | "contact" | "external-link"; + label: string; + config?: Record; +} + +export interface Offering { + id: string; + brandId?: string; + kind: "service" | "product" | "package" | "subscription"; + name: string; + summary?: string | null; + description?: string | null; + coverUrl?: string | null; + priceText?: string | null; + priceAmount?: number | null; + isEnabled: boolean; + sortOrder: number; + config?: Record | null; + sections?: OfferingSection[]; + media?: OfferingMedia[]; + cta?: OfferingCta; + inquiryForms?: Array>; +} + +export interface OfferingUpdate { + name?: string; + description?: string; + coverUrl?: string; + priceText?: string; + priceAmount?: number; + sortOrder?: number; + bookingEnabled?: boolean; + isEnabled?: boolean; + categoryKey?: string; + config?: Record; +} diff --git a/packages/api-client/src/types/template-definition.ts b/packages/api-client/src/types/template-definition.ts new file mode 100644 index 0000000..ed49e90 --- /dev/null +++ b/packages/api-client/src/types/template-definition.ts @@ -0,0 +1,27 @@ +export interface BrandTemplateDefinition { + key: "personal" | "food" | "doors"; + version: string; + name: string; + description: string; + serviceCategories: string[]; + trustContentTypes: string[]; + modules: Array<{ + key: string; + type: string; + title: string; + required: boolean; + }>; + fields: Array<{ + scope: string; + key: string; + label: string; + type: string; + required: boolean; + }>; + capabilities: string[]; + runtimeCapabilities: Array<{ + key: string; + version: string; + workflowKey?: string; + }>; +} diff --git a/packages/api-client/src/types/template.ts b/packages/api-client/src/types/template.ts new file mode 100644 index 0000000..ea39dd7 --- /dev/null +++ b/packages/api-client/src/types/template.ts @@ -0,0 +1,80 @@ +export interface TemplateAdminField { + key: string; + page?: string; + binding: string; + label: string; + help?: string; + input: + | "text" + | "textarea" + | "phone" + | "image" + | "number" + | "boolean" + | "select" + | "multi-select" + | "list"; + itemFields?: Array<{ + key: string; + label: string; + input?: "text" | "textarea"; + required?: boolean; + }>; + itemValueKey?: string; + required?: boolean; + maxLength?: number; + placeholder?: string; + options?: Array<{ value: string; label: string }>; + previewTarget?: string; +} + +export interface TemplateAdminSection { + key: string; + title: string; + description: string; + page: string; + target: "brand" | "offering" | "trust" | "inquiry"; + previewTargets?: Array<{ + key: string; + label: string; + composite?: boolean; + children?: string[]; + }>; + fields: TemplateAdminField[]; +} + +export interface AdminTemplateContent { + displayName: string; + admin: { sections: TemplateAdminSection[] }; + navigation: Array<{ key: string; label: string; page: string }>; + templateFields?: TemplateAdminField[]; + trustContentTypes?: Array<{ + type: string; + label: string; + adminFields: { + title: string; + summary: string; + content: string; + summaryHelp?: string; + summaryPlaceholder?: string; + }; + pages?: string[]; + help?: string; + placeholder?: string; + required?: boolean; + configFields?: TemplateAdminField[]; + previewTargets?: Array<{ key: string; label: string; page?: string }>; + maxPublishedItems?: number; + hideStandardFields?: Array<"summary" | "content">; + }>; + assetSlots: Array<{ + key: string; + binding: string; + target: "brand" | "offering" | "trust"; + label: string; + help: string; + required: boolean; + kind: "image" | "logo" | "portrait" | "texture"; + aspectRatio?: string; + }>; +} diff --git a/packages/api-client/src/types/trust.ts b/packages/api-client/src/types/trust.ts new file mode 100644 index 0000000..f2b313f --- /dev/null +++ b/packages/api-client/src/types/trust.ts @@ -0,0 +1,22 @@ +export interface TrustContent { + id: string; + type: string; + title: string; + summary?: string | null; + content: string; + coverUrl?: string | null; + sortOrder: number; + isPublished: boolean; + config?: Record | null; +} + +export interface TrustContentInput { + type: string; + title: string; + summary?: string; + content: string; + coverUrl?: string; + sortOrder?: number; + isPublished?: boolean; + config?: Record; +} diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts new file mode 100644 index 0000000..496aa84 --- /dev/null +++ b/packages/api-client/src/types/workspace.ts @@ -0,0 +1,76 @@ +import type { + BrandTemplateKey, + RuntimeCapability, + RuntimeInquiryForm, + RuntimeOffering, + RuntimeTrustItem, + ThemeManifest, +} from "@personal-brand/types"; +import type { BrandProfile } from "./brand.js"; + +export interface PublicWorkspace { + schemaVersion: string; + contractVersion: string; + publication: { + status: "published" | "unpublished"; + version: number | null; + publishedAt?: string; + }; + brand: (BrandProfile & Record) | null; + template: { key: BrandTemplateKey; version: string; name: string } | null; + visualTemplate: { + key: string; + version: string; + name: string; + supportedIndustryTemplates: BrandTemplateKey[]; + variants: Record; + } | null; + visualTemplateManifest?: { + schemaVersion: "1.0"; + key: string; + version: string; + name: string; + brandFirst: true; + tokens: { + colors: Record; + spacing: Record; + typography: Record; + radius: Record; + shadows?: Record; + }; + pages: Array<{ + key: string; + title: string; + modules: Array<{ + key: string; + type: string; + variant: string; + required: boolean; + dataSlots?: string[]; + assetSlots?: string[]; + capability?: string; + }>; + }>; + assets: Array>; + dataSlots: Array>; + capabilities: string[]; + }; + capabilities: RuntimeCapability[]; + offerings: RuntimeOffering[]; + inquiryForms: RuntimeInquiryForm[]; + trustItems: RuntimeTrustItem[]; + navigation: { tabs: Array<{ key: string; label: string; page: string }> }; + trustPresentation: Record; + theme: ThemeManifest; + layout?: { home: string[]; offerings: string[]; detail: string[]; profile: string[] }; + plugins?: Array<{ + key: string; + version: string; + displayName: string; + purpose: string; + requiredModules: string[]; + apiContract: string; + configSchema: string; + status: string; + }>; +} diff --git a/packages/api-client/test/exports.test.ts b/packages/api-client/test/exports.test.ts new file mode 100644 index 0000000..cb83eb1 --- /dev/null +++ b/packages/api-client/test/exports.test.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import * as apiClientModule from "../src/index.js"; + +test("聚合导出保持既有公共契约", () => { + const expectedExports = [ + "ApiClient", + "ApiClientError", + "apiClientName", + "isTrustContentComplete", + "projectBrandAliases", + "projectTrustPresentation", + ]; + + for (const exportName of expectedExports) { + assert.ok(exportName in apiClientModule, `${exportName} 必须保留导出`); + } +});