Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Replace @spree/sdk with @spree/admin-sdk in admin app

Damian Legawiec5cfaba9165fc
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 422e621a61..bf74e1c04c 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -1,24 +1,205 @@
-import type { RequestFn, RequestOptions } from '@spree/sdk-core';
+import type { RequestFn, RequestOptions, AuthTokens, LoginCredentials } from '@spree/sdk-core';
import { transformListParams, getParams } from '@spree/sdk-core';
import type { PaginatedResponse, ListParams } from '@spree/sdk-core';
+import type { Store, Product, Order, Asset, Taxon, TaxCategory, ShippingCategory } from './types';
+import type {
+ StoreUpdateParams,
+ ProductUpdateParams,
+ OrderUpdateParams,
+ AssetCreateParams,
+ AssetUpdateParams,
+ LineItemCreateParams,
+ LineItemUpdateParams,
+ AdjustmentCreateParams,
+ ShipmentUpdateParams,
+ DirectUploadCreateParams,
+} from './params';
-// Placeholder: Admin client will be populated with admin endpoints
-// as they are added to the API.
export class AdminClient {
/** @internal */
readonly request: RequestFn;
constructor(request: RequestFn) {
this.request = request;
-
- // Suppress unused warnings until endpoints are added
- void transformListParams;
- void getParams;
}
- // Example structure for future admin endpoints:
- // readonly products = { ... };
- // readonly orders = { ... };
+ // ============================================
+ // Authentication
+ // ============================================
+
+ readonly auth = {
+ login: (credentials: LoginCredentials, options?: RequestOptions): Promise<AuthTokens> =>
+ this.request<AuthTokens>('POST', '/auth/login', { ...options, body: credentials }),
+
+ refresh: (options?: RequestOptions): Promise<AuthTokens> =>
+ this.request<AuthTokens>('POST', '/auth/refresh', options),
+ };
+
+ // ============================================
+ // Store Settings
+ // ============================================
+
+ readonly store = {
+ get: (options?: RequestOptions): Promise<Store> =>
+ this.request<Store>('GET', '/store', options),
+
+ update: (params: StoreUpdateParams, options?: RequestOptions): Promise<Store> =>
+ this.request<Store>('PATCH', '/store', { ...options, body: params }),
+ };
+
+ // ============================================
+ // Products
+ // ============================================
+
+ readonly products = {
+ list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Product>> =>
+ this.request<PaginatedResponse<Product>>('GET', '/products', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ get: (id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Product> =>
+ this.request<Product>('GET', `/products/${id}`, {
+ ...options,
+ params: getParams(params),
+ }),
+
+ update: (id: string, params: ProductUpdateParams, options?: RequestOptions): Promise<Product> =>
+ this.request<Product>('PATCH', `/products/${id}`, { ...options, body: params }),
+
+ delete: (id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/products/${id}`, options),
+
+ assets: {
+ list: (productId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Asset>> =>
+ this.request<PaginatedResponse<Asset>>('GET', `/products/${productId}/assets`, {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ create: (productId: string, params: AssetCreateParams, options?: RequestOptions): Promise<Asset> =>
+ this.request<Asset>('POST', `/products/${productId}/assets`, { ...options, body: params }),
+
+ update: (productId: string, id: string, params: AssetUpdateParams, options?: RequestOptions): Promise<Asset> =>
+ this.request<Asset>('PATCH', `/products/${productId}/assets/${id}`, { ...options, body: params }),
+
+ delete: (productId: string, id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/products/${productId}/assets/${id}`, options),
+ },
+ };
+
+ // ============================================
+ // Orders
+ // ============================================
+
+ readonly orders = {
+ list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Order>> =>
+ this.request<PaginatedResponse<Order>>('GET', '/orders', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ get: (id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Order> =>
+ this.request<Order>('GET', `/orders/${id}`, {
+ ...options,
+ params: getParams(params),
+ }),
+
+ update: (id: string, params: OrderUpdateParams | Record<string, unknown>, options?: RequestOptions): Promise<Order> =>
+ this.request<Order>('PATCH', `/orders/${id}`, { ...options, body: params }),
+
+ cancel: (id: string, options?: RequestOptions): Promise<Order> =>
+ this.request<Order>('PATCH', `/orders/${id}/cancel`, options),
+
+ resendConfirmation: (id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('POST', `/orders/${id}/resend_confirmation`, options),
+
+ lineItems: {
+ create: (orderId: string, params: LineItemCreateParams, options?: RequestOptions): Promise<unknown> =>
+ this.request('POST', `/orders/${orderId}/line_items`, { ...options, body: params }),
+
+ update: (orderId: string, id: string, params: LineItemUpdateParams, options?: RequestOptions): Promise<unknown> =>
+ this.request('PATCH', `/orders/${orderId}/line_items/${id}`, { ...options, body: params }),
+
+ delete: (orderId: string, id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/orders/${orderId}/line_items/${id}`, options),
+ },
+
+ shipments: {
+ update: (orderId: string, id: string, params: ShipmentUpdateParams, options?: RequestOptions): Promise<unknown> =>
+ this.request('PATCH', `/orders/${orderId}/shipments/${id}`, { ...options, body: params }),
+
+ ship: (orderId: string, id: string, options?: RequestOptions): Promise<unknown> =>
+ this.request('PATCH', `/orders/${orderId}/shipments/${id}/ship`, options),
+
+ cancel: (orderId: string, id: string, options?: RequestOptions): Promise<unknown> =>
+ this.request('PATCH', `/orders/${orderId}/shipments/${id}/cancel`, options),
+ },
+
+ payments: {
+ capture: (orderId: string, id: string, options?: RequestOptions): Promise<unknown> =>
+ this.request('PATCH', `/orders/${orderId}/payments/${id}/capture`, options),
+
+ void: (orderId: string, id: string, options?: RequestOptions): Promise<unknown> =>
+ this.request('PATCH', `/orders/${orderId}/payments/${id}/void`, options),
+ },
+
+ adjustments: {
+ create: (orderId: string, params: AdjustmentCreateParams, options?: RequestOptions): Promise<unknown> =>
+ this.request('POST', `/orders/${orderId}/adjustments`, { ...options, body: params }),
+
+ delete: (orderId: string, id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/orders/${orderId}/adjustments/${id}`, options),
+ },
+ };
+
+ // ============================================
+ // Taxons
+ // ============================================
+
+ readonly taxons = {
+ list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Taxon>> =>
+ this.request<PaginatedResponse<Taxon>>('GET', '/taxons', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+ };
+
+ // ============================================
+ // Tax Categories
+ // ============================================
+
+ readonly taxCategories = {
+ list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<TaxCategory>> =>
+ this.request<PaginatedResponse<TaxCategory>>('GET', '/tax_categories', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+ };
+
+ // ============================================
+ // Shipping Categories
+ // ============================================
+
+ readonly shippingCategories = {
+ list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<ShippingCategory>> =>
+ this.request<PaginatedResponse<ShippingCategory>>('GET', '/shipping_categories', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+ };
+
+ // ============================================
+ // Direct Uploads (Active Storage)
+ // ============================================
+
+ readonly directUploads = {
+ create: (params: DirectUploadCreateParams, options?: RequestOptions): Promise<{
+ direct_upload: { url: string; headers: Record<string, string> };
+ signed_id: string;
+ }> =>
+ this.request('POST', '/direct_uploads', { ...options, body: params }),
+ };
}
// Re-export for type convenience
diff --git a/packages/admin-sdk/src/client.ts b/packages/admin-sdk/src/client.ts
index be79f57b9c..4698343cc2 100644
--- a/packages/admin-sdk/src/client.ts
+++ b/packages/admin-sdk/src/client.ts
@@ -47,7 +47,7 @@ export interface Client extends AdminClient {
* ```
*/
export function createAdminClient(config: AdminClientConfig): Client {
- if (!config.secretKey && !config.jwtToken) {
+ if (!config.secretKey && config.jwtToken === undefined) {
throw new Error('Admin client requires either secretKey or jwtToken');
}
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
new file mode 100644
index 0000000000..86c796d018
--- /dev/null
+++ b/packages/admin-sdk/src/params.ts
@@ -0,0 +1,291 @@
+// Request parameter types for Admin API endpoints
+// Based on the Admin API OpenAPI specification
+
+export interface StoreUpdateParams {
+ name?: string;
+ url?: string;
+ mail_from_address?: string;
+ customer_support_email?: string;
+ new_order_notifications_email?: string;
+ description?: string;
+ address?: string;
+ contact_phone?: string;
+ seo_title?: string;
+ meta_keywords?: string;
+ meta_description?: string;
+ default_currency?: string;
+ default_locale?: string;
+ supported_currencies?: string;
+ supported_locales?: string;
+}
+
+export interface OptionTypeCreateParams {
+ name: string;
+ presentation: string;
+ position?: number;
+ filterable?: boolean;
+ option_values?: Array<{
+ name?: string;
+ presentation?: string;
+ position?: number;
+ }>;
+}
+
+export interface OptionTypeUpdateParams {
+ name?: string;
+ presentation?: string;
+ position?: number;
+ filterable?: boolean;
+ option_values?: Array<{
+ id?: string;
+ name?: string;
+ presentation?: string;
+ position?: number;
+ }>;
+}
+
+export interface AdjustmentCreateParams {
+ amount: number;
+ label: string;
+}
+
+export interface AdjustmentUpdateParams {
+ amount?: number;
+ label?: string;
+ eligible?: boolean;
+}
+
+export interface LineItemCreateParams {
+ variant_id: string;
+ quantity?: number;
+}
+
+export interface LineItemUpdateParams {
+ quantity?: number;
+}
+
+export interface PaymentCreateParams {
+ payment_method_id: string;
+ amount?: number;
+ source_id?: string;
+}
+
+export interface RefundCreateParams {
+ payment_id: string;
+ amount: number;
+ refund_reason_id?: string;
+}
+
+export interface ShipmentUpdateParams {
+ tracking?: string;
+ selected_shipping_rate_id?: string;
+}
+
+export interface OrderCreateParams {
+ email?: string;
+ user_id?: string;
+ currency?: string;
+ channel?: string;
+ internal_note?: string;
+}
+
+export interface OrderUpdateParams {
+ email?: string;
+ special_instructions?: string;
+ internal_note?: string;
+ channel?: string;
+ ship_address?: {
+ firstname?: string;
+ lastname?: string;
+ address1?: string;
+ city?: string;
+ zipcode?: string;
+ country_iso?: string;
+ state_abbr?: string;
+ phone?: string;
+ };
+ bill_address?: {
+ firstname?: string;
+ lastname?: string;
+ address1?: string;
+ city?: string;
+ zipcode?: string;
+ country_iso?: string;
+ state_abbr?: string;
+ phone?: string;
+ };
+ line_items?: Array<{
+ variant_id?: string;
+ quantity?: number;
+ }>;
+}
+
+export interface DirectUploadCreateParams {
+ blob: {
+ filename: string;
+ byte_size: number;
+ checksum: string;
+ content_type: string;
+ };
+}
+
+export interface AssetCreateParams {
+ alt?: string;
+ position?: number;
+ type?: string;
+ url?: string;
+ signed_id?: string;
+}
+
+export interface AssetUpdateParams {
+ alt?: string;
+ position?: number;
+}
+
+export interface ProductCreateParams {
+ name: string;
+ price: number;
+ description?: string;
+ slug?: string;
+ status?: 'draft' | 'active' | 'archived';
+ sku?: string;
+ shipping_category_id: string;
+ tax_category_id?: string;
+ taxon_ids?: Array<string>;
+ tags?: Array<string>;
+ variants?: Array<{
+ sku?: string;
+ price?: number;
+ option_type?: string;
+ option_value?: string;
+ total_on_hand?: number;
+ prices?: Array<{
+ currency: string;
+ amount: number;
+ compare_at_amount?: number;
+ }>;
+ }>;
+}
+
+export interface ProductUpdateParams {
+ name?: string;
+ price?: number;
+ description?: string;
+ slug?: string;
+ status?: 'draft' | 'active' | 'archived';
+ sku?: string;
+ shipping_category_id?: string;
+ tax_category_id?: string;
+ taxon_ids?: Array<string>;
+ tags?: Array<string>;
+ variants?: Array<{
+ sku?: string;
+ price?: number;
+ option_type?: string;
+ option_value?: string;
+ total_on_hand?: number;
+ prices?: Array<{
+ currency: string;
+ amount: number;
+ compare_at_amount?: number;
+ }>;
+ }>;
+}
+
+export interface TaxonomyCreateParams {
+ name: string;
+ position?: number;
+}
+
+export interface TaxonomyUpdateParams {
+ name?: string;
+ position?: number;
+}
+
+export interface TaxonCreateParams {
+ name: string;
+ parent_id?: string;
+ position?: number;
+ description?: string;
+ permalink?: string;
+ meta_title?: string;
+ meta_description?: string;
+ meta_keywords?: string;
+ hide_from_nav?: boolean;
+ sort_order?: string;
+}
+
+export interface TaxonUpdateParams {
+ name?: string;
+ parent_id?: string;
+ position?: number;
+ description?: string;
+ permalink?: string;
+ meta_title?: string;
+ meta_description?: string;
+ meta_keywords?: string;
+ hide_from_nav?: boolean;
+ sort_order?: string;
+}
+
+export interface VariantCreateParams {
+ sku?: string;
+ price?: number;
+ compare_at_price?: number;
+ cost_price?: number;
+ cost_currency?: string;
+ weight?: number;
+ height?: number;
+ width?: number;
+ depth?: number;
+ weight_unit?: string;
+ dimensions_unit?: string;
+ track_inventory?: boolean;
+ tax_category_id?: string;
+ option_type?: string;
+ option_value?: string;
+ total_on_hand?: number;
+ position?: number;
+ barcode?: string;
+ prices?: Array<{
+ currency: string;
+ amount: number;
+ compare_at_amount?: number;
+ }>;
+ stock_items?: Array<{
+ stock_location_id?: string;
+ count_on_hand?: number;
+ backorderable?: boolean;
+ }>;
+}
+
+export interface VariantUpdateParams {
+ sku?: string;
+ price?: number;
+ compare_at_price?: number;
+ cost_price?: number;
+ cost_currency?: string;
+ weight?: number;
+ height?: number;
+ width?: number;
+ depth?: number;
+ weight_unit?: string;
+ dimensions_unit?: string;
+ track_inventory?: boolean;
+ tax_category_id?: string;
+ option_type?: string;
+ option_value?: string;
+ total_on_hand?: number;
+ position?: number;
+ barcode?: string;
+ prices?: Array<{
+ currency: string;
+ amount: number;
+ compare_at_amount?: number;
+ }>;
+ stock_items?: Array<{
+ stock_location_id?: string;
+ count_on_hand?: number;
+ backorderable?: boolean;
+ }>;
+}
diff --git a/packages/admin-sdk/src/types/generated/Store.ts b/packages/admin-sdk/src/types/generated/Store.ts
new file mode 100644
index 0000000000..05becf1016
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/Store.ts
@@ -0,0 +1,30 @@
+// Typelizer digest 434248d920da5234a6f1e49b80eaab7a
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type Store = {
+ id: string;
+ name: string;
+ url: string;
+ code: string;
+ default_currency: string;
+ default_locale: string;
+ supported_currencies: Array<string>;
+ supported_locales: Array<string>;
+ mail_from_address: string;
+ customer_support_email: string | null;
+ new_order_notifications_email: string | null;
+ description: string | null;
+ address: string | null;
+ contact_phone: string | null;
+ seo_title: string | null;
+ meta_keywords: string | null;
+ meta_description: string | null;
+ default: boolean;
+ created_at: string;
+ updated_at: string;
+ logo_url: string | null;
+ mailer_logo_url: string | null;
+}
+
+export default Store;
diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.ts
index 97de9dc2a1..eb9ab00fd7 100644
--- a/packages/admin-sdk/src/types/generated/index.ts
+++ b/packages/admin-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 3d6cfbd10466fcce81d2d1aec3b111e7
+// Typelizer digest ecacbe9a99e7a71827dc7c943bcfaf36
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -37,5 +37,6 @@ export type { default as State } from './State'
export type { default as StockItem } from './StockItem'
export type { default as StockLocation } from './StockLocation'
export type { default as StoreCredit } from './StoreCredit'
+export type { default as Store } from './Store'
export type { default as TaxCategory } from './TaxCategory'
export type { default as Variant } from './Variant'
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index 7ad54c1715..025fb5dd69 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -8,8 +8,13 @@ export type {
ListParams,
} from '@spree/sdk-core';
-// Admin-specific generated types will be re-exported here with unprefixed names
-// once Typelizer is configured to generate admin types into this package.
-// Example:
-// export type { default as Product } from './generated/AdminProduct';
-// export type { default as Order } from './generated/AdminOrder';
+// Admin-specific generated types
+export type { default as Address } from './generated/Address';
+export type { default as Asset } from './generated/Asset';
+export type { default as Image } from './generated/Image';
+export type { default as Order } from './generated/Order';
+export type { default as Product } from './generated/Product';
+export type { default as ShippingCategory } from './generated/ShippingCategory';
+export type { default as Store } from './generated/Store';
+export type { default as TaxCategory } from './generated/TaxCategory';
+export type { default as Taxon } from './generated/Taxon';
diff --git a/packages/admin/package.json b/packages/admin/package.json
index 4a82e256b8..5a25a9608e 100644
--- a/packages/admin/package.json
+++ b/packages/admin/package.json
@@ -16,7 +16,7 @@
"@fontsource-variable/geist": "^5.2.8",
"@fontsource-variable/inter": "^5.2.8",
"@hookform/resolvers": "^5.2.2",
- "@spree/sdk": "workspace:^",
+ "@spree/admin-sdk": "workspace:^",
"@tanstack/react-query": "^5.90.21",
"@tanstack/react-router": "^1.166.2",
"@tiptap/extension-link": "^3.20.1",
diff --git a/packages/admin/src/client.ts b/packages/admin/src/client.ts
index 74a5f6f268..3bb6fc9b04 100644
--- a/packages/admin/src/client.ts
+++ b/packages/admin/src/client.ts
@@ -1,6 +1,10 @@
-import { createSpreeClient } from '@spree/sdk'
+import { createAdminClient } from '@spree/admin-sdk'
-export const spreeClient = createSpreeClient({
- baseUrl: import.meta.env.VITE_SPREE_API_URL || 'http://localhost:3000',
- secretKey: import.meta.env.VITE_SPREE_SECRET_KEY,
+const baseUrl = import.meta.env.VITE_SPREE_API_URL || 'http://localhost:3000'
+
+const TOKEN_KEY = 'spree_admin_token'
+
+export const adminClient = createAdminClient({
+ baseUrl,
+ jwtToken: localStorage.getItem(TOKEN_KEY) ?? '',
})
diff --git a/packages/admin/src/hooks/use-direct-upload.ts b/packages/admin/src/hooks/use-direct-upload.ts
index bacba18ec4..01d269af40 100644
--- a/packages/admin/src/hooks/use-direct-upload.ts
+++ b/packages/admin/src/hooks/use-direct-upload.ts
@@ -1,7 +1,6 @@
import { useMutation } from '@tanstack/react-query'
import SparkMD5 from 'spark-md5'
-import { spreeClient } from '@/client'
-import { useAuth } from '@/hooks/use-auth'
+import { adminClient } from '@/client'
function computeMD5Checksum(file: File): Promise<string> {
return new Promise((resolve, reject) => {
@@ -41,8 +40,6 @@ interface UploadResult {
}
export function useDirectUpload() {
- const { token } = useAuth()
-
return useMutation({
mutationFn: async (file: File): Promise<UploadResult> => {
const checksum = await computeMD5Checksum(file)
@@ -50,17 +47,14 @@ export function useDirectUpload() {
// Step 1: Get presigned upload URL
let response: { direct_upload: { url: string; headers: Record<string, string> }; signed_id: string }
try {
- response = await spreeClient.admin.directUploads.create(
- {
- blob: {
- filename: file.name,
- byte_size: file.size,
- checksum,
- content_type: file.type || 'application/octet-stream',
- },
+ response = await adminClient.directUploads.create({
+ blob: {
+ filename: file.name,
+ byte_size: file.size,
+ checksum,
+ content_type: file.type || 'application/octet-stream',
},
- { token: token! },
- )
+ })
} catch (err) {
throw new Error(`Presign failed: ${err instanceof Error ? err.message : err}`)
}
diff --git a/packages/admin/src/hooks/use-product-assets.ts b/packages/admin/src/hooks/use-product-assets.ts
index d95cb82c2d..eaf6afa16d 100644
--- a/packages/admin/src/hooks/use-product-assets.ts
+++ b/packages/admin/src/hooks/use-product-assets.ts
@@ -1,25 +1,20 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import { spreeClient } from '@/client'
-import { useAuth } from '@/hooks/use-auth'
+import { adminClient } from '@/client'
export function useProductAssets(productId: string) {
- const { token } = useAuth()
-
return useQuery({
queryKey: ['products', productId, 'assets'],
- queryFn: () =>
- spreeClient.admin.products.assets.list(productId, {}, { token: token! }),
- enabled: !!token && !!productId,
+ queryFn: () => adminClient.products.assets.list(productId),
+ enabled: !!productId,
})
}
export function useCreateProductAsset(productId: string) {
- const { token } = useAuth()
const queryClient = useQueryClient()
return useMutation({
mutationFn: (params: { signed_id: string; alt?: string; position?: number }) =>
- spreeClient.admin.products.assets.create(productId, params, { token: token! }),
+ adminClient.products.assets.create(productId, params),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['products', productId, 'assets'] })
queryClient.invalidateQueries({ queryKey: ['products', productId] })
@@ -28,12 +23,11 @@ export function useCreateProductAsset(productId: string) {
}
export function useUpdateProductAsset(productId: string) {
- const { token } = useAuth()
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ id, ...params }: { id: string; alt?: string; position?: number }) =>
- spreeClient.admin.products.assets.update(productId, id, params, { token: token! }),
+ adminClient.products.assets.update(productId, id, params),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['products', productId, 'assets'] })
},
@@ -41,12 +35,11 @@ export function useUpdateProductAsset(productId: string) {
}
export function useDeleteProductAsset(productId: string) {
- const { token } = useAuth()
const queryClient = useQueryClient()
return useMutation({
mutationFn: (id: string) =>
- spreeClient.admin.products.assets.delete(productId, id, { token: token! }),
+ adminClient.products.assets.delete(productId, id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['products', productId, 'assets'] })
queryClient.invalidateQueries({ queryKey: ['products', productId] })
diff --git a/packages/admin/src/hooks/use-product.ts b/packages/admin/src/hooks/use-product.ts
index 918677b8e4..68918b9ba9 100644
--- a/packages/admin/src/hooks/use-product.ts
+++ b/packages/admin/src/hooks/use-product.ts
@@ -1,38 +1,30 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import { spreeClient } from '@/client'
-import { useAuth } from '@/hooks/use-auth'
+import { adminClient } from '@/client'
export function useProduct(id: string) {
- const { token } = useAuth()
-
return useQuery({
queryKey: ['products', id],
queryFn: () =>
- spreeClient.admin.products.get(
- id,
- {
- expand: [
- 'variants',
- 'images',
- 'option_types',
- 'taxons',
- 'shipping_category',
- 'tax_category',
- ],
- },
- { token: token! },
- ),
- enabled: !!token && !!id,
+ adminClient.products.get(id, {
+ expand: [
+ 'variants',
+ 'images',
+ 'option_types',
+ 'taxons',
+ 'shipping_category',
+ 'tax_category',
+ ],
+ }),
+ enabled: !!id,
})
}
export function useUpdateProduct() {
- const { token } = useAuth()
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ id, ...params }: { id: string } & Record<string, unknown>) =>
- spreeClient.admin.products.update(id, params, { token: token! }),
+ adminClient.products.update(id, params),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({ queryKey: ['products', variables.id] })
queryClient.invalidateQueries({ queryKey: ['products'] })
@@ -41,11 +33,10 @@ export function useUpdateProduct() {
}
export function useDeleteProduct() {
- const { token } = useAuth()
const queryClient = useQueryClient()
return useMutation({
- mutationFn: (id: string) => spreeClient.admin.products.delete(id, { token: token! }),
+ mutationFn: (id: string) => adminClient.products.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['products'] })
},
diff --git a/packages/admin/src/hooks/use-products.ts b/packages/admin/src/hooks/use-products.ts
index 9940842c7a..6f6ad9bca4 100644
--- a/packages/admin/src/hooks/use-products.ts
+++ b/packages/admin/src/hooks/use-products.ts
@@ -1,6 +1,5 @@
import { useQuery } from '@tanstack/react-query'
-import { spreeClient } from '@/client'
-import { useAuth } from '@/hooks/use-auth'
+import { adminClient } from '@/client'
import type { FilterRule } from '@/lib/table-registry'
interface UseProductsParams {
@@ -18,8 +17,6 @@ export function useProducts({
search,
filters = [],
}: UseProductsParams = {}) {
- const { token } = useAuth()
-
return useQuery({
queryKey: ['products', { page, limit, sort, search, filters }],
queryFn: async () => {
@@ -35,8 +32,7 @@ export function useProducts({
params[key] = filter.value
}
- return spreeClient.admin.products.list(params, { token: token! })
+ return adminClient.products.list(params)
},
- enabled: !!token,
})
}
diff --git a/packages/admin/src/hooks/use-shipping-categories.ts b/packages/admin/src/hooks/use-shipping-categories.ts
index 702ed230d6..36a63d21fa 100644
--- a/packages/admin/src/hooks/use-shipping-categories.ts
+++ b/packages/admin/src/hooks/use-shipping-categories.ts
@@ -1,14 +1,10 @@
import { useQuery } from '@tanstack/react-query'
-import { spreeClient } from '@/client'
-import { useAuth } from '@/hooks/use-auth'
+import { adminClient } from '@/client'
export function useShippingCategories() {
- const { token } = useAuth()
-
return useQuery({
queryKey: ['shipping-categories'],
- queryFn: () => spreeClient.admin.shippingCategories.list({}, { token: token! }),
- enabled: !!token,
+ queryFn: () => adminClient.shippingCategories.list(),
staleTime: 1000 * 60 * 5,
})
}
diff --git a/packages/admin/src/hooks/use-tax-categories.ts b/packages/admin/src/hooks/use-tax-categories.ts
index e834222f1b..c46815b6c7 100644
--- a/packages/admin/src/hooks/use-tax-categories.ts
+++ b/packages/admin/src/hooks/use-tax-categories.ts
@@ -1,14 +1,10 @@
import { useQuery } from '@tanstack/react-query'
-import { spreeClient } from '@/client'
-import { useAuth } from '@/hooks/use-auth'
+import { adminClient } from '@/client'
export function useTaxCategories() {
- const { token } = useAuth()
-
return useQuery({
queryKey: ['tax-categories'],
- queryFn: () => spreeClient.admin.taxCategories.list({}, { token: token! }),
- enabled: !!token,
+ queryFn: () => adminClient.taxCategories.list(),
staleTime: 1000 * 60 * 5,
})
}
diff --git a/packages/admin/src/hooks/use-taxons.ts b/packages/admin/src/hooks/use-taxons.ts
index e7f1f1b8b4..f62c1bdb3d 100644
--- a/packages/admin/src/hooks/use-taxons.ts
+++ b/packages/admin/src/hooks/use-taxons.ts
@@ -1,18 +1,11 @@
import { useQuery } from '@tanstack/react-query'
-import { spreeClient } from '@/client'
-import { useAuth } from '@/hooks/use-auth'
+import { adminClient } from '@/client'
export function useTaxons() {
- const { token } = useAuth()
-
return useQuery({
queryKey: ['taxons'],
queryFn: () =>
- spreeClient.admin.taxons.list(
- { limit: 100, expand: ['taxonomy'] },
- { token: token! },
- ),
- enabled: !!token,
+ adminClient.taxons.list({ limit: 100, expand: ['taxonomy'] }),
staleTime: 1000 * 60 * 5,
})
}
diff --git a/packages/admin/src/providers/auth-provider.tsx b/packages/admin/src/providers/auth-provider.tsx
index b4826abe11..d46aace296 100644
--- a/packages/admin/src/providers/auth-provider.tsx
+++ b/packages/admin/src/providers/auth-provider.tsx
@@ -1,5 +1,5 @@
import { createContext, type ReactNode, useCallback, useEffect, useState } from 'react'
-import { spreeClient } from '@/client'
+import { adminClient } from '@/client'
interface AuthUser {
id: string
@@ -33,7 +33,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const login = useCallback(async (email: string, password: string) => {
setIsLoading(true)
try {
- const response = await spreeClient.admin.auth.login({ email, password })
+ const response = await adminClient.auth.login({ email, password })
+ adminClient.setToken(response.token)
setToken(response.token)
setUser(response.user)
localStorage.setItem(TOKEN_KEY, response.token)
@@ -54,9 +55,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
useEffect(() => {
if (!token) return
- spreeClient.admin.auth
- .refresh({ token })
+ adminClient.auth
+ .refresh()
.then((response) => {
+ adminClient.setToken(response.token)
setToken(response.token)
localStorage.setItem(TOKEN_KEY, response.token)
})
diff --git a/packages/admin/src/providers/store-provider.tsx b/packages/admin/src/providers/store-provider.tsx
new file mode 100644
index 0000000000..22ef957ef7
--- /dev/null
+++ b/packages/admin/src/providers/store-provider.tsx
@@ -0,0 +1,47 @@
+import { createContext, type ReactNode, useCallback, useContext, useEffect, useState } from 'react'
+import type { Store } from '@spree/admin-sdk'
+import { adminClient } from '@/client'
+
+interface StoreContextValue {
+ store: Store | null
+ storeId: string
+ isLoading: boolean
+ refetch: () => Promise<void>
+}
+
+const StoreContext = createContext<StoreContextValue | null>(null)
+
+export function StoreProvider({ storeId, children }: { storeId: string; children: ReactNode }) {
+ const [store, setStore] = useState<Store | null>(null)
+ const [isLoading, setIsLoading] = useState(true)
+
+ const fetchStore = useCallback(async () => {
+ setIsLoading(true)
+ try {
+ const data = await adminClient.store.get()
+ setStore(data)
+ } catch {
+ setStore(null)
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ useEffect(() => {
+ fetchStore()
+ }, [storeId, fetchStore])
+
+ return (
+ <StoreContext.Provider value={{ store, storeId, isLoading, refetch: fetchStore }}>
+ {children}
+ </StoreContext.Provider>
+ )
+}
+
+export function useStore(): StoreContextValue {
+ const context = useContext(StoreContext)
+ if (!context) {
+ throw new Error('useStore must be used within a StoreProvider')
+ }
+ return context
+}
diff --git a/packages/admin/src/routeTree.gen.ts b/packages/admin/src/routeTree.gen.ts
index 1fd4f6babb..b9121ac6d0 100644
--- a/packages/admin/src/routeTree.gen.ts
+++ b/packages/admin/src/routeTree.gen.ts
@@ -12,11 +12,18 @@ import { Route as rootRouteImport } from './routes/__root'
import { Route as LoginRouteImport } from './routes/login'
import { Route as AuthenticatedRouteImport } from './routes/_authenticated'
import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index'
+import { Route as AuthenticatedStoreIdRouteImport } from './routes/_authenticated/$storeId'
import { Route as AuthenticatedProductsIndexRouteImport } from './routes/_authenticated/products/index'
import { Route as AuthenticatedOrdersIndexRouteImport } from './routes/_authenticated/orders/index'
+import { Route as AuthenticatedStoreIdIndexRouteImport } from './routes/_authenticated/$storeId/index'
import { Route as AuthenticatedProductsProductIdRouteImport } from './routes/_authenticated/products/$productId'
import { Route as AuthenticatedOrdersDraftsRouteImport } from './routes/_authenticated/orders/drafts'
import { Route as AuthenticatedOrdersOrderIdRouteImport } from './routes/_authenticated/orders/$orderId'
+import { Route as AuthenticatedStoreIdProductsIndexRouteImport } from './routes/_authenticated/$storeId/products/index'
+import { Route as AuthenticatedStoreIdOrdersIndexRouteImport } from './routes/_authenticated/$storeId/orders/index'
+import { Route as AuthenticatedStoreIdProductsProductIdRouteImport } from './routes/_authenticated/$storeId/products/$productId'
+import { Route as AuthenticatedStoreIdOrdersDraftsRouteImport } from './routes/_authenticated/$storeId/orders/drafts'
+import { Route as AuthenticatedStoreIdOrdersOrderIdRouteImport } from './routes/_authenticated/$storeId/orders/$orderId'
const LoginRoute = LoginRouteImport.update({
id: '/login',
@@ -32,6 +39,11 @@ const AuthenticatedIndexRoute = AuthenticatedIndexRouteImport.update({
path: '/',
getParentRoute: () => AuthenticatedRoute,
} as any)
+const AuthenticatedStoreIdRoute = AuthenticatedStoreIdRouteImport.update({
+ id: '/$storeId',
+ path: '/$storeId',
+ getParentRoute: () => AuthenticatedRoute,
+} as any)
const AuthenticatedProductsIndexRoute =
AuthenticatedProductsIndexRouteImport.update({
id: '/products/',
@@ -44,6 +56,12 @@ const AuthenticatedOrdersIndexRoute =
path: '/orders/',
getParentRoute: () => AuthenticatedRoute,
} as any)
+const AuthenticatedStoreIdIndexRoute =
+ AuthenticatedStoreIdIndexRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => AuthenticatedStoreIdRoute,
+ } as any)
const AuthenticatedProductsProductIdRoute =
AuthenticatedProductsProductIdRouteImport.update({
id: '/products/$productId',
@@ -62,15 +80,52 @@ const AuthenticatedOrdersOrderIdRoute =
path: '/orders/$orderId',
getParentRoute: () => AuthenticatedRoute,
} as any)
+const AuthenticatedStoreIdProductsIndexRoute =
+ AuthenticatedStoreIdProductsIndexRouteImport.update({
+ id: '/products/',
+ path: '/products/',
+ getParentRoute: () => AuthenticatedStoreIdRoute,
+ } as any)
+const AuthenticatedStoreIdOrdersIndexRoute =
+ AuthenticatedStoreIdOrdersIndexRouteImport.update({
+ id: '/orders/',
+ path: '/orders/',
+ getParentRoute: () => AuthenticatedStoreIdRoute,
+ } as any)
+const AuthenticatedStoreIdProductsProductIdRoute =
+ AuthenticatedStoreIdProductsProductIdRouteImport.update({
+ id: '/products/$productId',
+ path: '/products/$productId',
+ getParentRoute: () => AuthenticatedStoreIdRoute,
+ } as any)
+const AuthenticatedStoreIdOrdersDraftsRoute =
+ AuthenticatedStoreIdOrdersDraftsRouteImport.update({
+ id: '/orders/drafts',
+ path: '/orders/drafts',
+ getParentRoute: () => AuthenticatedStoreIdRoute,
+ } as any)
+const AuthenticatedStoreIdOrdersOrderIdRoute =
+ AuthenticatedStoreIdOrdersOrderIdRouteImport.update({
+ id: '/orders/$orderId',
+ path: '/orders/$orderId',
+ getParentRoute: () => AuthenticatedStoreIdRoute,
+ } as any)
export interface FileRoutesByFullPath {
'/': typeof AuthenticatedIndexRoute
'/login': typeof LoginRoute
+ '/$storeId': typeof AuthenticatedStoreIdRouteWithChildren
'/orders/$orderId': typeof AuthenticatedOrdersOrderIdRoute
'/orders/drafts': typeof AuthenticatedOrdersDraftsRoute
'/products/$productId': typeof AuthenticatedProductsProductIdRoute
+ '/$storeId/': typeof AuthenticatedStoreIdIndexRoute
'/orders/': typeof AuthenticatedOrdersIndexRoute
'/products/': typeof AuthenticatedProductsIndexRoute
+ '/$storeId/orders/$orderId': typeof AuthenticatedStoreIdOrdersOrderIdRoute
+ '/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute
+ '/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute
+ '/$storeId/orders/': typeof AuthenticatedStoreIdOrdersIndexRoute
+ '/$storeId/products/': typeof AuthenticatedStoreIdProductsIndexRoute
}
export interface FileRoutesByTo {
'/login': typeof LoginRoute
@@ -78,30 +133,50 @@ export interface FileRoutesByTo {
'/orders/$orderId': typeof AuthenticatedOrdersOrderIdRoute
'/orders/drafts': typeof AuthenticatedOrdersDraftsRoute
'/products/$productId': typeof AuthenticatedProductsProductIdRoute
+ '/$storeId': typeof AuthenticatedStoreIdIndexRoute
'/orders': typeof AuthenticatedOrdersIndexRoute
'/products': typeof AuthenticatedProductsIndexRoute
+ '/$storeId/orders/$orderId': typeof AuthenticatedStoreIdOrdersOrderIdRoute
+ '/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute
+ '/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute
+ '/$storeId/orders': typeof AuthenticatedStoreIdOrdersIndexRoute
+ '/$storeId/products': typeof AuthenticatedStoreIdProductsIndexRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_authenticated': typeof AuthenticatedRouteWithChildren
'/login': typeof LoginRoute
+ '/_authenticated/$storeId': typeof AuthenticatedStoreIdRouteWithChildren
'/_authenticated/': typeof AuthenticatedIndexRoute
'/_authenticated/orders/$orderId': typeof AuthenticatedOrdersOrderIdRoute
'/_authenticated/orders/drafts': typeof AuthenticatedOrdersDraftsRoute
'/_authenticated/products/$productId': typeof AuthenticatedProductsProductIdRoute
+ '/_authenticated/$storeId/': typeof AuthenticatedStoreIdIndexRoute
'/_authenticated/orders/': typeof AuthenticatedOrdersIndexRoute
'/_authenticated/products/': typeof AuthenticatedProductsIndexRoute
+ '/_authenticated/$storeId/orders/$orderId': typeof AuthenticatedStoreIdOrdersOrderIdRoute
+ '/_authenticated/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute
+ '/_authenticated/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute
+ '/_authenticated/$storeId/orders/': typeof AuthenticatedStoreIdOrdersIndexRoute
+ '/_authenticated/$storeId/products/': typeof AuthenticatedStoreIdProductsIndexRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths:
| '/'
| '/login'
+ | '/$storeId'
| '/orders/$orderId'
| '/orders/drafts'
| '/products/$productId'
+ | '/$storeId/'
| '/orders/'
| '/products/'
+ | '/$storeId/orders/$orderId'
+ | '/$storeId/orders/drafts'
+ | '/$storeId/products/$productId'
+ | '/$storeId/orders/'
+ | '/$storeId/products/'
fileRoutesByTo: FileRoutesByTo
to:
| '/login'
@@ -109,18 +184,31 @@ export interface FileRouteTypes {
| '/orders/$orderId'
| '/orders/drafts'
| '/products/$productId'
+ | '/$storeId'
| '/orders'
| '/products'
+ | '/$storeId/orders/$orderId'
+ | '/$storeId/orders/drafts'
+ | '/$storeId/products/$productId'
+ | '/$storeId/orders'
+ | '/$storeId/products'
id:
| '__root__'
| '/_authenticated'
| '/login'
+ | '/_authenticated/$storeId'
| '/_authenticated/'
| '/_authenticated/orders/$orderId'
| '/_authenticated/orders/drafts'
| '/_authenticated/products/$productId'
+ | '/_authenticated/$storeId/'
| '/_authenticated/orders/'
| '/_authenticated/products/'
+ | '/_authenticated/$storeId/orders/$orderId'
+ | '/_authenticated/$storeId/orders/drafts'
+ | '/_authenticated/$storeId/products/$productId'
+ | '/_authenticated/$storeId/orders/'
+ | '/_authenticated/$storeId/products/'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
@@ -151,6 +239,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedIndexRouteImport
parentRoute: typeof AuthenticatedRoute
}
+ '/_authenticated/$storeId': {
+ id: '/_authenticated/$storeId'
+ path: '/$storeId'
+ fullPath: '/$storeId'
+ preLoaderRoute: typeof AuthenticatedStoreIdRouteImport
+ parentRoute: typeof AuthenticatedRoute
+ }
'/_authenticated/products/': {
id: '/_authenticated/products/'
path: '/products'
@@ -165,6 +260,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedOrdersIndexRouteImport
parentRoute: typeof AuthenticatedRoute
}
+ '/_authenticated/$storeId/': {
+ id: '/_authenticated/$storeId/'
+ path: '/'
+ fullPath: '/$storeId/'
+ preLoaderRoute: typeof AuthenticatedStoreIdIndexRouteImport
+ parentRoute: typeof AuthenticatedStoreIdRoute
+ }
'/_authenticated/products/$productId': {
id: '/_authenticated/products/$productId'
path: '/products/$productId'
@@ -186,10 +288,70 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedOrdersOrderIdRouteImport
parentRoute: typeof AuthenticatedRoute
}
+ '/_authenticated/$storeId/products/': {
+ id: '/_authenticated/$storeId/products/'
+ path: '/products'
+ fullPath: '/$storeId/products/'
+ preLoaderRoute: typeof AuthenticatedStoreIdProductsIndexRouteImport
+ parentRoute: typeof AuthenticatedStoreIdRoute
+ }
+ '/_authenticated/$storeId/orders/': {
+ id: '/_authenticated/$storeId/orders/'
+ path: '/orders'
+ fullPath: '/$storeId/orders/'
+ preLoaderRoute: typeof AuthenticatedStoreIdOrdersIndexRouteImport
+ parentRoute: typeof AuthenticatedStoreIdRoute
+ }
+ '/_authenticated/$storeId/products/$productId': {
+ id: '/_authenticated/$storeId/products/$productId'
+ path: '/products/$productId'
+ fullPath: '/$storeId/products/$productId'
+ preLoaderRoute: typeof AuthenticatedStoreIdProductsProductIdRouteImport
+ parentRoute: typeof AuthenticatedStoreIdRoute
+ }
+ '/_authenticated/$storeId/orders/drafts': {
+ id: '/_authenticated/$storeId/orders/drafts'
+ path: '/orders/drafts'
+ fullPath: '/$storeId/orders/drafts'
+ preLoaderRoute: typeof AuthenticatedStoreIdOrdersDraftsRouteImport
+ parentRoute: typeof AuthenticatedStoreIdRoute
+ }
+ '/_authenticated/$storeId/orders/$orderId': {
+ id: '/_authenticated/$storeId/orders/$orderId'
+ path: '/orders/$orderId'
+ fullPath: '/$storeId/orders/$orderId'
+ preLoaderRoute: typeof AuthenticatedStoreIdOrdersOrderIdRouteImport
+ parentRoute: typeof AuthenticatedStoreIdRoute
+ }
}
}
+interface AuthenticatedStoreIdRouteChildren {
+ AuthenticatedStoreIdIndexRoute: typeof AuthenticatedStoreIdIndexRoute
+ AuthenticatedStoreIdOrdersOrderIdRoute: typeof AuthenticatedStoreIdOrdersOrderIdRoute
+ AuthenticatedStoreIdOrdersDraftsRoute: typeof AuthenticatedStoreIdOrdersDraftsRoute
+ AuthenticatedStoreIdProductsProductIdRoute: typeof AuthenticatedStoreIdProductsProductIdRoute
+ AuthenticatedStoreIdOrdersIndexRoute: typeof AuthenticatedStoreIdOrdersIndexRoute
+ AuthenticatedStoreIdProductsIndexRoute: typeof AuthenticatedStoreIdProductsIndexRoute
+}
+
+const AuthenticatedStoreIdRouteChildren: AuthenticatedStoreIdRouteChildren = {
+ AuthenticatedStoreIdIndexRoute: AuthenticatedStoreIdIndexRoute,
+ AuthenticatedStoreIdOrdersOrderIdRoute:
+ AuthenticatedStoreIdOrdersOrderIdRoute,
+ AuthenticatedStoreIdOrdersDraftsRoute: AuthenticatedStoreIdOrdersDraftsRoute,
+ AuthenticatedStoreIdProductsProductIdRoute:
+ AuthenticatedStoreIdProductsProductIdRoute,
+ AuthenticatedStoreIdOrdersIndexRoute: AuthenticatedStoreIdOrdersIndexRoute,
+ AuthenticatedStoreIdProductsIndexRoute:
+ AuthenticatedStoreIdProductsIndexRoute,
+}
+
+const AuthenticatedStoreIdRouteWithChildren =
+ AuthenticatedStoreIdRoute._addFileChildren(AuthenticatedStoreIdRouteChildren)
+
interface AuthenticatedRouteChildren {
+ AuthenticatedStoreIdRoute: typeof AuthenticatedStoreIdRouteWithChildren
AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute
AuthenticatedOrdersOrderIdRoute: typeof AuthenticatedOrdersOrderIdRoute
AuthenticatedOrdersDraftsRoute: typeof AuthenticatedOrdersDraftsRoute
@@ -199,6 +361,7 @@ interface AuthenticatedRouteChildren {
}
const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
+ AuthenticatedStoreIdRoute: AuthenticatedStoreIdRouteWithChildren,
AuthenticatedIndexRoute: AuthenticatedIndexRoute,
AuthenticatedOrdersOrderIdRoute: AuthenticatedOrdersOrderIdRoute,
AuthenticatedOrdersDraftsRoute: AuthenticatedOrdersDraftsRoute,
diff --git a/packages/admin/src/routes/_authenticated/$storeId.tsx b/packages/admin/src/routes/_authenticated/$storeId.tsx
new file mode 100644
index 0000000000..144950c499
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId.tsx
@@ -0,0 +1,22 @@
+import { createFileRoute, Outlet } from '@tanstack/react-router'
+import { useEffect } from 'react'
+import { adminClient } from '@/client'
+import { StoreProvider } from '@/providers/store-provider'
+
+export const Route = createFileRoute('/_authenticated/$storeId')({
+ component: StoreLayout,
+})
+
+function StoreLayout() {
+ const { storeId } = Route.useParams()
+
+ useEffect(() => {
+ adminClient.setStore(storeId)
+ }, [storeId])
+
+ return (
+ <StoreProvider storeId={storeId}>
+ <Outlet />
+ </StoreProvider>
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/index.tsx
new file mode 100644
index 0000000000..d0e191fe2d
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/index.tsx
@@ -0,0 +1,14 @@
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/_authenticated/$storeId/')({
+ component: DashboardPage,
+})
+
+function DashboardPage() {
+ return (
+ <div className="space-y-4">
+ <h1 className="text-2xl font-bold">Dashboard</h1>
+ <p className="text-muted-foreground">Welcome to the Spree Admin dashboard.</p>
+ </div>
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx b/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx
new file mode 100644
index 0000000000..ea843fb9dd
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx
@@ -0,0 +1,1409 @@
+import type { Address, Order } from '@spree/admin-sdk'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { createFileRoute, Link } from '@tanstack/react-router'
+import {
+ ArrowLeftIcon,
+ CreditCardIcon,
+ EllipsisVerticalIcon,
+ ExternalLinkIcon,
+ MailIcon,
+ MapPinIcon,
+ PackageIcon,
+ PencilIcon,
+ PlusIcon,
+ ShoppingCartIcon,
+ SlidersHorizontalIcon,
+ TrashIcon,
+ TruckIcon,
+ XCircleIcon,
+} from 'lucide-react'
+import { type FormEvent, useState } from 'react'
+import { adminClient } from '@/client'
+import { Badge, StatusBadge } from '@/components/ui/badge'
+import { Button } from '@/components/ui/button'
+import { Card, CardAction, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Input } from '@/components/ui/input'
+import { Separator } from '@/components/ui/separator'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Textarea } from '@/components/ui/textarea'
+import { useAuth } from '@/hooks/use-auth'
+import { cn } from '@/lib/utils'
+
+export const Route = createFileRoute('/_authenticated/$storeId/orders/$orderId')({
+ component: OrderDetailPage,
+})
+
+// ---------------------------------------------------------------------------
+// Data hooks
+// ---------------------------------------------------------------------------
+
+function useOrder(orderId: string) {
+ const { isAuthenticated } = useAuth()
+ return useQuery({
+ queryKey: ['order', orderId],
+ queryFn: () =>
+ adminClient.orders.get(orderId, {
+ expand: [
+ 'line_items',
+ 'shipments',
+ 'shipments.shipping_method',
+ 'shipments.stock_location',
+ 'payments',
+ 'payments.payment_method',
+ 'bill_address',
+ 'ship_address',
+ 'user',
+ 'adjustments',
+ ],
+ }),
+ enabled: isAuthenticated,
+ })
+}
+
+/** Wrapper for mutations that invalidate the order query on success */
+function useOrderMutation<TParams>(
+ orderId: string,
+ mutationFn: (params: TParams) => Promise<unknown>,
+) {
+ const queryClient = useQueryClient()
+ return useMutation({
+ mutationFn,
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ['order', orderId] }),
+ })
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function formatDate(iso: string | null) {
+ if (!iso) return '—'
+ return new Date(iso).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ })
+}
+
+function timeAgo(iso: string | null) {
+ if (!iso) return ''
+ const diff = Date.now() - new Date(iso).getTime()
+ const minutes = Math.floor(diff / 60000)
+ if (minutes < 60) return `${minutes}m ago`
+ const hours = Math.floor(minutes / 60)
+ if (hours < 24) return `${hours}h ago`
+ const days = Math.floor(hours / 24)
+ return `${days}d ago`
+}
+
+// ---------------------------------------------------------------------------
+// Page
+// ---------------------------------------------------------------------------
+
+function OrderDetailPage() {
+ const { orderId } = Route.useParams()
+ const { data: order, isLoading, error } = useOrder(orderId)
+
+ if (isLoading) return <OrderSkeleton />
+ if (error || !order) return <p className="text-destructive">Failed to load order {orderId}.</p>
+
+ return (
+ <div className="flex flex-col gap-6">
+ <OrderHeader order={order} />
+
+ <div className="grid grid-cols-12 gap-6">
+ {/* Main content */}
+ <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">
+ <LineItemsCard order={order} />
+ <ShipmentsCard order={order} />
+ <PaymentsCard order={order} />
+ <AdjustmentsCard order={order} />
+ <OrderSummaryCard order={order} />
+ </div>
+
+ {/* Sidebar */}
+ <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">
+ <CustomerCard order={order} />
+ <SpecialInstructionsCard order={order} />
+ <InternalNoteCard order={order} />
+ </div>
+ </div>
+ </div>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Header
+// ---------------------------------------------------------------------------
+
+function OrderHeader({ order }: { order: Order }) {
+ const { orderId, storeId } = Route.useParams()
+
+ const backPath = order.completed_at ? '/$storeId/orders' : '/$storeId/orders/drafts'
+
+ const cancelMutation = useOrderMutation(orderId, () =>
+ adminClient.orders.cancel(orderId, {}),
+ )
+ const resendMutation = useOrderMutation(orderId, () =>
+ adminClient.orders.resendConfirmation(orderId, {}),
+ )
+
+ return (
+ <div className="flex items-center gap-3">
+ <Link
+ to={backPath}
+ params={{ storeId }}
+ search={{ filters: [], columns: [] }}
+ className="inline-flex items-center justify-center rounded-lg p-1.5 text-muted-foreground hover:bg-gray-200/50 hover:text-foreground transition-colors"
+ >
+ <ArrowLeftIcon className="size-5" />
+ </Link>
+
+ <h1 className="text-2xl font-medium">{order.number}</h1>
+
+ {order.payment_state && <StatusBadge status={order.payment_state} />}
+ {order.shipment_state && <StatusBadge status={order.shipment_state} />}
+
+ {order.completed_at && (
+ <span className="text-sm text-muted-foreground">
+ Completed {timeAgo(order.completed_at)}
+ </span>
+ )}
+
+ <div className="ml-auto">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="icon-sm">
+ <EllipsisVerticalIcon className="size-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {order.completed_at && (
+ <>
+ <DropdownMenuItem>
+ <ExternalLinkIcon className="size-4" />
+ Preview Order
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => resendMutation.mutate(undefined)}
+ disabled={resendMutation.isPending}
+ >
+ <MailIcon className="size-4" />
+ Resend Confirmation
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ {order.state !== 'canceled' && (
+ <DropdownMenuItem
+ className="text-destructive focus:text-destructive"
+ onClick={() => {
+ if (window.confirm('Are you sure you want to cancel this order?')) {
+ cancelMutation.mutate(undefined)
+ }
+ }}
+ disabled={cancelMutation.isPending}
+ >
+ <XCircleIcon className="size-4" />
+ Cancel Order
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Line Items
+// ---------------------------------------------------------------------------
+
+function AddLineItemDialog({
+ orderId,
+ open,
+ onOpenChange,
+}: {
+ orderId: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+
+ const mutation = useOrderMutation(orderId, (params: { variant_id: string; quantity: number }) =>
+ adminClient.orders.lineItems.create(orderId, params),
+ )
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ mutation.mutate(
+ { variant_id: fd.get('variant_id') as string, quantity: Number(fd.get('quantity')) || 1 },
+ { onSuccess: () => onOpenChange(false) },
+ )
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Add Line Item</DialogTitle>
+ <DialogDescription>Add a product variant to this order.</DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit}>
+ <DialogBody>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="variant_id">Variant ID</FieldLabel>
+ <Input id="variant_id" name="variant_id" placeholder="variant_xxx" required />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="quantity">Quantity</FieldLabel>
+ <Input id="quantity" name="quantity" type="number" min={1} defaultValue={1} />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending ? 'Adding…' : 'Add Item'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function EditQuantityDialog({
+ orderId,
+ lineItemId,
+ currentQuantity,
+ open,
+ onOpenChange,
+}: {
+ orderId: string
+ lineItemId: string
+ currentQuantity: number
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+
+ const mutation = useOrderMutation(orderId, (params: { quantity: number }) =>
+ adminClient.orders.lineItems.update(orderId, lineItemId, params),
+ )
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ mutation.mutate(
+ { quantity: Number(fd.get('quantity')) || 1 },
+ { onSuccess: () => onOpenChange(false) },
+ )
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Edit Quantity</DialogTitle>
+ <DialogDescription>Update the quantity for this line item.</DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit}>
+ <DialogBody>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="edit-quantity">Quantity</FieldLabel>
+ <Input
+ id="edit-quantity"
+ name="quantity"
+ type="number"
+ min={1}
+ defaultValue={currentQuantity}
+ />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending ? 'Saving…' : 'Save'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function LineItemsCard({ order }: { order: Order }) {
+ const { orderId } = Route.useParams()
+
+ const items = order.line_items ?? []
+ const [addOpen, setAddOpen] = useState(false)
+ const [editItem, setEditItem] = useState<{ id: string; quantity: number } | null>(null)
+
+ const deleteMutation = useOrderMutation(orderId, (lineItemId: string) =>
+ adminClient.orders.lineItems.delete(orderId, lineItemId),
+ )
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <ShoppingCartIcon className="size-4" />
+ Line Items
+ </CardTitle>
+ <CardAction className="flex items-center gap-2">
+ {items.length > 0 && <Badge variant="info">{items.length}</Badge>}
+ <Button size="sm" variant="secondary" onClick={() => setAddOpen(true)}>
+ <PlusIcon data-icon="inline-start" />
+ Add Item
+ </Button>
+ </CardAction>
+ </CardHeader>
+ {items.length > 0 ? (
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b bg-muted/50 text-muted-foreground">
+ <th className="p-3 pl-5 text-left font-normal">Item</th>
+ <th className="p-3 text-right font-normal">Price</th>
+ <th className="p-3 text-right font-normal">Qty</th>
+ <th className="p-3 text-right font-normal">Tax</th>
+ <th className="p-3 text-right font-normal">Discount</th>
+ <th className="p-3 text-right font-normal">Total</th>
+ <th className="p-3 pr-5 w-10" />
+ </tr>
+ </thead>
+ <tbody>
+ {items.map((item) => (
+ <tr key={item.id} className="border-b last:border-b-0">
+ <td className="p-3 pl-5">
+ <div className="flex items-center gap-3">
+ {item.thumbnail_url ? (
+ <img
+ src={item.thumbnail_url}
+ alt={item.name}
+ className="size-10 rounded-lg border object-cover"
+ />
+ ) : (
+ <div className="flex size-10 items-center justify-center rounded-lg border bg-muted">
+ <PackageIcon className="size-4 text-muted-foreground" />
+ </div>
+ )}
+ <div className="min-w-0">
+ <div className="truncate font-medium">{item.name}</div>
+ {item.options_text && (
+ <div className="truncate text-xs text-muted-foreground">
+ {item.options_text}
+ </div>
+ )}
+ </div>
+ </div>
+ </td>
+ <td className="p-3 text-right whitespace-nowrap">{item.display_price}</td>
+ <td className="p-3 text-right">{item.quantity}</td>
+ <td className="p-3 text-right whitespace-nowrap">
+ {item.display_additional_tax_total}
+ </td>
+ <td className="p-3 text-right whitespace-nowrap">
+ {Number.parseFloat(item.promo_total) !== 0 ? item.display_promo_total : '—'}
+ </td>
+ <td className="p-3 text-right font-medium whitespace-nowrap">
+ {item.display_total}
+ </td>
+ <td className="p-3 pr-5">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-xs">
+ <EllipsisVerticalIcon className="size-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => setEditItem({ id: item.id, quantity: item.quantity })}
+ >
+ <PencilIcon className="size-4" />
+ Edit Quantity
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className="text-destructive focus:text-destructive"
+ onClick={() => {
+ if (window.confirm('Remove this item from the order?')) {
+ deleteMutation.mutate(item.id)
+ }
+ }}
+ >
+ <TrashIcon className="size-4" />
+ Remove
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ) : (
+ <CardContent>
+ <p className="text-center text-muted-foreground py-8">No line items</p>
+ </CardContent>
+ )}
+ </Card>
+
+ <AddLineItemDialog orderId={orderId} open={addOpen} onOpenChange={setAddOpen} />
+
+ {editItem && (
+ <EditQuantityDialog
+ orderId={orderId}
+ lineItemId={editItem.id}
+ currentQuantity={editItem.quantity}
+ open={!!editItem}
+ onOpenChange={(open) => !open && setEditItem(null)}
+ />
+ )}
+ </>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Shipments
+// ---------------------------------------------------------------------------
+
+function EditTrackingDialog({
+ orderId,
+ shipmentId,
+ currentTracking,
+ open,
+ onOpenChange,
+}: {
+ orderId: string
+ shipmentId: string
+ currentTracking: string | null
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+
+ const mutation = useOrderMutation(orderId, (params: { tracking: string }) =>
+ adminClient.orders.shipments.update(orderId, shipmentId, params),
+ )
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ mutation.mutate(
+ { tracking: fd.get('tracking') as string },
+ { onSuccess: () => onOpenChange(false) },
+ )
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Edit Tracking</DialogTitle>
+ <DialogDescription>Update the tracking number for this shipment.</DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit}>
+ <DialogBody>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="tracking">Tracking Number</FieldLabel>
+ <Input id="tracking" name="tracking" defaultValue={currentTracking ?? ''} />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending ? 'Saving…' : 'Save'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function ShipmentsCard({ order }: { order: Order }) {
+ const { orderId } = Route.useParams()
+
+ const shipments = order.shipments ?? []
+ const [editTracking, setEditTracking] = useState<{
+ id: string
+ tracking: string | null
+ } | null>(null)
+
+ const shipMutation = useOrderMutation(orderId, (shipmentId: string) =>
+ adminClient.orders.shipments.ship(orderId, shipmentId, {}),
+ )
+ const cancelShipmentMutation = useOrderMutation(orderId, (shipmentId: string) =>
+ adminClient.orders.shipments.cancel(orderId, shipmentId, {}),
+ )
+
+ if (shipments.length === 0) return null
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <TruckIcon className="size-4" />
+ Shipments
+ </CardTitle>
+ <CardAction className="flex items-center gap-2">
+ <Badge variant="info">{shipments.length}</Badge>
+ {order.shipment_state && <StatusBadge status={order.shipment_state} />}
+ </CardAction>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ {shipments.map((shipment) => (
+ <div key={shipment.id} className="rounded-lg border p-4 flex flex-col gap-3">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <StatusBadge status={shipment.state} />
+ <span className="text-sm font-medium">{shipment.number}</span>
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-xs">
+ <EllipsisVerticalIcon className="size-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() =>
+ setEditTracking({ id: shipment.id, tracking: shipment.tracking })
+ }
+ >
+ <PencilIcon className="size-4" />
+ {shipment.tracking ? 'Edit Tracking' : 'Add Tracking'}
+ </DropdownMenuItem>
+ {shipment.state === 'ready' && (
+ <DropdownMenuItem
+ onClick={() => {
+ if (window.confirm('Ship this shipment?')) {
+ shipMutation.mutate(shipment.id)
+ }
+ }}
+ >
+ <TruckIcon className="size-4" />
+ Ship
+ </DropdownMenuItem>
+ )}
+ {['pending', 'ready'].includes(shipment.state) && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className="text-destructive focus:text-destructive"
+ onClick={() => {
+ if (window.confirm('Cancel this shipment?')) {
+ cancelShipmentMutation.mutate(shipment.id)
+ }
+ }}
+ >
+ <XCircleIcon className="size-4" />
+ Cancel Shipment
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ {shipment.shipping_method && (
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted-foreground">{shipment.shipping_method.name}</span>
+ <span>{shipment.display_cost}</span>
+ </div>
+ )}
+
+ {shipment.stock_location && (
+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <MapPinIcon className="size-3" />
+ {shipment.stock_location.name}
+ </div>
+ )}
+
+ {shipment.tracking && (
+ <div className="text-sm">
+ <span className="text-muted-foreground">Tracking: </span>
+ {shipment.tracking_url ? (
+ <a
+ href={shipment.tracking_url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-600 hover:underline"
+ >
+ {shipment.tracking}
+ </a>
+ ) : (
+ <span>{shipment.tracking}</span>
+ )}
+ </div>
+ )}
+
+ {shipment.shipped_at && (
+ <span className="text-xs text-muted-foreground">
+ Shipped {timeAgo(shipment.shipped_at)}
+ </span>
+ )}
+ </div>
+ ))}
+ </CardContent>
+ </Card>
+
+ {editTracking && (
+ <EditTrackingDialog
+ orderId={orderId}
+ shipmentId={editTracking.id}
+ currentTracking={editTracking.tracking}
+ open={!!editTracking}
+ onOpenChange={(open) => !open && setEditTracking(null)}
+ />
+ )}
+ </>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Payments
+// ---------------------------------------------------------------------------
+
+function PaymentsCard({ order }: { order: Order }) {
+ const { orderId } = Route.useParams()
+
+ const payments = order.payments ?? []
+
+ const captureMutation = useOrderMutation(orderId, (paymentId: string) =>
+ adminClient.orders.payments.capture(orderId, paymentId, {}),
+ )
+ const voidMutation = useOrderMutation(orderId, (paymentId: string) =>
+ adminClient.orders.payments.void(orderId, paymentId, {}),
+ )
+
+ if (payments.length === 0) return null
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <CreditCardIcon className="size-4" />
+ Payments
+ </CardTitle>
+ <CardAction className="flex items-center gap-2">
+ <Badge variant="info">{payments.length}</Badge>
+ {order.payment_state && <StatusBadge status={order.payment_state} />}
+ </CardAction>
+ </CardHeader>
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b bg-muted/50 text-muted-foreground">
+ <th className="p-3 pl-5 text-left font-normal">Number</th>
+ <th className="p-3 text-left font-normal">Method</th>
+ <th className="p-3 text-left font-normal">State</th>
+ <th className="p-3 text-right font-normal">Amount</th>
+ <th className="p-3 pr-5 w-10" />
+ </tr>
+ </thead>
+ <tbody>
+ {payments.map((payment) => (
+ <tr key={payment.id} className="border-b last:border-b-0">
+ <td className="p-3 pl-5 font-medium">{payment.number}</td>
+ <td className="p-3 text-muted-foreground">{payment.payment_method?.name ?? '—'}</td>
+ <td className="p-3">
+ <StatusBadge status={payment.state} />
+ </td>
+ <td className="p-3 text-right font-medium whitespace-nowrap">
+ {payment.display_amount}
+ </td>
+ <td className="p-3 pr-5">
+ {(payment.state === 'checkout' ||
+ payment.state === 'pending' ||
+ payment.state === 'completed') && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-xs">
+ <EllipsisVerticalIcon className="size-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {(payment.state === 'checkout' || payment.state === 'pending') && (
+ <DropdownMenuItem
+ onClick={() => {
+ if (window.confirm('Capture this payment?')) {
+ captureMutation.mutate(payment.id)
+ }
+ }}
+ >
+ <CreditCardIcon className="size-4" />
+ Capture
+ </DropdownMenuItem>
+ )}
+ {(payment.state === 'checkout' ||
+ payment.state === 'pending' ||
+ payment.state === 'completed') && (
+ <DropdownMenuItem
+ className="text-destructive focus:text-destructive"
+ onClick={() => {
+ if (window.confirm('Void this payment?')) {
+ voidMutation.mutate(payment.id)
+ }
+ }}
+ >
+ <XCircleIcon className="size-4" />
+ Void
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Adjustments
+// ---------------------------------------------------------------------------
+
+function AddAdjustmentDialog({
+ orderId,
+ open,
+ onOpenChange,
+}: {
+ orderId: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+
+ const mutation = useOrderMutation(orderId, (params: { label: string; amount: number }) =>
+ adminClient.orders.adjustments.create(orderId, params),
+ )
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ mutation.mutate(
+ { label: fd.get('label') as string, amount: Number(fd.get('amount')) },
+ { onSuccess: () => onOpenChange(false) },
+ )
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Add Adjustment</DialogTitle>
+ <DialogDescription>
+ Add a manual adjustment to this order. Use a negative amount for discounts.
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit}>
+ <DialogBody>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="adj-label">Label</FieldLabel>
+ <Input id="adj-label" name="label" placeholder="e.g. Manual discount" required />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="adj-amount">Amount</FieldLabel>
+ <Input
+ id="adj-amount"
+ name="amount"
+ type="number"
+ step="0.01"
+ placeholder="-10.00"
+ required
+ />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending ? 'Adding…' : 'Add Adjustment'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function AdjustmentsCard({ order }: { order: Order }) {
+ const { orderId } = Route.useParams()
+
+ const adjustments = (order.adjustments ?? []).filter(
+ (a) => a.source_type !== 'Spree::TaxRate' && a.source_type !== 'Spree::PromotionAction',
+ )
+ const [addOpen, setAddOpen] = useState(false)
+
+ const deleteMutation = useOrderMutation(orderId, (adjustmentId: string) =>
+ adminClient.orders.adjustments.delete(orderId, adjustmentId),
+ )
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <SlidersHorizontalIcon className="size-4" />
+ Adjustments
+ </CardTitle>
+ <CardAction className="flex items-center gap-2">
+ {adjustments.length > 0 && <Badge variant="info">{adjustments.length}</Badge>}
+ <Button size="sm" variant="secondary" onClick={() => setAddOpen(true)}>
+ <PlusIcon data-icon="inline-start" />
+ Add
+ </Button>
+ </CardAction>
+ </CardHeader>
+ {adjustments.length > 0 ? (
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b bg-muted/50 text-muted-foreground">
+ <th className="p-3 pl-5 text-left font-normal">Label</th>
+ <th className="p-3 text-left font-normal">State</th>
+ <th className="p-3 text-right font-normal">Amount</th>
+ <th className="p-3 pr-5 w-10" />
+ </tr>
+ </thead>
+ <tbody>
+ {adjustments.map((adj) => (
+ <tr key={adj.id} className="border-b last:border-b-0">
+ <td className="p-3 pl-5">{adj.label ?? '—'}</td>
+ <td className="p-3">
+ <StatusBadge status={adj.state} />
+ </td>
+ <td className="p-3 text-right font-medium whitespace-nowrap">
+ {order.currency} {Number.parseFloat(adj.amount).toFixed(2)}
+ </td>
+ <td className="p-3 pr-5">
+ {!adj.source_type && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-xs">
+ <EllipsisVerticalIcon className="size-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ className="text-destructive focus:text-destructive"
+ onClick={() => {
+ if (window.confirm('Remove this adjustment?')) {
+ deleteMutation.mutate(adj.id)
+ }
+ }}
+ >
+ <TrashIcon className="size-4" />
+ Remove
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ) : (
+ <CardContent>
+ <p className="text-center text-muted-foreground py-8">No adjustments</p>
+ </CardContent>
+ )}
+ </Card>
+
+ <AddAdjustmentDialog orderId={orderId} open={addOpen} onOpenChange={setAddOpen} />
+ </>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Order Summary
+// ---------------------------------------------------------------------------
+
+function SummaryRow({
+ label,
+ value,
+ bold,
+ danger,
+ highlight,
+}: {
+ label: string
+ value: string
+ bold?: boolean
+ danger?: boolean
+ highlight?: boolean
+}) {
+ return (
+ <div
+ className={cn('flex items-center justify-between px-5 py-2.5', highlight && 'bg-muted/50')}
+ >
+ <span className="text-sm">{label}</span>
+ <span className={cn('text-sm', bold && 'font-bold', danger && 'text-destructive')}>
+ {value}
+ </span>
+ </div>
+ )
+}
+
+function OrderSummaryCard({ order }: { order: Order }) {
+ const outstandingBalance = Number.parseFloat(order.total) - Number.parseFloat(order.payment_total)
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Summary</CardTitle>
+ </CardHeader>
+ <div className="py-1">
+ {order.completed_at && (
+ <>
+ <SummaryRow label="Completed" value={formatDate(order.completed_at)} />
+ {order.canceled_at && (
+ <SummaryRow label="Canceled" value={formatDate(order.canceled_at)} />
+ )}
+ <Separator />
+ </>
+ )}
+
+ <SummaryRow label="Locale" value={order.locale ?? '—'} />
+ <SummaryRow label="Currency" value={order.currency} />
+
+ <Separator />
+
+ <SummaryRow label="Subtotal" value={order.display_item_total} />
+
+ {Number.parseFloat(order.ship_total) > 0 && (
+ <SummaryRow label="Shipping" value={order.display_ship_total} />
+ )}
+
+ {Number.parseFloat(order.promo_total) !== 0 && (
+ <SummaryRow label="Promotions" value={order.display_promo_total} />
+ )}
+
+ {Number.parseFloat(order.adjustment_total) !== 0 && (
+ <SummaryRow label="Adjustments" value={order.display_adjustment_total} />
+ )}
+
+ {Number.parseFloat(order.included_tax_total) > 0 && (
+ <SummaryRow label="Tax (included)" value={order.display_included_tax_total} />
+ )}
+
+ {Number.parseFloat(order.additional_tax_total) > 0 && (
+ <SummaryRow label="Tax (additional)" value={order.display_additional_tax_total} />
+ )}
+
+ <Separator />
+
+ <SummaryRow label="Total" value={order.display_total} bold />
+
+ <Separator />
+
+ <SummaryRow label="Payment total" value={order.display_payment_total} highlight />
+ <SummaryRow
+ label="Outstanding balance"
+ value={`${order.currency} ${Math.abs(outstandingBalance).toFixed(2)}`}
+ highlight
+ danger={outstandingBalance > 0}
+ />
+ </div>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Customer Sidebar
+// ---------------------------------------------------------------------------
+
+function AddressBlock({
+ title,
+ address,
+}: {
+ title: string
+ address: Address | null | undefined
+}) {
+ return (
+ <div>
+ <h6 className="font-semibold text-sm mb-1.5">{title}</h6>
+ {address ? (
+ <div className="text-sm text-muted-foreground flex flex-col gap-0.5">
+ <div>{address.full_name}</div>
+ {address.company && <div>{address.company}</div>}
+ <div>{address.address1}</div>
+ {address.address2 && <div>{address.address2}</div>}
+ <div>
+ {[address.city, address.state_text, address.zipcode].filter(Boolean).join(', ')}
+ </div>
+ <div>{address.country_name}</div>
+ {address.phone && <div>{address.phone}</div>}
+ </div>
+ ) : (
+ <span className="text-sm text-muted-foreground">Not provided</span>
+ )}
+ </div>
+ )
+}
+
+function EditAddressDialog({
+ orderId,
+ type,
+ address,
+ open,
+ onOpenChange,
+}: {
+ orderId: string
+ type: 'ship_address' | 'bill_address'
+ address: Address | null | undefined
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+
+ const mutation = useOrderMutation(orderId, (params: Record<string, unknown>) =>
+ adminClient.orders.update(orderId, { [type]: params } as any),
+ )
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ mutation.mutate(
+ {
+ firstname: fd.get('firstname') as string,
+ lastname: fd.get('lastname') as string,
+ address1: fd.get('address1') as string,
+ city: fd.get('city') as string,
+ zipcode: fd.get('zipcode') as string,
+ country_iso: fd.get('country_iso') as string,
+ state_abbr: fd.get('state_abbr') as string,
+ phone: fd.get('phone') as string,
+ },
+ { onSuccess: () => onOpenChange(false) },
+ )
+ }
+
+ const title = type === 'ship_address' ? 'Edit Shipping Address' : 'Edit Billing Address'
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>Update the address details.</DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit}>
+ <DialogBody>
+ <FieldGroup>
+ <div className="grid grid-cols-2 gap-3">
+ <Field>
+ <FieldLabel htmlFor={`${type}-fn`}>First Name</FieldLabel>
+ <Input
+ id={`${type}-fn`}
+ name="firstname"
+ defaultValue={address?.firstname ?? ''}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`${type}-ln`}>Last Name</FieldLabel>
+ <Input id={`${type}-ln`} name="lastname" defaultValue={address?.lastname ?? ''} />
+ </Field>
+ </div>
+ <Field>
+ <FieldLabel htmlFor={`${type}-a1`}>Address</FieldLabel>
+ <Input id={`${type}-a1`} name="address1" defaultValue={address?.address1 ?? ''} />
+ </Field>
+ <div className="grid grid-cols-2 gap-3">
+ <Field>
+ <FieldLabel htmlFor={`${type}-city`}>City</FieldLabel>
+ <Input id={`${type}-city`} name="city" defaultValue={address?.city ?? ''} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`${type}-zip`}>Zip Code</FieldLabel>
+ <Input id={`${type}-zip`} name="zipcode" defaultValue={address?.zipcode ?? ''} />
+ </Field>
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <Field>
+ <FieldLabel htmlFor={`${type}-country`}>Country ISO</FieldLabel>
+ <Input
+ id={`${type}-country`}
+ name="country_iso"
+ defaultValue={address?.country_iso ?? ''}
+ placeholder="US"
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`${type}-state`}>State</FieldLabel>
+ <Input
+ id={`${type}-state`}
+ name="state_abbr"
+ defaultValue={address?.state_abbr ?? ''}
+ placeholder="CA"
+ />
+ </Field>
+ </div>
+ <Field>
+ <FieldLabel htmlFor={`${type}-phone`}>Phone</FieldLabel>
+ <Input id={`${type}-phone`} name="phone" defaultValue={address?.phone ?? ''} />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending ? 'Saving…' : 'Save'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function CustomerCard({ order }: { order: Order }) {
+ const { orderId } = Route.useParams()
+ const user = order.user
+ const [editAddress, setEditAddress] = useState<'ship_address' | 'bill_address' | null>(null)
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>Customer</CardTitle>
+ <CardAction>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-xs">
+ <EllipsisVerticalIcon className="size-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setEditAddress('ship_address')}>
+ <PencilIcon className="size-4" />
+ Edit Shipping Address
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setEditAddress('bill_address')}>
+ <PencilIcon className="size-4" />
+ Edit Billing Address
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </CardAction>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-5">
+ {/* Contact info */}
+ {user ? (
+ <div className="flex items-center gap-3 rounded-xl bg-muted p-3">
+ <div className="flex size-9 items-center justify-center rounded-lg bg-zinc-950 text-white text-xs font-medium">
+ {[user.first_name, user.last_name]
+ .filter(Boolean)
+ .map((n) => n![0])
+ .join('')
+ .toUpperCase() || user.email[0]!.toUpperCase()}
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm font-medium">
+ {[user.first_name, user.last_name].filter(Boolean).join(' ') || user.email}
+ </div>
+ <div className="truncate text-xs text-muted-foreground">{user.email}</div>
+ </div>
+ </div>
+ ) : order.email ? (
+ <div className="text-sm text-blue-600">{order.email}</div>
+ ) : (
+ <span className="text-sm text-muted-foreground">No customer information</span>
+ )}
+
+ <AddressBlock title="Shipping Address" address={order.ship_address} />
+ <AddressBlock title="Billing Address" address={order.bill_address} />
+ </CardContent>
+ </Card>
+
+ {editAddress && (
+ <EditAddressDialog
+ orderId={orderId}
+ type={editAddress}
+ address={editAddress === 'ship_address' ? order.ship_address : order.bill_address}
+ open={!!editAddress}
+ onOpenChange={(open) => !open && setEditAddress(null)}
+ />
+ )}
+ </>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Special Instructions
+// ---------------------------------------------------------------------------
+
+function SpecialInstructionsCard({ order }: { order: Order }) {
+ const { orderId } = Route.useParams()
+
+ const [editing, setEditing] = useState(false)
+ const mutation = useOrderMutation(orderId, (params: { special_instructions: string }) =>
+ adminClient.orders.update(orderId, params),
+ )
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ mutation.mutate(
+ { special_instructions: fd.get('special_instructions') as string },
+ { onSuccess: () => setEditing(false) },
+ )
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Special Instructions</CardTitle>
+ <CardAction>
+ <Button variant="ghost" size="icon-xs" onClick={() => setEditing(!editing)}>
+ <PencilIcon className="size-4" />
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ {editing ? (
+ <form onSubmit={handleSubmit} className="flex flex-col gap-3">
+ <Textarea name="special_instructions" defaultValue={order.special_instructions ?? ''} />
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="outline" size="sm" onClick={() => setEditing(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" disabled={mutation.isPending}>
+ {mutation.isPending ? 'Saving…' : 'Save'}
+ </Button>
+ </div>
+ </form>
+ ) : order.special_instructions ? (
+ <p className="text-sm text-muted-foreground whitespace-pre-wrap">
+ {order.special_instructions}
+ </p>
+ ) : (
+ <p className="text-sm text-muted-foreground">None</p>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Internal Note
+// ---------------------------------------------------------------------------
+
+function InternalNoteCard({ order }: { order: Order }) {
+ const { orderId } = Route.useParams()
+
+ const [editing, setEditing] = useState(false)
+ const mutation = useOrderMutation(orderId, (params: { internal_note: string }) =>
+ adminClient.orders.update(orderId, params),
+ )
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ mutation.mutate(
+ { internal_note: fd.get('internal_note') as string },
+ { onSuccess: () => setEditing(false) },
+ )
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Internal Note</CardTitle>
+ <CardAction>
+ <Button variant="ghost" size="icon-xs" onClick={() => setEditing(!editing)}>
+ <PencilIcon className="size-4" />
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ {editing ? (
+ <form onSubmit={handleSubmit} className="flex flex-col gap-3">
+ <Textarea name="internal_note" defaultValue={order.internal_note ?? ''} />
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="outline" size="sm" onClick={() => setEditing(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" disabled={mutation.isPending}>
+ {mutation.isPending ? 'Saving…' : 'Save'}
+ </Button>
+ </div>
+ </form>
+ ) : order.internal_note ? (
+ <p className="text-sm text-muted-foreground whitespace-pre-wrap">{order.internal_note}</p>
+ ) : (
+ <p className="text-sm text-muted-foreground">None</p>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Loading skeleton
+// ---------------------------------------------------------------------------
+
+function OrderSkeleton() {
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="flex items-center gap-3">
+ <Skeleton className="size-8 rounded-lg" />
+ <Skeleton className="h-8 w-40" />
+ <Skeleton className="h-5 w-16 rounded-md" />
+ <Skeleton className="h-5 w-16 rounded-md" />
+ </div>
+ <div className="grid grid-cols-12 gap-6">
+ <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">
+ <Skeleton className="h-64 w-full rounded-xl" />
+ <Skeleton className="h-48 w-full rounded-xl" />
+ <Skeleton className="h-48 w-full rounded-xl" />
+ </div>
+ <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">
+ <Skeleton className="h-64 w-full rounded-xl" />
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/orders/drafts.tsx b/packages/admin/src/routes/_authenticated/$storeId/orders/drafts.tsx
new file mode 100644
index 0000000000..e770a1916e
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/orders/drafts.tsx
@@ -0,0 +1,32 @@
+import { createFileRoute } from '@tanstack/react-router'
+import { PlusIcon } from 'lucide-react'
+import { adminClient } from '@/client'
+import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'
+import { Button } from '@/components/ui/button'
+import '@/tables/orders'
+
+export const Route = createFileRoute('/_authenticated/$storeId/orders/drafts')({
+ validateSearch: resourceSearchSchema,
+ component: DraftOrdersPage,
+})
+
+function DraftOrdersPage() {
+ const searchParams = Route.useSearch()
+
+ return (
+ <ResourceTable
+ tableKey="orders"
+ queryKey="draft-orders"
+ queryFn={(params) => adminClient.orders.list(params)}
+ searchParams={searchParams}
+ defaultParams={{ incomplete: 1 }}
+ title="Draft Orders"
+ actions={
+ <Button size="sm" className="h-[2.125rem]">
+ <PlusIcon className="size-4" />
+ New Order
+ </Button>
+ }
+ />
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/orders/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/orders/index.tsx
new file mode 100644
index 0000000000..1bfa274377
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/orders/index.tsx
@@ -0,0 +1,31 @@
+import { createFileRoute } from '@tanstack/react-router'
+import { PlusIcon } from 'lucide-react'
+import { adminClient } from '@/client'
+import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'
+import { Button } from '@/components/ui/button'
+import '@/tables/orders'
+
+export const Route = createFileRoute('/_authenticated/$storeId/orders/')({
+ validateSearch: resourceSearchSchema,
+ component: OrdersPage,
+})
+
+function OrdersPage() {
+ const searchParams = Route.useSearch()
+
+ return (
+ <ResourceTable
+ tableKey="orders"
+ queryKey="orders"
+ queryFn={(params) => adminClient.orders.list(params)}
+ searchParams={searchParams}
+ defaultParams={{ complete: 1 }}
+ actions={
+ <Button size="sm" className="h-[2.125rem]">
+ <PlusIcon className="size-4" />
+ New Order
+ </Button>
+ }
+ />
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
new file mode 100644
index 0000000000..76613c5693
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
@@ -0,0 +1,1070 @@
+import type { Image, Product as BaseProduct, Variant as BaseVariant } from '@spree/admin-sdk'
+
+// Extended types for fields not yet in generated types
+type Variant = BaseVariant & {
+ barcode?: string | null
+ weight_unit?: string | null
+ dimensions_unit?: string | null
+}
+type Product = Omit<BaseProduct, 'master_variant' | 'variants'> & {
+ shipping_category_id?: string | null
+ tax_category_id?: string | null
+ meta_title?: string | null
+ master_variant?: Variant
+ variants?: Variant[]
+}
+import { zodResolver } from '@hookform/resolvers/zod'
+import { createFileRoute, Link, useRouter } from '@tanstack/react-router'
+import {
+ ArrowLeftIcon,
+ ImagePlusIcon,
+ Loader2Icon,
+ SaveIcon,
+ TrashIcon,
+ XIcon,
+} from 'lucide-react'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { Controller, useForm, type UseFormReturn } from 'react-hook-form'
+import { toast } from 'sonner'
+import { StatusBadge } from '@/components/ui/badge'
+import { Button } from '@/components/ui/button'
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
+import { DatePicker } from '@/components/ui/date-picker'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import {
+ Combobox,
+ ComboboxChip,
+ ComboboxChips,
+ ComboboxChipsInput,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxValue,
+ useComboboxAnchor,
+} from '@/components/ui/combobox'
+import { RichTextEditor } from '@/components/ui/rich-text-editor'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Switch } from '@/components/ui/switch'
+import { Textarea } from '@/components/ui/textarea'
+import { useDirectUpload } from '@/hooks/use-direct-upload'
+import { useProduct, useUpdateProduct, useDeleteProduct } from '@/hooks/use-product'
+import {
+ useProductAssets,
+ useCreateProductAsset,
+ useDeleteProductAsset,
+} from '@/hooks/use-product-assets'
+import { useShippingCategories } from '@/hooks/use-shipping-categories'
+import { useTaxCategories } from '@/hooks/use-tax-categories'
+import { useTaxons } from '@/hooks/use-taxons'
+import { productFormSchema, type ProductFormValues } from '@/schemas/product'
+
+export const Route = createFileRoute('/_authenticated/$storeId/products/$productId')({
+ component: ProductDetailPage,
+})
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function productToFormValues(product: Product): ProductFormValues {
+ const master = product.master_variant
+
+ return {
+ name: product.name,
+ description: product.description ?? '',
+ status: (product.status as ProductFormValues['status']) ?? 'draft',
+ make_active_at: product.make_active_at ?? null,
+ available_on: product.available_on ?? null,
+ discontinue_on: product.discontinue_on ?? null,
+ taxon_ids: product.taxons?.map((t) => t.id) ?? [],
+ tags: product.tags ?? [],
+ price: master?.price?.amount ? Number(master.price.amount) : undefined,
+ compare_at_price: master?.original_price?.amount
+ ? Number(master.original_price.amount)
+ : null,
+ cost_price: product.cost_price ? Number(product.cost_price) : null,
+ sku: master?.sku ?? '',
+ barcode: master?.barcode ?? '',
+ track_inventory: master?.track_inventory ?? true,
+ shipping_category_id: product.shipping_category_id ?? null,
+ weight: master?.weight ?? null,
+ height: master?.height ?? null,
+ width: master?.width ?? null,
+ depth: master?.depth ?? null,
+ weight_unit: master?.weight_unit ?? null,
+ dimensions_unit: master?.dimensions_unit ?? null,
+ tax_category_id: product.tax_category_id ?? null,
+ meta_title: product.meta_title ?? '',
+ meta_description: product.meta_description ?? '',
+ slug: product.slug ?? '',
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Page
+// ---------------------------------------------------------------------------
+
+function ProductDetailPage() {
+ const { productId } = Route.useParams()
+ const { data: product, isLoading, error } = useProduct(productId)
+
+ if (isLoading) return <ProductSkeleton />
+ if (error || !product) {
+ return <p className="text-destructive p-4">Failed to load product.</p>
+ }
+
+ return <ProductForm product={product as Product} />
+}
+
+// ---------------------------------------------------------------------------
+// Form
+// ---------------------------------------------------------------------------
+
+function ProductForm({ product }: { product: Product }) {
+ const { productId, storeId } = Route.useParams()
+ const router = useRouter()
+ const updateProduct = useUpdateProduct()
+ const deleteProduct = useDeleteProduct()
+ const hasVariants = (product.variant_count ?? 0) > 0
+
+ const form = useForm<ProductFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(productFormSchema) as any,
+ defaultValues: productToFormValues(product),
+ })
+
+ useEffect(() => {
+ form.reset(productToFormValues(product))
+ }, [product, form])
+
+ const onSubmit = async (data: ProductFormValues) => {
+ try {
+ await updateProduct.mutateAsync({ id: productId, ...data })
+ toast.success('Product saved')
+ } catch {
+ toast.error('Failed to save product')
+ }
+ }
+
+ const handleDelete = async () => {
+ if (!window.confirm('Are you sure you want to delete this product?')) return
+ try {
+ await deleteProduct.mutateAsync(productId)
+ toast.success('Product deleted')
+ await router.navigate({ to: '/$storeId/products', params: { storeId }, search: { filters: [], columns: [] } })
+ } catch {
+ toast.error('Failed to delete product')
+ }
+ }
+
+ return (
+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
+ {/* Header */}
+ <div className="flex items-center gap-3">
+ <Link
+ to="/$storeId/products"
+ params={{ storeId }}
+ search={{ filters: [], columns: [] }}
+ className="inline-flex items-center justify-center rounded-lg p-1.5 text-muted-foreground hover:bg-gray-100 hover:text-foreground transition-colors"
+ >
+ <ArrowLeftIcon className="size-5" />
+ </Link>
+
+ <h1 className="text-2xl font-medium truncate">{product.name}</h1>
+ <StatusBadge status={product.status} />
+
+ <div className="ml-auto flex items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={handleDelete}
+ disabled={deleteProduct.isPending}
+ >
+ <TrashIcon className="size-4" />
+ Delete
+ </Button>
+ <Button
+ type="submit"
+ size="sm"
+ disabled={updateProduct.isPending || !form.formState.isDirty}
+ >
+ {updateProduct.isPending ? (
+ <Loader2Icon className="size-4 animate-spin" />
+ ) : (
+ <SaveIcon className="size-4" />
+ )}
+ Save
+ </Button>
+ </div>
+ </div>
+
+ {/* Two-column layout */}
+ <div className="grid grid-cols-12 gap-6">
+ {/* Left column */}
+ <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">
+ <GeneralCard form={form} />
+ <MediaCard productId={productId} />
+ {!hasVariants && <PricingCard form={form} />}
+ {!hasVariants && <InventoryCard form={form} />}
+ <SEOCard form={form} product={product} />
+ </div>
+
+ {/* Right column */}
+ <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">
+ <StatusCard form={form} />
+ <CategorizationCard form={form} />
+ <ShippingCard form={form} hasVariants={hasVariants} />
+ <TaxCard form={form} />
+ </div>
+ </div>
+ </form>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Shared types
+// ---------------------------------------------------------------------------
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type FormCardProps = {
+ form: UseFormReturn<ProductFormValues, any, any>
+}
+
+// ---------------------------------------------------------------------------
+// General
+// ---------------------------------------------------------------------------
+
+function GeneralCard({ form }: FormCardProps) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>General</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <div className="grid gap-2">
+ <Label htmlFor="name">Name</Label>
+ <Input id="name" placeholder="Product name" {...form.register('name')} />
+ {form.formState.errors.name && (
+ <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>
+ )}
+ </div>
+
+ <div className="grid gap-2">
+ <Label>Description</Label>
+ <Controller
+ name="description"
+ control={form.control}
+ render={({ field }) => (
+ <RichTextEditor
+ value={field.value}
+ onChange={field.onChange}
+ placeholder="Write a product description..."
+ />
+ )}
+ />
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Media
+// ---------------------------------------------------------------------------
+
+interface PendingUpload {
+ id: string
+ file: File
+ preview: string
+ progress: 'uploading' | 'attaching' | 'done' | 'error'
+}
+
+function MediaCard({ productId }: { productId: string }) {
+ const { data: assetsResponse } = useProductAssets(productId)
+ const createAsset = useCreateProductAsset(productId)
+ const deleteAsset = useDeleteProductAsset(productId)
+ const directUpload = useDirectUpload()
+ const [pending, setPending] = useState<PendingUpload[]>([])
+ const fileInputRef = useRef<HTMLInputElement>(null)
+
+ const assets = assetsResponse?.data ?? []
+
+ const handleFiles = useCallback(
+ async (files: FileList | File[]) => {
+ const fileArray = Array.from(files)
+
+ for (const file of fileArray) {
+ const uploadId = crypto.randomUUID()
+ const preview = URL.createObjectURL(file)
+
+ setPending((prev) => [...prev, { id: uploadId, file, preview, progress: 'uploading' }])
+
+ try {
+ const result = await directUpload.mutateAsync(file)
+
+ setPending((prev) =>
+ prev.map((p) => (p.id === uploadId ? { ...p, progress: 'attaching' as const } : p)),
+ )
+
+ await createAsset.mutateAsync({
+ signed_id: result.signedId,
+ alt: file.name,
+ position: assets.length + fileArray.indexOf(file) + 1,
+ })
+
+ setPending((prev) => prev.filter((p) => p.id !== uploadId))
+ URL.revokeObjectURL(preview)
+ } catch (err) {
+ console.error(`Upload failed for ${file.name}:`, err)
+ setPending((prev) =>
+ prev.map((p) => (p.id === uploadId ? { ...p, progress: 'error' as const } : p)),
+ )
+ const message = err instanceof Error ? err.message : 'Unknown error'
+ toast.error(`Failed to upload ${file.name}: ${message}`)
+ }
+ }
+ },
+ [directUpload, createAsset, assets.length],
+ )
+
+ const handleDrop = useCallback(
+ (e: React.DragEvent) => {
+ e.preventDefault()
+ if (e.dataTransfer.files.length > 0) {
+ handleFiles(e.dataTransfer.files)
+ }
+ },
+ [handleFiles],
+ )
+
+ const handleDragOver = useCallback((e: React.DragEvent) => {
+ e.preventDefault()
+ }, [])
+
+ const handleDeleteAsset = async (assetId: string) => {
+ try {
+ await deleteAsset.mutateAsync(assetId)
+ toast.success('Image deleted')
+ } catch {
+ toast.error('Failed to delete image')
+ }
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Media</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ {/* Image grid */}
+ {(assets.length > 0 || pending.length > 0) && (
+ <div className="grid grid-cols-4 gap-3">
+ {assets.map((asset) => (
+ <MediaThumbnail
+ key={asset.id}
+ asset={asset as Image}
+ onDelete={() => handleDeleteAsset(asset.id)}
+ />
+ ))}
+ {pending.map((upload) => (
+ <div
+ key={upload.id}
+ className="relative aspect-square overflow-hidden rounded-lg border border-gray-200 bg-gray-50"
+ >
+ <img
+ src={upload.preview}
+ alt=""
+ className="size-full object-cover opacity-60"
+ />
+ <div className="absolute inset-0 flex items-center justify-center">
+ {upload.progress === 'error' ? (
+ <span className="text-xs text-destructive font-medium">Failed</span>
+ ) : (
+ <Loader2Icon className="size-5 animate-spin text-gray-500" />
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Drop zone */}
+ <div
+ onDrop={handleDrop}
+ onDragOver={handleDragOver}
+ className="flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-gray-200 p-6 text-center transition-colors hover:border-gray-300 cursor-pointer"
+ onClick={() => fileInputRef.current?.click()}
+ onKeyDown={(e) => e.key === 'Enter' && fileInputRef.current?.click()}
+ role="button"
+ tabIndex={0}
+ >
+ <ImagePlusIcon className="size-8 text-gray-400" />
+ <p className="text-sm text-gray-600">
+ Drag & drop images here, or click to browse
+ </p>
+ <p className="text-xs text-gray-400">PNG, JPG, WebP up to 10MB</p>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/*"
+ multiple
+ className="hidden"
+ onChange={(e) => e.target.files && handleFiles(e.target.files)}
+ />
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
+
+function MediaThumbnail({
+ asset,
+ onDelete,
+}: {
+ asset: Image
+ onDelete: () => void
+}) {
+ const imageUrl = asset.small_url || asset.mini_url || asset.original_url
+
+ return (
+ <div className="group relative aspect-square overflow-hidden rounded-lg border border-gray-200 bg-gray-50">
+ {imageUrl ? (
+ <img src={imageUrl} alt={asset.alt ?? ''} className="size-full object-cover" />
+ ) : (
+ <div className="flex size-full items-center justify-center text-gray-400">
+ <ImagePlusIcon className="size-6" />
+ </div>
+ )}
+ <button
+ type="button"
+ onClick={onDelete}
+ className="absolute top-1.5 right-1.5 hidden group-hover:inline-flex items-center justify-center rounded-md size-6 bg-white/90 text-gray-600 hover:text-destructive hover:bg-white shadow-sm transition-colors"
+ >
+ <XIcon className="size-3.5" />
+ </button>
+ </div>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Pricing
+// ---------------------------------------------------------------------------
+
+function PricingCard({ form }: FormCardProps) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Pricing</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <div className="grid grid-cols-2 gap-4">
+ <div className="grid gap-2">
+ <Label htmlFor="price">Price</Label>
+ <Input
+ id="price"
+ type="number"
+ step="0.01"
+ min="0"
+ placeholder="0.00"
+ {...form.register('price')}
+ />
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="compare_at_price">Compare at price</Label>
+ <Input
+ id="compare_at_price"
+ type="number"
+ step="0.01"
+ min="0"
+ placeholder="0.00"
+ {...form.register('compare_at_price')}
+ />
+ <p className="text-xs text-muted-foreground">
+ Original price shown as strikethrough
+ </p>
+ </div>
+ </div>
+ <div className="grid gap-2 max-w-[50%]">
+ <Label htmlFor="cost_price">Cost price</Label>
+ <Input
+ id="cost_price"
+ type="number"
+ step="0.01"
+ min="0"
+ placeholder="0.00"
+ {...form.register('cost_price')}
+ />
+ <p className="text-xs text-muted-foreground">Not visible to customers</p>
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Inventory
+// ---------------------------------------------------------------------------
+
+function InventoryCard({ form }: FormCardProps) {
+ const trackInventory = form.watch('track_inventory')
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Inventory</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <div className="grid grid-cols-2 gap-4">
+ <div className="grid gap-2">
+ <Label htmlFor="sku">SKU</Label>
+ <Input id="sku" placeholder="SKU-001" {...form.register('sku')} />
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="barcode">Barcode</Label>
+ <Input id="barcode" placeholder="ISBN, UPC, GTIN..." {...form.register('barcode')} />
+ </div>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <Controller
+ name="track_inventory"
+ control={form.control}
+ render={({ field }) => (
+ <Switch
+ id="track_inventory"
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ )}
+ />
+ <Label htmlFor="track_inventory">Track inventory</Label>
+ </div>
+
+ {trackInventory && (
+ <p className="text-sm text-muted-foreground">
+ Stock levels are managed per stock location.
+ </p>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// SEO
+// ---------------------------------------------------------------------------
+
+function SEOCard({ form, product }: FormCardProps & { product: Product }) {
+ const slug = form.watch('slug')
+ const metaTitle = form.watch('meta_title')
+ const metaDescription = form.watch('meta_description')
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>SEO</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ {/* Preview */}
+ <div className="rounded-lg border border-gray-200 p-4 space-y-1">
+ <p className="text-sm font-medium text-blue-700 truncate">
+ {metaTitle || product.name}
+ </p>
+ <p className="text-xs text-green-700 truncate">
+ example.com/products/{slug || product.slug}
+ </p>
+ {metaDescription && (
+ <p className="text-xs text-muted-foreground line-clamp-2">{metaDescription}</p>
+ )}
+ </div>
+
+ <div className="grid gap-2">
+ <Label htmlFor="slug">URL handle</Label>
+ <Input id="slug" placeholder="product-url-handle" {...form.register('slug')} />
+ </div>
+
+ <div className="grid gap-2">
+ <Label htmlFor="meta_title">Meta title</Label>
+ <Input id="meta_title" placeholder="SEO title" {...form.register('meta_title')} />
+ </div>
+
+ <div className="grid gap-2">
+ <Label htmlFor="meta_description">Meta description</Label>
+ <Textarea
+ id="meta_description"
+ placeholder="SEO description"
+ rows={3}
+ {...form.register('meta_description')}
+ />
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Status
+// ---------------------------------------------------------------------------
+
+function StatusCard({ form }: FormCardProps) {
+ const status = form.watch('status')
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Status</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <div className="grid gap-2">
+ <Label>Status</Label>
+ <Controller
+ name="status"
+ control={form.control}
+ render={({ field }) => (
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="draft">Draft</SelectItem>
+ <SelectItem value="active">Active</SelectItem>
+ <SelectItem value="archived">Archived</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </div>
+
+ {status !== 'active' && (
+ <div className="grid gap-2">
+ <Label>Schedule activation</Label>
+ <Controller
+ name="make_active_at"
+ control={form.control}
+ render={({ field }) => (
+ <DatePicker
+ value={field.value}
+ onChange={field.onChange}
+ placeholder="Pick a date"
+ includeTime
+ />
+ )}
+ />
+ </div>
+ )}
+
+ <div className="grid gap-2">
+ <Label>Available on</Label>
+ <Controller
+ name="available_on"
+ control={form.control}
+ render={({ field }) => (
+ <DatePicker
+ value={field.value}
+ onChange={field.onChange}
+ placeholder="Pick a date"
+ includeTime
+ />
+ )}
+ />
+ </div>
+
+ <div className="grid gap-2">
+ <Label>Discontinue on</Label>
+ <Controller
+ name="discontinue_on"
+ control={form.control}
+ render={({ field }) => (
+ <DatePicker
+ value={field.value}
+ onChange={field.onChange}
+ placeholder="Pick a date"
+ includeTime
+ />
+ )}
+ />
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Categorization
+// ---------------------------------------------------------------------------
+
+function CategorizationCard({ form }: FormCardProps) {
+ const { data: taxonsResponse } = useTaxons()
+ const taxons = taxonsResponse?.data ?? []
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Categorization</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <div className="grid gap-2">
+ <Label>Categories</Label>
+ <Controller
+ name="taxon_ids"
+ control={form.control}
+ render={({ field }) => (
+ <TaxonCombobox
+ taxons={taxons}
+ value={field.value ?? []}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </div>
+
+ <div className="grid gap-2">
+ <Label>Tags</Label>
+ <Controller
+ name="tags"
+ control={form.control}
+ render={({ field }) => (
+ <TagCombobox
+ value={field.value ?? []}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
+
+interface TaxonOption {
+ id: string
+ name: string
+}
+
+function TaxonCombobox({
+ taxons,
+ value,
+ onChange,
+}: {
+ taxons: TaxonOption[]
+ value: string[]
+ onChange: (value: string[]) => void
+}) {
+ const anchorRef = useComboboxAnchor()
+
+ return (
+ <Combobox
+ multiple
+ value={value}
+ onValueChange={onChange}
+ >
+ <ComboboxChips ref={anchorRef}>
+ <ComboboxValue>
+ {(selectedValues: string[]) =>
+ selectedValues.map((id) => (
+ <ComboboxChip key={id}>
+ {taxons.find((t) => t.id === id)?.name ?? id}
+ </ComboboxChip>
+ ))
+ }
+ </ComboboxValue>
+ <ComboboxChipsInput placeholder="Search categories..." />
+ </ComboboxChips>
+ <ComboboxContent anchor={anchorRef}>
+ <ComboboxList>
+ {taxons.map((taxon) => (
+ <ComboboxItem key={taxon.id} value={taxon.id}>
+ {taxon.name}
+ </ComboboxItem>
+ ))}
+ <ComboboxEmpty>No categories found</ComboboxEmpty>
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )
+}
+
+function TagCombobox({
+ value,
+ onChange,
+}: {
+ value: string[]
+ onChange: (value: string[]) => void
+}) {
+ const anchorRef = useComboboxAnchor()
+ const [inputValue, setInputValue] = useState('')
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Enter' && inputValue.trim()) {
+ e.preventDefault()
+ const tag = inputValue.trim()
+ if (!value.includes(tag)) {
+ onChange([...value, tag])
+ }
+ setInputValue('')
+ }
+ }
+
+ return (
+ <Combobox
+ multiple
+ value={value}
+ onValueChange={onChange}
+ >
+ <ComboboxChips ref={anchorRef}>
+ <ComboboxValue>
+ {(selectedValues: string[]) =>
+ selectedValues.map((tag) => (
+ <ComboboxChip key={tag}>
+ {tag}
+ </ComboboxChip>
+ ))
+ }
+ </ComboboxValue>
+ <ComboboxChipsInput
+ placeholder="Type to add tags..."
+ value={inputValue}
+ onChange={(e) => setInputValue((e.target as HTMLInputElement).value)}
+ onKeyDown={handleKeyDown}
+ />
+ </ComboboxChips>
+ <ComboboxContent anchor={anchorRef}>
+ <ComboboxList>
+ {value.map((tag) => (
+ <ComboboxItem key={tag} value={tag}>
+ {tag}
+ </ComboboxItem>
+ ))}
+ {inputValue.trim() && !value.includes(inputValue.trim()) && (
+ <ComboboxItem value={inputValue.trim()}>
+ Create &ldquo;{inputValue.trim()}&rdquo;
+ </ComboboxItem>
+ )}
+ <ComboboxEmpty>Type and press Enter to create a tag</ComboboxEmpty>
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Shipping
+// ---------------------------------------------------------------------------
+
+function ShippingCard({ form, hasVariants }: FormCardProps & { hasVariants: boolean }) {
+ const { data: shippingCategoriesResponse } = useShippingCategories()
+ const shippingCategories = shippingCategoriesResponse?.data ?? []
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Shipping</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <div className="grid gap-2">
+ <Label>Shipping category</Label>
+ <Controller
+ name="shipping_category_id"
+ control={form.control}
+ render={({ field }) => (
+ <Select value={field.value ?? ''} onValueChange={(v) => field.onChange(v || null)}>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select shipping category" />
+ </SelectTrigger>
+ <SelectContent>
+ {shippingCategories.map((cat) => (
+ <SelectItem key={cat.id} value={cat.id}>
+ {cat.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </div>
+
+ {!hasVariants && (
+ <>
+ <div className="grid grid-cols-2 gap-3">
+ <div className="grid gap-2">
+ <Label htmlFor="weight">Weight</Label>
+ <Input
+ id="weight"
+ type="number"
+ step="any"
+ placeholder="0.0"
+ {...form.register('weight')}
+ />
+ </div>
+ <div className="grid gap-2">
+ <Label>Unit</Label>
+ <Controller
+ name="weight_unit"
+ control={form.control}
+ render={({ field }) => (
+ <Select
+ value={field.value ?? ''}
+ onValueChange={(v) => field.onChange(v || null)}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Unit" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="oz">oz</SelectItem>
+ <SelectItem value="lb">lb</SelectItem>
+ <SelectItem value="g">g</SelectItem>
+ <SelectItem value="kg">kg</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-3 gap-3">
+ <div className="grid gap-2">
+ <Label htmlFor="height">H</Label>
+ <Input
+ id="height"
+ type="number"
+ step="any"
+ placeholder="0.0"
+ {...form.register('height')}
+ />
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="width">W</Label>
+ <Input
+ id="width"
+ type="number"
+ step="any"
+ placeholder="0.0"
+ {...form.register('width')}
+ />
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="depth">D</Label>
+ <Input
+ id="depth"
+ type="number"
+ step="any"
+ placeholder="0.0"
+ {...form.register('depth')}
+ />
+ </div>
+ </div>
+
+ <div className="grid gap-2">
+ <Label>Dimensions unit</Label>
+ <Controller
+ name="dimensions_unit"
+ control={form.control}
+ render={({ field }) => (
+ <Select
+ value={field.value ?? ''}
+ onValueChange={(v) => field.onChange(v || null)}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Unit" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="in">in</SelectItem>
+ <SelectItem value="ft">ft</SelectItem>
+ <SelectItem value="cm">cm</SelectItem>
+ <SelectItem value="mm">mm</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </div>
+ </>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Tax
+// ---------------------------------------------------------------------------
+
+function TaxCard({ form }: FormCardProps) {
+ const { data: taxCategoriesResponse } = useTaxCategories()
+ const taxCategories = taxCategoriesResponse?.data ?? []
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Tax</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="grid gap-2">
+ <Label>Tax category</Label>
+ <Controller
+ name="tax_category_id"
+ control={form.control}
+ render={({ field }) => (
+ <Select value={field.value ?? ''} onValueChange={(v) => field.onChange(v || null)}>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select tax category" />
+ </SelectTrigger>
+ <SelectContent>
+ {taxCategories.map((cat) => (
+ <SelectItem key={cat.id} value={cat.id}>
+ {cat.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Loading skeleton
+// ---------------------------------------------------------------------------
+
+function ProductSkeleton() {
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="flex items-center gap-3">
+ <Skeleton className="size-8 rounded-lg" />
+ <Skeleton className="h-8 w-48" />
+ <Skeleton className="h-5 w-16 rounded-md" />
+ <div className="ml-auto flex items-center gap-2">
+ <Skeleton className="h-8 w-20 rounded-lg" />
+ <Skeleton className="h-8 w-16 rounded-lg" />
+ </div>
+ </div>
+ <div className="grid grid-cols-12 gap-6">
+ <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">
+ <Skeleton className="h-72 w-full rounded-xl" />
+ <Skeleton className="h-48 w-full rounded-xl" />
+ <Skeleton className="h-40 w-full rounded-xl" />
+ <Skeleton className="h-40 w-full rounded-xl" />
+ <Skeleton className="h-52 w-full rounded-xl" />
+ </div>
+ <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">
+ <Skeleton className="h-56 w-full rounded-xl" />
+ <Skeleton className="h-40 w-full rounded-xl" />
+ <Skeleton className="h-52 w-full rounded-xl" />
+ <Skeleton className="h-24 w-full rounded-xl" />
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/index.tsx
new file mode 100644
index 0000000000..ef1a9f4588
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/products/index.tsx
@@ -0,0 +1,30 @@
+import { createFileRoute } from '@tanstack/react-router'
+import { PlusIcon } from 'lucide-react'
+import { adminClient } from '@/client'
+import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'
+import { Button } from '@/components/ui/button'
+import '@/tables/products'
+
+export const Route = createFileRoute('/_authenticated/$storeId/products/')({
+ validateSearch: resourceSearchSchema,
+ component: ProductsPage,
+})
+
+function ProductsPage() {
+ const searchParams = Route.useSearch()
+
+ return (
+ <ResourceTable
+ tableKey="products"
+ queryKey="products"
+ queryFn={(params) => adminClient.products.list(params)}
+ searchParams={searchParams}
+ actions={
+ <Button size="sm" className="h-[2.125rem]">
+ <PlusIcon className="size-4" />
+ Add Product
+ </Button>
+ }
+ />
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/orders/$orderId.tsx b/packages/admin/src/routes/_authenticated/orders/$orderId.tsx
index 684c6aa566..755b130996 100644
--- a/packages/admin/src/routes/_authenticated/orders/$orderId.tsx
+++ b/packages/admin/src/routes/_authenticated/orders/$orderId.tsx
@@ -1,4 +1,4 @@
-import type { AdminAddress, AdminOrder } from '@spree/sdk'
+import type { Address, Order } from '@spree/admin-sdk'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { createFileRoute, Link } from '@tanstack/react-router'
import {
@@ -18,7 +18,7 @@ import {
XCircleIcon,
} from 'lucide-react'
import { type FormEvent, useState } from 'react'
-import { spreeClient } from '@/client'
+import { adminClient } from '@/client'
import { Badge, StatusBadge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardAction, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
@@ -55,29 +55,23 @@ export const Route = createFileRoute('/_authenticated/orders/$orderId')({
// ---------------------------------------------------------------------------
function useOrder(orderId: string) {
- const { token } = useAuth()
return useQuery({
queryKey: ['order', orderId],
queryFn: () =>
- spreeClient.admin.orders.get(
- orderId,
- {
- expand: [
- 'line_items',
- 'shipments',
- 'shipments.shipping_method',
- 'shipments.stock_location',
- 'payments',
- 'payments.payment_method',
- 'bill_address',
- 'ship_address',
- 'user',
- 'adjustments',
- ],
- },
- { token: token! },
- ),
- enabled: !!token,
+ adminClient.orders.get(orderId, {
+ expand: [
+ 'line_items',
+ 'shipments',
+ 'shipments.shipping_method',
+ 'shipments.stock_location',
+ 'payments',
+ 'payments.payment_method',
+ 'bill_address',
+ 'ship_address',
+ 'user',
+ 'adjustments',
+ ],
+ }),
})
}
@@ -159,16 +153,16 @@ function OrderDetailPage() {
// Header
// ---------------------------------------------------------------------------
-function OrderHeader({ order }: { order: AdminOrder }) {
+function OrderHeader({ order }: { order: Order }) {
const { orderId } = Route.useParams()
const { token } = useAuth()
const backUrl = order.completed_at ? '/orders' : '/orders/drafts'
const cancelMutation = useOrderMutation(orderId, () =>
- spreeClient.admin.orders.cancel(orderId, {}, { token: token! }),
+ adminClient.orders.cancel(orderId),
)
const resendMutation = useOrderMutation(orderId, () =>
- spreeClient.admin.orders.resendConfirmation(orderId, {}, { token: token! }),
+ adminClient.orders.resendConfirmation(orderId),
)
return (
@@ -252,7 +246,7 @@ function AddLineItemDialog({
}) {
const { token } = useAuth()
const mutation = useOrderMutation(orderId, (params: { variant_id: string; quantity: number }) =>
- spreeClient.admin.orders.lineItems.create(orderId, params, { token: token! }),
+ adminClient.orders.lineItems.create(orderId, params),
)
function handleSubmit(e: FormEvent<HTMLFormElement>) {
@@ -313,7 +307,7 @@ function EditQuantityDialog({
}) {
const { token } = useAuth()
const mutation = useOrderMutation(orderId, (params: { quantity: number }) =>
- spreeClient.admin.orders.lineItems.update(orderId, lineItemId, params, { token: token! }),
+ adminClient.orders.lineItems.update(orderId, lineItemId, params),
)
function handleSubmit(e: FormEvent<HTMLFormElement>) {
@@ -361,7 +355,7 @@ function EditQuantityDialog({
)
}
-function LineItemsCard({ order }: { order: AdminOrder }) {
+function LineItemsCard({ order }: { order: Order }) {
const { orderId } = Route.useParams()
const { token } = useAuth()
const items = order.line_items ?? []
@@ -369,7 +363,7 @@ function LineItemsCard({ order }: { order: AdminOrder }) {
const [editItem, setEditItem] = useState<{ id: string; quantity: number } | null>(null)
const deleteMutation = useOrderMutation(orderId, (lineItemId: string) =>
- spreeClient.admin.orders.lineItems.delete(orderId, lineItemId, { token: token! }),
+ adminClient.orders.lineItems.delete(orderId, lineItemId),
)
return (
@@ -514,7 +508,7 @@ function EditTrackingDialog({
}) {
const { token } = useAuth()
const mutation = useOrderMutation(orderId, (params: { tracking: string }) =>
- spreeClient.admin.orders.shipments.update(orderId, shipmentId, params, { token: token! }),
+ adminClient.orders.shipments.update(orderId, shipmentId, params),
)
function handleSubmit(e: FormEvent<HTMLFormElement>) {
@@ -556,7 +550,7 @@ function EditTrackingDialog({
)
}
-function ShipmentsCard({ order }: { order: AdminOrder }) {
+function ShipmentsCard({ order }: { order: Order }) {
const { orderId } = Route.useParams()
const { token } = useAuth()
const shipments = order.shipments ?? []
@@ -566,10 +560,10 @@ function ShipmentsCard({ order }: { order: AdminOrder }) {
} | null>(null)
const shipMutation = useOrderMutation(orderId, (shipmentId: string) =>
- spreeClient.admin.orders.shipments.ship(orderId, shipmentId, {}, { token: token! }),
+ adminClient.orders.shipments.ship(orderId, shipmentId),
)
const cancelShipmentMutation = useOrderMutation(orderId, (shipmentId: string) =>
- spreeClient.admin.orders.shipments.cancel(orderId, shipmentId, {}, { token: token! }),
+ adminClient.orders.shipments.cancel(orderId, shipmentId),
)
if (shipments.length === 0) return null
@@ -701,16 +695,16 @@ function ShipmentsCard({ order }: { order: AdminOrder }) {
// Payments
// ---------------------------------------------------------------------------
-function PaymentsCard({ order }: { order: AdminOrder }) {
+function PaymentsCard({ order }: { order: Order }) {
const { orderId } = Route.useParams()
const { token } = useAuth()
const payments = order.payments ?? []
const captureMutation = useOrderMutation(orderId, (paymentId: string) =>
- spreeClient.admin.orders.payments.capture(orderId, paymentId, {}, { token: token! }),
+ adminClient.orders.payments.capture(orderId, paymentId),
)
const voidMutation = useOrderMutation(orderId, (paymentId: string) =>
- spreeClient.admin.orders.payments.void(orderId, paymentId, {}, { token: token! }),
+ adminClient.orders.payments.void(orderId, paymentId),
)
if (payments.length === 0) return null
@@ -815,7 +809,7 @@ function AddAdjustmentDialog({
}) {
const { token } = useAuth()
const mutation = useOrderMutation(orderId, (params: { label: string; amount: number }) =>
- spreeClient.admin.orders.adjustments.create(orderId, params, { token: token! }),
+ adminClient.orders.adjustments.create(orderId, params),
)
function handleSubmit(e: FormEvent<HTMLFormElement>) {
@@ -870,7 +864,7 @@ function AddAdjustmentDialog({
)
}
-function AdjustmentsCard({ order }: { order: AdminOrder }) {
+function AdjustmentsCard({ order }: { order: Order }) {
const { orderId } = Route.useParams()
const { token } = useAuth()
const adjustments = (order.adjustments ?? []).filter(
@@ -879,7 +873,7 @@ function AdjustmentsCard({ order }: { order: AdminOrder }) {
const [addOpen, setAddOpen] = useState(false)
const deleteMutation = useOrderMutation(orderId, (adjustmentId: string) =>
- spreeClient.admin.orders.adjustments.delete(orderId, adjustmentId, { token: token! }),
+ adminClient.orders.adjustments.delete(orderId, adjustmentId),
)
return (
@@ -989,7 +983,7 @@ function SummaryRow({
)
}
-function OrderSummaryCard({ order }: { order: AdminOrder }) {
+function OrderSummaryCard({ order }: { order: Order }) {
const outstandingBalance = Number.parseFloat(order.total) - Number.parseFloat(order.payment_total)
return (
@@ -1062,7 +1056,7 @@ function AddressBlock({
address,
}: {
title: string
- address: AdminAddress | null | undefined
+ address: Address | null | undefined
}) {
return (
<div>
@@ -1095,13 +1089,13 @@ function EditAddressDialog({
}: {
orderId: string
type: 'ship_address' | 'bill_address'
- address: AdminAddress | null | undefined
+ address: Address | null | undefined
open: boolean
onOpenChange: (open: boolean) => void
}) {
const { token } = useAuth()
const mutation = useOrderMutation(orderId, (params: Record<string, unknown>) =>
- spreeClient.admin.orders.update(orderId, { [type]: params } as any, { token: token! }),
+ adminClient.orders.update(orderId, { [type]: params } as any),
)
function handleSubmit(e: FormEvent<HTMLFormElement>) {
@@ -1202,7 +1196,7 @@ function EditAddressDialog({
)
}
-function CustomerCard({ order }: { order: AdminOrder }) {
+function CustomerCard({ order }: { order: Order }) {
const { orderId } = Route.useParams()
const user = order.user
const [editAddress, setEditAddress] = useState<'ship_address' | 'bill_address' | null>(null)
@@ -1278,12 +1272,12 @@ function CustomerCard({ order }: { order: AdminOrder }) {
// Special Instructions
// ---------------------------------------------------------------------------
-function SpecialInstructionsCard({ order }: { order: AdminOrder }) {
+function SpecialInstructionsCard({ order }: { order: Order }) {
const { orderId } = Route.useParams()
const { token } = useAuth()
const [editing, setEditing] = useState(false)
const mutation = useOrderMutation(orderId, (params: { special_instructions: string }) =>
- spreeClient.admin.orders.update(orderId, params, { token: token! }),
+ adminClient.orders.update(orderId, params),
)
function handleSubmit(e: FormEvent<HTMLFormElement>) {
@@ -1334,12 +1328,12 @@ function SpecialInstructionsCard({ order }: { order: AdminOrder }) {
// Internal Note
// ---------------------------------------------------------------------------
-function InternalNoteCard({ order }: { order: AdminOrder }) {
+function InternalNoteCard({ order }: { order: Order }) {
const { orderId } = Route.useParams()
const { token } = useAuth()
const [editing, setEditing] = useState(false)
const mutation = useOrderMutation(orderId, (params: { internal_note: string }) =>
- spreeClient.admin.orders.update(orderId, params, { token: token! }),
+ adminClient.orders.update(orderId, params),
)
function handleSubmit(e: FormEvent<HTMLFormElement>) {
diff --git a/packages/admin/src/routes/_authenticated/orders/drafts.tsx b/packages/admin/src/routes/_authenticated/orders/drafts.tsx
index 40d54aae43..3a60fcb9fc 100644
--- a/packages/admin/src/routes/_authenticated/orders/drafts.tsx
+++ b/packages/admin/src/routes/_authenticated/orders/drafts.tsx
@@ -1,9 +1,8 @@
import { createFileRoute } from '@tanstack/react-router'
import { PlusIcon } from 'lucide-react'
-import { spreeClient } from '@/client'
+import { adminClient } from '@/client'
import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'
import { Button } from '@/components/ui/button'
-import { useAuth } from '@/hooks/use-auth'
import '@/tables/orders'
export const Route = createFileRoute('/_authenticated/orders/drafts')({
@@ -13,13 +12,12 @@ export const Route = createFileRoute('/_authenticated/orders/drafts')({
function DraftOrdersPage() {
const searchParams = Route.useSearch()
- const { token } = useAuth()
return (
<ResourceTable
tableKey="orders"
queryKey="draft-orders"
- queryFn={(params) => spreeClient.admin.orders.list(params, { token: token! })}
+ queryFn={(params) => adminClient.orders.list(params)}
searchParams={searchParams}
defaultParams={{ incomplete: 1 }}
title="Draft Orders"
diff --git a/packages/admin/src/routes/_authenticated/orders/index.tsx b/packages/admin/src/routes/_authenticated/orders/index.tsx
index aee450aa63..55488d4f49 100644
--- a/packages/admin/src/routes/_authenticated/orders/index.tsx
+++ b/packages/admin/src/routes/_authenticated/orders/index.tsx
@@ -1,9 +1,8 @@
import { createFileRoute } from '@tanstack/react-router'
import { PlusIcon } from 'lucide-react'
-import { spreeClient } from '@/client'
+import { adminClient } from '@/client'
import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'
import { Button } from '@/components/ui/button'
-import { useAuth } from '@/hooks/use-auth'
import '@/tables/orders'
export const Route = createFileRoute('/_authenticated/orders/')({
@@ -13,13 +12,12 @@ export const Route = createFileRoute('/_authenticated/orders/')({
function OrdersPage() {
const searchParams = Route.useSearch()
- const { token } = useAuth()
return (
<ResourceTable
tableKey="orders"
queryKey="orders"
- queryFn={(params) => spreeClient.admin.orders.list(params, { token: token! })}
+ queryFn={(params) => adminClient.orders.list(params)}
searchParams={searchParams}
defaultParams={{ complete: 1 }}
actions={
diff --git a/packages/admin/src/routes/_authenticated/products/$productId.tsx b/packages/admin/src/routes/_authenticated/products/$productId.tsx
index 5f9fa5c2b4..8e63007797 100644
--- a/packages/admin/src/routes/_authenticated/products/$productId.tsx
+++ b/packages/admin/src/routes/_authenticated/products/$productId.tsx
@@ -1,4 +1,4 @@
-import type { AdminImage, AdminProduct } from '@spree/sdk'
+import type { Image, Product } from '@spree/admin-sdk'
import { zodResolver } from '@hookform/resolvers/zod'
import { createFileRoute, Link, useRouter } from '@tanstack/react-router'
import {
@@ -61,7 +61,7 @@ export const Route = createFileRoute('/_authenticated/products/$productId')({
// Helpers
// ---------------------------------------------------------------------------
-function productToFormValues(product: AdminProduct): ProductFormValues {
+function productToFormValues(product: Product): ProductFormValues {
const master = product.master_variant
return {
@@ -115,7 +115,7 @@ function ProductDetailPage() {
// Form
// ---------------------------------------------------------------------------
-function ProductForm({ product }: { product: AdminProduct }) {
+function ProductForm({ product }: { product: Product }) {
const { productId } = Route.useParams()
const router = useRouter()
const updateProduct = useUpdateProduct()
@@ -357,7 +357,7 @@ function MediaCard({ productId }: { productId: string }) {
{assets.map((asset) => (
<MediaThumbnail
key={asset.id}
- asset={asset as AdminImage}
+ asset={asset as Image}
onDelete={() => handleDeleteAsset(asset.id)}
/>
))}
@@ -416,7 +416,7 @@ function MediaThumbnail({
asset,
onDelete,
}: {
- asset: AdminImage
+ asset: Image
onDelete: () => void
}) {
const imageUrl = asset.small_url || asset.mini_url || asset.original_url
@@ -549,7 +549,7 @@ function InventoryCard({ form }: FormCardProps) {
// SEO
// ---------------------------------------------------------------------------
-function SEOCard({ form, product }: FormCardProps & { product: AdminProduct }) {
+function SEOCard({ form, product }: FormCardProps & { product: Product }) {
const slug = form.watch('slug')
const metaTitle = form.watch('meta_title')
const metaDescription = form.watch('meta_description')
diff --git a/packages/admin/src/routes/_authenticated/products/index.tsx b/packages/admin/src/routes/_authenticated/products/index.tsx
index 80d6416a25..103ecb672b 100644
--- a/packages/admin/src/routes/_authenticated/products/index.tsx
+++ b/packages/admin/src/routes/_authenticated/products/index.tsx
@@ -1,9 +1,8 @@
import { createFileRoute } from '@tanstack/react-router'
import { PlusIcon } from 'lucide-react'
-import { spreeClient } from '@/client'
+import { adminClient } from '@/client'
import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'
import { Button } from '@/components/ui/button'
-import { useAuth } from '@/hooks/use-auth'
import '@/tables/products'
export const Route = createFileRoute('/_authenticated/products/')({
@@ -13,13 +12,12 @@ export const Route = createFileRoute('/_authenticated/products/')({
function ProductsPage() {
const searchParams = Route.useSearch()
- const { token } = useAuth()
return (
<ResourceTable
tableKey="products"
queryKey="products"
- queryFn={(params) => spreeClient.admin.products.list(params, { token: token! })}
+ queryFn={(params) => adminClient.products.list(params)}
searchParams={searchParams}
actions={
<Button size="sm" className="h-[2.125rem]">
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb
new file mode 100644
index 0000000000..3343934202
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb
@@ -0,0 +1,44 @@
+module Spree
+ module Api
+ module V3
+ module AdminAuthentication
+ extend ActiveSupport::Concern
+
+ included do
+ before_action :authenticate_admin!
+ after_action :set_no_store_cache
+ end
+
+ protected
+
+ # Override JWT audience to require admin tokens
+ def expected_audience
+ Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN
+ end
+
+ # Authenticates admin requests via secret API key OR JWT token.
+ # Secret keys are checked first (server-to-server integrations),
+ # then JWT tokens (admin SPA sessions).
+ def authenticate_admin!
+ # Try secret API key first
+ @current_api_key = Spree::ApiKey.find_by_secret_token(extract_api_key)
+ @current_api_key = nil if @current_api_key && @current_api_key.store_id != current_store.id
+
+ if @current_api_key
+ touch_api_key_if_needed(@current_api_key)
+ return true
+ end
+
+ # Fall back to JWT authentication
+ require_authentication!
+ end
+
+ private
+
+ def set_no_store_cache
+ response.headers['Cache-Control'] = 'private, no-store'
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
index ecfe70db4a..08c57b40e1 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
@@ -6,8 +6,8 @@ module Spree
rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, with: RATE_LIMIT_RESPONSE
rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :refresh, with: RATE_LIMIT_RESPONSE
- skip_before_action :authenticate_user, only: [:create]
- prepend_before_action :require_authentication!, only: [:refresh]
+ skip_before_action :authenticate_admin!, only: [:create]
+ before_action :require_authentication!, only: [:refresh]
# POST /api/v3/admin/auth/login
def create
diff --git a/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb
index d241608f51..c6ff1f7b46 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb
@@ -3,24 +3,7 @@ module Spree
module V3
module Admin
class BaseController < Spree::Api::V3::BaseController
- # Require secret API key for all Admin API requests
- before_action :authenticate_secret_key!
-
- # Admin API responses must never be cached
- after_action :set_no_store_cache
-
- protected
-
- # Override JWT audience to require admin tokens
- def expected_audience
- JWT_AUDIENCE_ADMIN
- end
-
- private
-
- def set_no_store_cache
- response.headers['Cache-Control'] = 'private, no-store'
- end
+ include Spree::Api::V3::AdminAuthentication
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
index 52142138db..03b8af70b7 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
@@ -3,19 +3,10 @@ module Spree
module V3
module Admin
class ResourceController < Spree::Api::V3::ResourceController
- # Require secret API key for all Admin API requests
- before_action :authenticate_secret_key!
-
- # Admin API responses must never be cached
- after_action :set_no_store_cache
+ include Spree::Api::V3::AdminAuthentication
protected
- # Override JWT audience to require admin tokens
- def expected_audience
- JWT_AUDIENCE_ADMIN
- end
-
# Render error from ServiceModule::Result, extracting ActiveModel::Errors
# from the ResultError wrapper to get proper validation_error responses.
def render_result_error(result)
@@ -28,12 +19,6 @@ module Spree
render_service_error(error)
end
end
-
- private
-
- def set_no_store_cache
- response.headers['Cache-Control'] = 'private, no-store'
- end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
new file mode 100644
index 0000000000..60731702d5
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
@@ -0,0 +1,40 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class StoreController < Admin::BaseController
+ # GET /api/v3/admin/store
+ def show
+ authorize! :show, current_store
+ render json: serialize_store
+ end
+
+ # PATCH /api/v3/admin/store
+ def update
+ authorize! :update, current_store
+
+ if current_store.update(permitted_params)
+ render json: serialize_store
+ else
+ render_validation_error(current_store.errors)
+ end
+ end
+
+ private
+
+ def serialize_store
+ serializer_class.new(current_store, params: serializer_params).to_h
+ end
+
+ def serializer_class
+ Spree.api.admin_store_serializer
+ end
+
+ def permitted_params
+ params.permit(Spree::PermittedAttributes.store_attributes)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
new file mode 100644
index 0000000000..b09328853e
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
@@ -0,0 +1,44 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class StoreSerializer < V3::BaseSerializer
+ typelize name: :string, url: :string, code: :string,
+ default_currency: :string, default_locale: :string,
+ supported_currencies: [:string, multi: true],
+ supported_locales: [:string, multi: true],
+ mail_from_address: :string,
+ customer_support_email: [:string, nullable: true],
+ new_order_notifications_email: [:string, nullable: true],
+ description: [:string, nullable: true],
+ address: [:string, nullable: true],
+ contact_phone: [:string, nullable: true],
+ seo_title: [:string, nullable: true],
+ meta_keywords: [:string, nullable: true],
+ meta_description: [:string, nullable: true],
+ default: :boolean,
+ logo_url: [:string, nullable: true],
+ mailer_logo_url: [:string, nullable: true]
+
+ attributes :id, :name, :url, :code,
+ :default_currency, :default_locale,
+ :supported_currencies, :supported_locales,
+ :mail_from_address, :customer_support_email,
+ :new_order_notifications_email,
+ :description, :address, :contact_phone,
+ :seo_title, :meta_keywords, :meta_description,
+ :default,
+ created_at: :iso8601, updated_at: :iso8601
+
+ attribute :logo_url do |store|
+ store.logo.attached? ? Rails.application.routes.url_helpers.url_for(store.logo) : nil
+ end
+
+ attribute :mailer_logo_url do |store|
+ store.mailer_logo.attached? ? Rails.application.routes.url_helpers.url_for(store.mailer_logo) : nil
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 11f84b9067..60cc06a34f 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -95,6 +95,9 @@ Spree::Core::Engine.add_routes do
post 'auth/login', to: 'auth#create'
post 'auth/refresh', to: 'auth#refresh'
+ # Store Settings
+ resource :store, only: [:show, :update], controller: 'store'
+
# Direct Uploads (Active Storage)
resources :direct_uploads, only: [:create]
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 8ac4ee5741..85b24a7fa5 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -196,6 +196,7 @@ module Spree
admin_store_credit_serializer: 'Spree::Api::V3::Admin::StoreCreditSerializer',
admin_payment_source_serializer: 'Spree::Api::V3::Admin::PaymentSourceSerializer',
admin_digital_link_serializer: 'Spree::Api::V3::Admin::DigitalLinkSerializer',
+ admin_store_serializer: 'Spree::Api::V3::Admin::StoreSerializer',
# platform serializers
platform_metafield_serializer: 'Spree::Api::V2::Platform::MetafieldSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb
index 312c14e79e..ecdb851a53 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb
@@ -5,61 +5,91 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
include_context 'API v3 Admin'
- before do
- request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token
- end
-
describe 'POST #create (login)' do
let!(:existing_admin) { create(:admin_user, password: 'password123', password_confirmation: 'password123') }
- it 'authenticates with email and password' do
- post :create, params: { provider: 'email', email: existing_admin.email, password: 'password123' }
+ context 'without any authentication headers' do
+ it 'authenticates with email and password' do
+ post :create, params: { email: existing_admin.email, password: 'password123' }
- expect(response).to have_http_status(:ok)
- expect(json_response['token']).to be_present
- end
+ expect(response).to have_http_status(:ok)
+ expect(json_response['token']).to be_present
+ expect(json_response['user']).to be_present
+ expect(json_response['user']['email']).to eq(existing_admin.email)
+ end
+
+ it 'returns a JWT with admin audience and correct claims' do
+ post :create, params: { email: existing_admin.email, password: 'password123' }
- it 'returns user data on successful login' do
- post :create, params: { provider: 'email', email: existing_admin.email, password: 'password123' }
+ token = json_response['token']
+ secret = Rails.application.secret_key_base
+ payload = JWT.decode(token, secret, true, algorithm: 'HS256').first
- expect(json_response['user']).to be_present
- expect(json_response['user']['email']).to eq(existing_admin.email)
+ expect(payload['aud']).to eq('admin_api')
+ expect(payload['user_type']).to eq('admin')
+ expect(payload['user_id']).to eq(existing_admin.id)
+ expect(payload['iss']).to eq('spree')
+ expect(payload['exp']).to be > Time.current.to_i
+ expect(payload['jti']).to be_present
+ end
+
+ it 'returns user data in the response' do
+ post :create, params: { email: existing_admin.email, password: 'password123' }
+
+ expect(json_response['user']).to have_key('id')
+ expect(json_response['user']).to have_key('email')
+ end
end
- it 'returns a JWT with admin audience' do
- post :create, params: { provider: 'email', email: existing_admin.email, password: 'password123' }
+ context 'with secret API key header (also works)' do
+ before { request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token }
- token = json_response['token']
- secret = Rails.application.secret_key_base
- payload = JWT.decode(token, secret, true, algorithm: 'HS256').first
+ it 'authenticates successfully' do
+ post :create, params: { email: existing_admin.email, password: 'password123' }
- expect(payload['aud']).to eq('admin_api')
- expect(payload['user_type']).to eq('admin')
+ expect(response).to have_http_status(:ok)
+ expect(json_response['token']).to be_present
+ end
+ end
+
+ context 'with explicit email provider' do
+ it 'authenticates successfully' do
+ post :create, params: { provider: 'email', email: existing_admin.email, password: 'password123' }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['token']).to be_present
+ end
end
context 'invalid credentials' do
it 'returns unauthorized for wrong password' do
- post :create, params: { provider: 'email', email: existing_admin.email, password: 'wrong' }
+ post :create, params: { email: existing_admin.email, password: 'wrong' }
expect(response).to have_http_status(:unauthorized)
expect(json_response['error']['code']).to eq('authentication_failed')
end
it 'returns unauthorized for non-existent email' do
- post :create, params: { provider: 'email', email: '[email protected]', password: 'password123' }
+ post :create, params: { email: '[email protected]', password: 'password123' }
expect(response).to have_http_status(:unauthorized)
expect(json_response['error']['code']).to eq('authentication_failed')
end
it 'returns unauthorized for missing email' do
- post :create, params: { provider: 'email', password: 'password123' }
+ post :create, params: { password: 'password123' }
expect(response).to have_http_status(:unauthorized)
end
it 'returns unauthorized for missing password' do
- post :create, params: { provider: 'email', email: existing_admin.email }
+ post :create, params: { email: existing_admin.email }
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ it 'returns unauthorized for empty credentials' do
+ post :create, params: { email: '', password: '' }
expect(response).to have_http_status(:unauthorized)
end
@@ -74,60 +104,69 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
end
end
- context 'without secret API key' do
- before { request.headers['X-Spree-Api-Key'] = nil }
+ context 'with a non-admin user' do
+ let!(:regular_user) { create(:user, password: 'password123', password_confirmation: 'password123') }
it 'returns unauthorized' do
- post :create, params: { provider: 'email', email: existing_admin.email, password: 'password123' }
+ post :create, params: { email: regular_user.email, password: 'password123' }
expect(response).to have_http_status(:unauthorized)
+ expect(json_response['error']['code']).to eq('authentication_failed')
end
end
- context 'with a non-admin user' do
- let!(:regular_user) { create(:user, password: 'password123', password_confirmation: 'password123') }
+ it 'does not leak timing information between existing and non-existing emails' do
+ # Both should return the same error code regardless of whether the email exists
+ post :create, params: { email: existing_admin.email, password: 'wrong' }
+ existing_error = json_response['error']['code']
- it 'returns unauthorized' do
- post :create, params: { provider: 'email', email: regular_user.email, password: 'password123' }
+ post :create, params: { email: '[email protected]', password: 'wrong' }
+ nonexistent_error = json_response['error']['code']
- expect(response).to have_http_status(:unauthorized)
- expect(json_response['error']['code']).to eq('authentication_failed')
- end
+ expect(existing_error).to eq(nonexistent_error)
end
end
describe 'POST #refresh' do
- before do
- request.headers['Authorization'] = "Bearer #{admin_jwt_token}"
- end
+ context 'with valid admin JWT token' do
+ before { request.headers['Authorization'] = "Bearer #{admin_jwt_token}" }
- it 'returns a new token' do
- post :refresh
+ it 'returns a new token' do
+ post :refresh
- expect(response).to have_http_status(:ok)
- expect(json_response['token']).to be_present
- end
+ expect(response).to have_http_status(:ok)
+ expect(json_response['token']).to be_present
+ expect(json_response['token']).not_to eq(admin_jwt_token)
+ end
- it 'returns user data' do
- post :refresh
+ it 'returns user data' do
+ post :refresh
- expect(json_response['user']).to be_present
- expect(json_response['user']['email']).to eq(admin_user.email)
- end
+ expect(json_response['user']).to be_present
+ expect(json_response['user']['email']).to eq(admin_user.email)
+ end
- it 'returns a JWT with admin audience' do
- post :refresh
+ it 'returns a JWT with admin audience' do
+ post :refresh
- token = json_response['token']
- secret = Rails.application.secret_key_base
- payload = JWT.decode(token, secret, true, algorithm: 'HS256').first
+ token = json_response['token']
+ secret = Rails.application.secret_key_base
+ payload = JWT.decode(token, secret, true, algorithm: 'HS256').first
- expect(payload['aud']).to eq('admin_api')
+ expect(payload['aud']).to eq('admin_api')
+ expect(payload['user_type']).to eq('admin')
+ expect(payload['user_id']).to eq(admin_user.id)
+ end
+
+ it 'returns user data in the response' do
+ post :refresh
+
+ expect(json_response['user']).to have_key('id')
+ expect(json_response['user']).to have_key('email')
+ end
end
context 'without token' do
- before { request.headers['Authorization'] = nil }
-
it 'returns unauthorized' do
post :refresh
@@ -137,7 +176,7 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
end
context 'with invalid token' do
- before { request.headers['Authorization'] = 'Bearer invalid' }
+ before { request.headers['Authorization'] = 'Bearer invalid_garbage_token' }
it 'returns unauthorized' do
post :refresh
@@ -148,7 +187,13 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
end
context 'with expired token' do
- let(:expired_token) { Spree::Api::V3::TestingSupport.generate_jwt(admin_user, expiration: -1.hour.to_i, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN) }
+ let(:expired_token) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ admin_user,
+ expiration: -1.hour.to_i,
+ audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN
+ )
+ end
before { request.headers['Authorization'] = "Bearer #{expired_token}" }
@@ -161,7 +206,12 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
end
context 'with store API token (wrong audience)' do
- let(:store_token) { Spree::Api::V3::TestingSupport.generate_jwt(admin_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_STORE) }
+ let(:store_token) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ admin_user,
+ audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_STORE
+ )
+ end
before { request.headers['Authorization'] = "Bearer #{store_token}" }
@@ -172,5 +222,36 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller do
expect(json_response['error']['code']).to eq('authentication_required')
end
end
+
+ context 'with secret API key only (no JWT)' do
+ before { request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token }
+
+ it 'returns unauthorized because refresh requires JWT' do
+ post :refresh
+
+ expect(response).to have_http_status(:unauthorized)
+ expect(json_response['error']['code']).to eq('authentication_required')
+ end
+ end
+
+ context 'with tampered token' do
+ let(:tampered_token) { admin_jwt_token + 'tampered' }
+
+ before { request.headers['Authorization'] = "Bearer #{tampered_token}" }
+
+ it 'returns unauthorized' do
+ post :refresh
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+ end
+
+ describe 'response headers' do
+ it 'sets no-store cache control' do
+ post :create, params: { email: '[email protected]', password: 'whatever' }
+
+ expect(response.headers['Cache-Control']).to include('no-store')
+ end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb
index f70d1a43ae..0381555e7d 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb
@@ -26,7 +26,7 @@ RSpec.describe Spree::Api::V3::Admin::BaseController, type: :controller do
routes.draw { get 'index' => 'spree/api/v3/admin/test#index' }
end
- describe 'secret API key authentication' do
+ describe 'authentication via secret API key' do
context 'with valid secret API key' do
before { request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token }
@@ -37,16 +37,6 @@ RSpec.describe Spree::Api::V3::Admin::BaseController, type: :controller do
end
end
- context 'without API key' do
- it 'returns 401 unauthorized' do
- get :index
-
- expect(response).to have_http_status(:unauthorized)
- expect(json_response['error']['code']).to eq('invalid_token')
- expect(json_response['error']['message']).to include('secret API key')
- end
- end
-
context 'with invalid API key' do
before { request.headers['X-Spree-Api-Key'] = 'sk_invalid' }
@@ -54,7 +44,6 @@ RSpec.describe Spree::Api::V3::Admin::BaseController, type: :controller do
get :index
expect(response).to have_http_status(:unauthorized)
- expect(json_response['error']['code']).to eq('invalid_token')
end
end
@@ -97,27 +86,189 @@ RSpec.describe Spree::Api::V3::Admin::BaseController, type: :controller do
end
end
+ describe 'authentication via JWT token' do
+ context 'with valid admin JWT token' do
+ before { request.headers['Authorization'] = "Bearer #{admin_jwt_token}" }
+
+ it 'returns 200 and sets current_user' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['user_id']).to eq(admin_user.id)
+ end
+ end
+
+ context 'with expired JWT token' do
+ let(:expired_token) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ admin_user,
+ expiration: -1.hour.to_i,
+ audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN
+ )
+ end
+
+ before { request.headers['Authorization'] = "Bearer #{expired_token}" }
+
+ it 'returns 401 unauthorized' do
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ context 'with store JWT token (wrong audience)' do
+ let(:store_jwt_token) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ admin_user,
+ audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_STORE
+ )
+ end
+
+ before { request.headers['Authorization'] = "Bearer #{store_jwt_token}" }
+
+ it 'returns 401 unauthorized' do
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ context 'with tampered JWT token' do
+ before { request.headers['Authorization'] = "Bearer #{admin_jwt_token}tampered" }
+
+ it 'returns 401 unauthorized' do
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ context 'with completely invalid JWT token' do
+ before { request.headers['Authorization'] = 'Bearer not_a_real_jwt_at_all' }
+
+ it 'returns 401 unauthorized' do
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ context 'with a non-admin user JWT token' do
+ let(:customer) { create(:user) }
+ let(:customer_admin_jwt) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ customer,
+ audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN
+ )
+ end
+
+ before { request.headers['Authorization'] = "Bearer #{customer_admin_jwt}" }
+
+ it 'authenticates the user (authorization is handled separately)' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['user_id']).to eq(customer.id)
+ end
+ end
+ end
+
+ describe 'authentication priority (secret key vs JWT)' do
+ context 'with both valid secret key and valid JWT' do
+ before do
+ request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token
+ request.headers['Authorization'] = "Bearer #{admin_jwt_token}"
+ end
+
+ it 'authenticates successfully via secret key' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ context 'with invalid secret key and valid JWT' do
+ before do
+ request.headers['X-Spree-Api-Key'] = 'sk_invalid'
+ request.headers['Authorization'] = "Bearer #{admin_jwt_token}"
+ end
+
+ it 'falls back to JWT authentication' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['user_id']).to eq(admin_user.id)
+ end
+ end
+
+ context 'with both invalid secret key and invalid JWT' do
+ before do
+ request.headers['X-Spree-Api-Key'] = 'sk_invalid'
+ request.headers['Authorization'] = 'Bearer invalid_token'
+ end
+
+ it 'returns 401 unauthorized' do
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+ end
+
+ describe 'no authentication' do
+ it 'returns 401 unauthorized' do
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ describe 'API key query parameter rejection' do
+ it 'does not accept API key via query parameter' do
+ get :index, params: { api_key: secret_api_key.plaintext_token }
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ describe 'response headers' do
+ before { request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token }
+
+ it 'sets no-store cache control' do
+ get :index
+
+ expect(response.headers['Cache-Control']).to include('no-store')
+ end
+
+ it 'sets private cache control' do
+ get :index
+
+ expect(response.headers['Cache-Control']).to include('private')
+ end
+ end
+
describe 'JWT audience enforcement' do
before { request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token }
context 'with admin JWT token (audience: admin_api)' do
before { request.headers['Authorization'] = "Bearer #{admin_jwt_token}" }
- it 'authenticates successfully' do
+ it 'authenticates successfully and sets current_user' do
get :index
expect(response).to have_http_status(:ok)
- expect(json_response['user_id']).to eq(admin_user.id)
+ # Secret key takes priority, so user_id won't be set from JWT
+ # To test JWT audience, we remove the secret key
end
end
- context 'with store JWT token (audience: store_api)' do
+ context 'with store JWT token (audience: store_api) and valid secret key' do
let(:customer) { create(:user) }
let(:store_jwt_token) { Spree::Api::V3::TestingSupport.generate_jwt(customer, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_STORE) }
before { request.headers['Authorization'] = "Bearer #{store_jwt_token}" }
- it 'rejects the token silently (optional auth)' do
+ it 'authenticates via secret key, ignoring the store JWT' do
get :index
expect(response).to have_http_status(:ok)
@@ -125,8 +276,8 @@ RSpec.describe Spree::Api::V3::Admin::BaseController, type: :controller do
end
end
- context 'without JWT token' do
- it 'proceeds without user (optional auth)' do
+ context 'without JWT token but with valid secret key' do
+ it 'proceeds without user (optional auth via JWT)' do
get :index
expect(response).to have_http_status(:ok)
@@ -135,11 +286,29 @@ RSpec.describe Spree::Api::V3::Admin::BaseController, type: :controller do
end
end
- describe 'API key query parameter rejection' do
- it 'does not accept API key via query parameter' do
- get :index, params: { api_key: secret_api_key.plaintext_token }
+ describe 'JWT-only audience enforcement' do
+ context 'with admin JWT only (no secret key)' do
+ before { request.headers['Authorization'] = "Bearer #{admin_jwt_token}" }
- expect(response).to have_http_status(:unauthorized)
+ it 'authenticates and sets current_user' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['user_id']).to eq(admin_user.id)
+ end
+ end
+
+ context 'with store JWT only (wrong audience, no secret key)' do
+ let(:customer) { create(:user) }
+ let(:store_jwt_token) { Spree::Api::V3::TestingSupport.generate_jwt(customer, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_STORE) }
+
+ before { request.headers['Authorization'] = "Bearer #{store_jwt_token}" }
+
+ it 'rejects the token because audience does not match' do
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ end
end
end
end