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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add countries endpoint and reusable address components
Damian Legawiec6f6001234f5d
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 6c57ee651f..e30dd59a78 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -38,7 +38,7 @@ export interface MeResponse {};permissions: PermissionRule[];}-import type { Store, Product, Order, Media, Category, TaxCategory } from './types';+import type { Store, Product, Order, Media, Category, TaxCategory, Country } from './types';import type {StoreUpdateParams,ProductUpdateParams,@@ -224,6 +224,24 @@ export class AdminClient {}),};+ // ============================================+ // Countries+ // ============================================++ readonly countries = {+ list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Country>> =>+ this.request<PaginatedResponse<Country>>('GET', '/countries', {+ ...options,+ params: params ? transformListParams(params) : undefined,+ }),++ get: (iso: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Country> =>+ this.request<Country>('GET', `/countries/${iso}`, {+ ...options,+ params: getParams(params),+ }),+ };+// ============================================// Direct Uploads (Active Storage)// ============================================diff --git a/packages/admin/src/components/address-block.tsx b/packages/admin/src/components/address-block.tsxnew file mode 100644index 0000000000..5a2b3cbb3f--- /dev/null+++ b/packages/admin/src/components/address-block.tsx@@ -0,0 +1,30 @@+import type { Address } from '@spree/admin-sdk'++export 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.postal_code].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>+ )+}diff --git a/packages/admin/src/components/address-form-dialog.tsx b/packages/admin/src/components/address-form-dialog.tsxnew file mode 100644index 0000000000..b67524c9db--- /dev/null+++ b/packages/admin/src/components/address-form-dialog.tsx@@ -0,0 +1,209 @@+import type { Address } from '@spree/admin-sdk'+import { type FormEvent, useMemo, useState } from 'react'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { Input } from '@/components/ui/input'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { useCountries } from '@/hooks/use-countries'++export interface AddressParams {+ first_name: string+ last_name: string+ address1: string+ address2: string+ city: string+ postal_code: string+ country_iso: string+ state_abbr: string+ phone: string+}++export function AddressFormDialog({+ address,+ open,+ onOpenChange,+ onSave,+ title = 'Edit Address',+ isPending = false,+}: {+ address: Address | null | undefined+ open: boolean+ onOpenChange: (open: boolean) => void+ onSave: (address: AddressParams) => void+ title?: string+ isPending?: boolean+}) {+ const { countries } = useCountries()+ const [selectedCountryIso, setSelectedCountryIso] = useState<string>(+ address?.country_iso ?? '',+ )++ const selectedCountry = useMemo(+ () => countries.find((c) => c.iso === selectedCountryIso),+ [countries, selectedCountryIso],+ )++ const statesRequired = selectedCountry?.states_required ?? false+ const states = selectedCountry?.states ?? []++ function handleSubmit(e: FormEvent<HTMLFormElement>) {+ e.preventDefault()+ const fd = new FormData(e.currentTarget)+ onSave({+ first_name: fd.get('first_name') as string,+ last_name: fd.get('last_name') as string,+ address1: fd.get('address1') as string,+ address2: fd.get('address2') as string,+ city: fd.get('city') as string,+ postal_code: fd.get('postal_code') as string,+ country_iso: fd.get('country_iso') as string,+ state_abbr: fd.get('state_abbr') as string,+ phone: fd.get('phone') as string,+ })+ }++ 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="addr-fn">First Name</FieldLabel>+ <Input+ id="addr-fn"+ name="first_name"+ defaultValue={address?.first_name ?? ''}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor="addr-ln">Last Name</FieldLabel>+ <Input+ id="addr-ln"+ name="last_name"+ defaultValue={address?.last_name ?? ''}+ />+ </Field>+ </div>+ <Field>+ <FieldLabel htmlFor="addr-a1">Address</FieldLabel>+ <Input+ id="addr-a1"+ name="address1"+ defaultValue={address?.address1 ?? ''}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor="addr-a2">Apartment, suite, etc.</FieldLabel>+ <Input+ id="addr-a2"+ name="address2"+ defaultValue={address?.address2 ?? ''}+ />+ </Field>+ <div className="grid grid-cols-2 gap-3">+ <Field>+ <FieldLabel htmlFor="addr-city">City</FieldLabel>+ <Input+ id="addr-city"+ name="city"+ defaultValue={address?.city ?? ''}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor="addr-zip">Postal Code</FieldLabel>+ <Input+ id="addr-zip"+ name="postal_code"+ defaultValue={address?.postal_code ?? ''}+ />+ </Field>+ </div>+ <Field>+ <FieldLabel>Country</FieldLabel>+ <Select+ name="country_iso"+ defaultValue={address?.country_iso ?? ''}+ onValueChange={setSelectedCountryIso}+ >+ <SelectTrigger className="w-full">+ <SelectValue placeholder="Select country" />+ </SelectTrigger>+ <SelectContent>+ {countries.map((country) => (+ <SelectItem key={country.iso} value={country.iso}>+ {country.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ <Field>+ <FieldLabel htmlFor="addr-state">State / Province</FieldLabel>+ {statesRequired && states.length > 0 ? (+ <Select+ name="state_abbr"+ defaultValue={address?.state_abbr ?? ''}+ >+ <SelectTrigger className="w-full">+ <SelectValue placeholder="Select state" />+ </SelectTrigger>+ <SelectContent>+ {states.map((state) => (+ <SelectItem key={state.abbr} value={state.abbr}>+ {state.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <Input+ id="addr-state"+ name="state_abbr"+ defaultValue={address?.state_abbr ?? address?.state_name ?? ''}+ />+ )}+ </Field>+ <Field>+ <FieldLabel htmlFor="addr-phone">Phone</FieldLabel>+ <Input+ id="addr-phone"+ name="phone"+ defaultValue={address?.phone ?? ''}+ />+ </Field>+ </FieldGroup>+ </DialogBody>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button type="submit" disabled={isPending}>+ {isPending ? 'Saving...' : 'Save'}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}diff --git a/packages/admin/src/hooks/use-countries.ts b/packages/admin/src/hooks/use-countries.tsnew file mode 100644index 0000000000..f8213863da--- /dev/null+++ b/packages/admin/src/hooks/use-countries.ts@@ -0,0 +1,16 @@+import type { Country } from '@spree/admin-sdk'+import { useQuery } from '@tanstack/react-query'+import { adminClient } from '@/client'++export function useCountries() {+ const { data, isLoading } = useQuery({+ queryKey: ['countries'],+ queryFn: () =>+ adminClient.countries.list({ limit: 250, expand: ['states'] }),+ staleTime: 1000 * 60 * 30, // 30 minutes — countries rarely change+ })++ const countries: Country[] = data?.data ?? []++ return { countries, isLoading }+}diff --git a/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx b/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsxindex 93c148d901..7b0c999892 100644--- a/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx@@ -1,6 +1,8 @@-import type { Address, Order } from '@spree/admin-sdk'+import type { Order } from '@spree/admin-sdk'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { createFileRoute } from '@tanstack/react-router'+import { AddressBlock } from '@/components/address-block'+import { AddressFormDialog, type AddressParams } from '@/components/address-form-dialog'import { BackButton } from '@/components/back-button'import {CreditCardIcon,@@ -1047,156 +1049,23 @@ function OrderSummaryCard({ order }: { order: Order }) {// 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.postal_code].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: 'shipping_address' | 'billing_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(- {- first_name: fd.get('first_name') as string,- last_name: fd.get('last_name') as string,- address1: fd.get('address1') as string,- city: fd.get('city') as string,- postal_code: fd.get('postal_code') 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 === 'shipping_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="first_name"- defaultValue={address?.first_name ?? ''}- />- </Field>- <Field>- <FieldLabel htmlFor={`${type}-ln`}>Last Name</FieldLabel>- <Input id={`${type}-ln`} name="last_name" defaultValue={address?.last_name ?? ''} />- </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="postal_code" defaultValue={address?.postal_code ?? ''} />- </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 queryClient = useQueryClient()const user = order.customerconst [editAddress, setEditAddress] = useState<'shipping_address' | 'billing_address' | null>(null)+ const addressMutation = useMutation({+ mutationFn: (params: { type: 'shipping_address' | 'billing_address'; address: AddressParams }) =>+ adminClient.orders.update(orderId, { [params.type]: params.address } as any),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['order', orderId] })+ setEditAddress(null)+ },+ })++ const editTitle = editAddress === 'shipping_address' ? 'Edit Shipping Address' : 'Edit Billing Address'+return (<><Card>@@ -1252,12 +1121,13 @@ function CustomerCard({ order }: { order: Order }) {</Card>{editAddress && (- <EditAddressDialog- orderId={orderId}- type={editAddress}+ <AddressFormDialog+ title={editTitle}address={editAddress === 'shipping_address' ? order.shipping_address : order.billing_address}open={!!editAddress}onOpenChange={(open) => !open && setEditAddress(null)}+ onSave={(address) => addressMutation.mutate({ type: editAddress, address })}+ isPending={addressMutation.isPending}/>)}</>diff --git a/spree/api/app/controllers/spree/api/v3/admin/countries_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/countries_controller.rbnew file mode 100644index 0000000000..cc521c6459--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/countries_controller.rb@@ -0,0 +1,27 @@+module Spree+ module Api+ module V3+ module Admin+ class CountriesController < ResourceController+ protected++ def model_class+ Spree::Country+ end++ def serializer_class+ Spree.api.admin_country_serializer+ end++ def scope+ Spree::Country.all.order(:name)+ end++ def find_resource+ scope.find_by!(iso: params[:id].upcase)+ end+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 84ca88b717..ce24f75011 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -124,6 +124,9 @@ Spree::Core::Engine.add_routes do# Tax Categoriesresources :tax_categories, only: [:index, :show]+ # Countries (with ?expand=states for state/province dropdown)+ resources :countries, only: [:index, :show]+# Ordersresources :orders domember do