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
Move the shared 6.0 documentation changes into the v6 docs
Damian Legawiec97de5e842d32
diff --git a/docs/developer/core-concepts/imports-exports.mdx b/docs/developer/core-concepts/imports-exports.mdxindex 7bbc54dd0a..2c9d83454f 100644--- a/docs/developer/core-concepts/imports-exports.mdx+++ b/docs/developer/core-concepts/imports-exports.mdx@@ -270,12 +270,24 @@ module Spreehas_many :mappings # Field mappingshas_many :rows # CSV rows to process- # Statuses. Each move between them is a workflow — Spree::Imports::- # StartMapping, CompleteMapping, StartProcessing, Complete and- # RetryFailedRows — so every step of the pipeline can be hooked.- include Spree::HasStatus- has_status :pending, :mapping, :completed_mapping, :processing, :completed, :failed,- default: :pending+ # State machine+ state_machine initial: :pending do+ event :start_mapping do+ transition to: :mapping+ end+ event :complete_mapping do+ transition from: :mapping, to: :completed_mapping+ end+ event :start_processing do+ transition from: :completed_mapping, to: :processing+ end+ event :complete do+ transition from: :processing, to: :completed+ end+ event :fail do+ transition to: :failed+ end+ end# Key methodsdef import_schema # Returns schema class instancediff --git a/docs/developer/core-concepts/store-credits-gift-cards.mdx b/docs/developer/core-concepts/store-credits-gift-cards.mdxindex 0cbe7e7405..8d2dd0b566 100644--- a/docs/developer/core-concepts/store-credits-gift-cards.mdx+++ b/docs/developer/core-concepts/store-credits-gift-cards.mdx@@ -179,7 +179,7 @@ erDiagramGiftCard {string code- string status+ string statedecimal amountdecimal amount_useddecimal amount_authorized@@ -204,26 +204,28 @@ erDiagram| `code` | Unique redemption code | `abc1234def` || `amount` | Total gift card value | `50.00` || `amount_used` | Amount already redeemed | `0.00` |-| `status` | Current status | `active` |+| `state` | Current state | `active` || `currency` | Currency code | `USD` || `expires_at` | Optional expiration date | `2025-12-31` |-### Gift Card Statuses+### Gift Card States-| Status | Description | How it gets there |-|-------|-------------|-------------------|-| `active` | Available for redemption | The status a card is created with |-| `partially_redeemed` | Some value has been redeemed | `Spree::GiftCards::Redeem`, when a balance remains |-| `redeemed` | Fully redeemed | `Spree::GiftCards::Redeem`, when nothing is left |-| `canceled` | Voided, and no longer spendable | `Spree::GiftCards::Cancel` |--Redemption does not need the caller to choose: `Spree::GiftCards::Redeem`-looks at what is left on the card and marks it partially or fully redeemed-accordingly. A card can be partially redeemed more than once, and each spend-publishes its own event.+```mermaid+stateDiagram-v2+ [*] --> active: Created+ active --> partially_redeemed: Partial redemption+ active --> redeemed: Full redemption+ active --> canceled: Admin cancels+ partially_redeemed --> redeemed: Remaining redeemed+ partially_redeemed --> partially_redeemed: Another partial redemption+```-Cancelling is refused once a card has been spent against, so cancellation can-never take back value a customer has already used.+| State | Description |+|-------|-------------|+| `active` | Available for redemption |+| `partially_redeemed` | Some value has been redeemed |+| `redeemed` | Fully redeemed |+| `canceled` | Canceled by admin |<Note>Gift cards can also be `expired` if `expires_at` date has passed and the card hasn't been fully redeemed.diff --git a/docs/docs.json b/docs/docs.jsonindex a244c87353..081686a8c5 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -991,7 +991,7 @@"developer/core-concepts/taxes","v6/developer/core-concepts/taxes-discounts-fees","v6/developer/core-concepts/promotions",- "developer/core-concepts/store-credits-gift-cards"+ "v6/developer/core-concepts/store-credits-gift-cards"]},{@@ -1013,7 +1013,7 @@"developer/core-concepts/translations","developer/core-concepts/slugs","developer/core-concepts/metafields",- "developer/core-concepts/imports-exports"+ "v6/developer/core-concepts/imports-exports"]}]diff --git a/docs/v6/developer/core-concepts/imports-exports.mdx b/docs/v6/developer/core-concepts/imports-exports.mdxnew file mode 100644index 0000000000..7bbc54dd0a--- /dev/null+++ b/docs/v6/developer/core-concepts/imports-exports.mdx@@ -0,0 +1,741 @@+---+title: Imports & Exports+---++## Overview++Spree provides a comprehensive bulk data import and export system for managing large datasets. The system supports CSV file processing with configurable field mapping, asynchronous processing via background jobs, and real-time progress tracking in the admin interface.++### Import/Export System Diagram++```mermaid+erDiagram+ Import {+ string number+ string type+ string status+ bigint owner_id+ string owner_type+ bigint user_id+ }++ ImportMapping {+ string schema_field+ string file_column+ }++ ImportRow {+ integer row_number+ text data+ string status+ text validation_errors+ }++ ImportSchema {+ array fields+ }++ RowProcessor {+ hash attributes+ }++ Export {+ string number+ string type+ integer format+ jsonb search_params+ }++ Store {+ string name+ }++ Import ||--|| Store : "belongs to (owner)"+ Import ||--o{ ImportMapping : "has many"+ Import ||--o{ ImportRow : "has many"+ Import ||--|| ImportSchema : "uses"+ ImportRow ||--|| RowProcessor : "processed by"+ Export ||--|| Store : "belongs to"+```++## Architecture++The import/export system uses several design patterns:++1. **Single Table Inheritance (STI)**: Import and Export types inherit from base classes+2. **State Machine**: Imports progress through states (pending → mapping → processing → completed)+3. **Schema Definition**: ImportSchema classes define expected fields and validation+4. **Row Processors**: Transform CSV rows into database records+5. **Event-Driven Processing**: Background jobs handle heavy lifting asynchronously+6. **Registry Pattern**: Types registered in `Spree.import_types` and `Spree.export_types`++---++## Exports++Exports generate CSV files from filtered database records.++### Built-in Export Types++| Type | Description | Multi-line |+|------|-------------|------------|+| `Spree::Exports::Products` | Products with all variants | Yes |+| `Spree::Exports::ProductTranslations` | Product translations for non-default store locales | Yes |+| `Spree::Exports::Orders` | Orders with line items | Yes |+| `Spree::Exports::Customers` | Customer accounts | No |+| `Spree::Exports::GiftCards` | Gift cards | No |+| `Spree::Exports::NewsletterSubscribers` | Newsletter subscribers | No |+| `Spree::Exports::CouponCodes` | Promotion coupon codes | No |++### Export Model++The base `Spree::Export` class provides:++```ruby+module Spree+ class Export < Spree.base_class+ # Associations+ belongs_to :store+ belongs_to :user # Admin who created export++ # Attachments+ has_one_attached :attachment # Generated CSV file++ # Key methods+ def csv_headers # Define column headers+ def scope # Base query with store/vendor filtering+ def scope_includes # Eager loading associations+ def records_to_export # Apply ransack filters+ def multi_line_csv? # True if records produce multiple rows+ def generate # Create CSV and attach file+ end+end+```++### Creating a Custom Exporter++**Step 1: Create the Export Class**++```ruby app/models/spree/exports/subscriptions.rb+module Spree+ module Exports+ class Subscriptions < Spree::Export+ # Define CSV column headers+ def csv_headers+ %w[id email plan_name status created_at] + metafields_headers+ end++ # Eager load associations to avoid N+1 queries+ def scope_includes+ [:user, :plan, { metafields: :metafield_definition }]+ end++ # Override scope if needed (e.g., exclude cancelled)+ def scope+ super.where.not(status: 'cancelled')+ end++ # Set to true if each record produces multiple CSV rows+ def multi_line_csv?+ false+ end+ end+ end+end+```++**Step 2: Add `to_csv` Method to Your Model**++```ruby app/models/spree/subscription.rb+module Spree+ class Subscription < Spree.base_class+ def to_csv(store)+ [+ id,+ user&.email,+ plan&.name,+ status,+ created_at.iso8601+ ] + metafields_csv_values(store)+ end++ private++ def metafields_csv_values(store)+ Spree::MetafieldDefinition.for_resource_type(self.class.name).order(:namespace, :key).map do |definition|+ metafields.find { |m| m.metafield_definition_id == definition.id }&.value+ end+ end+ end+end+```++**Step 3: Register the Export Type**++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.export_types << Spree::Exports::Subscriptions+end+```++**Step 4: Add Translations**++```yaml config/locales/en.yml+en:+ spree:+ subscriptions: Subscriptions+```++### Multi-line Exports++For exports where each record produces multiple rows (like products with variants):++```ruby app/models/spree/exports/orders_with_items.rb+module Spree+ module Exports+ class OrdersWithItems < Spree::Export+ def multi_line_csv?+ true+ end++ def csv_headers+ %w[order_number line_item_sku quantity price]+ end++ def scope_includes+ [line_items: :variant]+ end+ end+ end+end+```++```ruby app/models/spree/order.rb+# In the Order model+def to_csv(store)+ line_items.map do |item|+ [number, item.variant.sku, item.quantity, item.price]+ end+end+```++### Export Filtering++Exports support [Ransack filtering via `search_params`](/api-reference/admin-api/querying):++```ruby+# In admin, users can filter before exporting+export = Spree::Exports::Products.new(+ store: current_store,+ user: current_user,+ search_params: { name_cont: 'shirt', status_eq: 'active' }.to_json,+ record_selection: 'filtered' # or 'all' to ignore filters+)+```++---++## Imports++Imports process CSV files to create or update database records.++### Built-in Import Types++| Type | Description |+|------|-------------|+| `Spree::Imports::Products` | Products and variants |+| `Spree::Imports::ProductTranslations` | Product translations (matched by slug) |+| `Spree::Imports::Customers` | Customers |++### Import Workflow++```+1. Upload CSV → pending+2. Auto-map columns → mapping+3. User confirms mapping → completed_mapping+4. Parse rows (CreateRowsJob) → processing+5. Process rows (ProcessRowsJob) → completed/failed+```++### Import Components++#### Import Model++```ruby+module Spree+ class Import < Spree.base_class+ # Associations+ belongs_to :owner, polymorphic: true # Store or Vendor+ belongs_to :user+ has_many :mappings # Field mappings+ has_many :rows # CSV rows to process++ # Statuses. Each move between them is a workflow — Spree::Imports::+ # StartMapping, CompleteMapping, StartProcessing, Complete and+ # RetryFailedRows — so every step of the pipeline can be hooked.+ include Spree::HasStatus+ has_status :pending, :mapping, :completed_mapping, :processing, :completed, :failed,+ default: :pending++ # Key methods+ def import_schema # Returns schema class instance+ def row_processor_class # Returns processor class+ def schema_fields # Fields from schema + metafields+ def mapping_done? # All required fields mapped?+ end+end+```++#### Import Schema++Defines expected CSV fields:++```ruby+module Spree+ class ImportSchema+ FIELDS = []++ def fields+ self.class::FIELDS+ end++ def required_fields+ FIELDS.select { |f| f[:required] }.map { |f| f[:name] }+ end++ def optional_fields+ FIELDS.reject { |f| f[:required] }.map { |f| f[:name] }+ end+ end+end+```++#### Import Mapping++Maps CSV columns to schema fields:++```ruby+module Spree+ class ImportMapping < Spree.base_class+ belongs_to :import++ # Attributes+ # schema_field - target field name from schema+ # file_column - CSV column header++ def try_to_auto_assign_file_column(csv_headers)+ # Matches by parameterized name comparison+ self.file_column = csv_headers.find do |header|+ header.parameterize.underscore == schema_field.parameterize.underscore+ end+ end+ end+end+```++#### Import Row++Represents a single CSV row:++```ruby+module Spree+ class ImportRow < Spree.base_class+ belongs_to :import, counter_cache: :rows_count+ belongs_to :item, polymorphic: true, optional: true # Created record++ # Attributes+ # row_number - position in CSV+ # data - JSON-serialized row data+ # status - pending/processing/completed/failed+ # validation_errors - error message if failed++ def process!+ start_processing!+ self.item = import.row_processor_class.new(self).process!+ complete!+ rescue StandardError => e+ self.validation_errors = e.message+ fail!+ end++ def to_schema_hash+ # Maps CSV data using import.mappings+ end+ end+end+```++#### Row Processor++Transforms row data into database records:++```ruby+module Spree+ module Imports+ module RowProcessors+ class Base+ def initialize(row)+ @row = row+ @import = row.import+ @attributes = row.to_schema_hash+ end++ attr_reader :row, :import, :attributes++ def process!+ raise NotImplementedError+ end+ end+ end+ end+end+```++### Creating a Custom Importer++**Step 1: Create the Import Class**++```ruby app/models/spree/imports/subscriptions.rb+module Spree+ module Imports+ class Subscriptions < Spree::Import+ def row_processor_class+ Spree::Imports::RowProcessors::Subscription+ end+ end+ end+end+```++**Step 2: Define the Schema**++```ruby app/models/spree/import_schemas/subscriptions.rb+module Spree+ module ImportSchemas+ class Subscriptions < Spree::ImportSchema+ FIELDS = [+ { name: 'email', label: 'Customer Email', required: true },+ { name: 'plan_name', label: 'Plan Name', required: true },+ { name: 'status', label: 'Status', required: true },+ { name: 'start_date', label: 'Start Date' },+ { name: 'billing_interval', label: 'Billing Interval' },+ { name: 'amount', label: 'Amount' },+ { name: 'currency', label: 'Currency' }+ ].freeze+ end+ end+end+```++**Step 3: Create the Row Processor**++```ruby app/services/spree/imports/row_processors/subscription.rb+module Spree+ module Imports+ module RowProcessors+ class Subscription < Base+ def process!+ user = find_or_create_user+ plan = find_plan++ subscription = Spree::Subscription.find_or_initialize_by(+ user: user,+ plan: plan+ )++ subscription.status = attributes['status'] if attributes['status'].present?+ subscription.start_date = parse_date(attributes['start_date']) if attributes['start_date'].present?+ subscription.billing_interval = attributes['billing_interval'] if attributes['billing_interval'].present?++ if attributes['amount'].present?+ currency = attributes['currency'].presence || import.store.default_currency+ subscription.set_price(currency, attributes['amount'])+ end++ subscription.save!+ subscription+ end++ private++ def find_or_create_user+ email = attributes['email'].strip.downcase+ Spree.user_class.find_or_create_by!(email: email)+ end++ def find_plan+ Spree::Plan.find_by!(name: attributes['plan_name'].strip)+ end++ def parse_date(date_string)+ Date.parse(date_string)+ rescue ArgumentError+ nil+ end+ end+ end+ end+end+```++**Step 4: Register the Import Type**++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.import_types << Spree::Imports::Subscriptions+end+```++**Step 5: Add Translations**++```yaml config/locales/en.yml+en:+ spree:+ subscriptions: Subscriptions+```++### Products Import Schema++The built-in products import supports these fields:++**Required Fields:**+- `slug` - Product URL slug+- `sku` - Variant SKU+- `name` - Product name+- `price` - Variant price++**Optional Fields:**+- `status` - Product status (active/draft/archived)+- `description` - Product description+- `meta_title`, `meta_description`, `meta_keywords` - SEO metadata+- `tags` - Product tags+- `compare_at_price` - Original price for sale display+- `currency` - Price currency+- `width`, `height`, `depth`, `dimensions_unit` - Dimensions+- `weight`, `weight_unit` - Weight+- `available_on`, `discontinue_on` - Availability dates+- `track_inventory` - Enable inventory tracking+- `inventory_count`, `inventory_backorderable` - Stock settings+- `tax_category`, `shipping_category` - Category assignments+- `image1_src`, `image2_src`, `image3_src` - Image URLs+- `option1_name`, `option1_value` through `option3_name`, `option3_value` - Variant options+- `category1`, `category2`, `category3` - Taxon assignments (format: "Taxonomy -> Taxon -> Child Taxon")++### Handling Multi-Variant Products++The products import handles variants intelligently:++1. **Master variant rows** (no option values): Create/update the product and its master variant+2. **Non-master variant rows** (with option values): Create additional variants for an existing product++```csv+slug,sku,name,price,option1_name,option1_value,option2_name,option2_value+my-tshirt,TSHIRT-001,My T-Shirt,29.99,,,,+my-tshirt,TSHIRT-S-RED,My T-Shirt,29.99,Size,Small,Color,Red+my-tshirt,TSHIRT-M-RED,My T-Shirt,29.99,Size,Medium,Color,Red+my-tshirt,TSHIRT-L-RED,My T-Shirt,29.99,Size,Large,Color,Red+```++### Metafield Support++Both imports and exports support metafields dynamically:++**Export:** Metafield definitions are automatically added as CSV columns using the format `metafield.{namespace}.{key}`.++**Import:** Map CSV columns to metafield definitions. The system automatically detects columns matching the metafield pattern and updates the corresponding metafield values.++---++## Background Jobs++### CreateRowsJob++Parses CSV and creates ImportRow records:++All import jobs inherit from `Spree::Imports::BaseJob`, which sets `queue_as Spree.queues.imports` once and is shared across the pipeline.++```ruby+module Spree+ module Imports+ class CreateRowsJob < Spree::Imports::BaseJob+ def perform(import_id)+ import = Spree::Import.find(import_id)+ # Stream CSV, batch insert rows+ # Then enqueue ProcessRowsJob via import.process_rows_async+ end+ end+ end+end+```++### ProcessRowsJob++Fans the pending rows out into groups, each processed by a separate `ProcessGroupJob`:++```ruby+module Spree+ module Imports+ class ProcessRowsJob < Spree::Imports::BaseJob+ BATCH_SIZE = 100++ def perform(import_id)+ import = Spree::Import.find(import_id)+ dispatch_groups(import)+ end++ private++ def dispatch_groups(import)+ # When the import defines a group_column (e.g. ProductTranslations groups+ # by slug) and that field is mapped, group rows by the column value.+ # Otherwise, fall back to slicing pending_and_failed rows into batches of+ # BATCH_SIZE. Either way: pluck the row IDs, set processing_groups_count /+ # completed_groups_count up front so workers can't complete prematurely,+ # then enqueue one ProcessGroupJob per group.+ import.rows.pending_and_failed.in_batches(of: BATCH_SIZE) do |batch|+ ProcessGroupJob.perform_later(import.id, batch.ids)+ end+ end+ end+ end+end+```++### ProcessGroupJob++Processes one group of rows and reports completion:++```ruby+module Spree+ module Imports+ class ProcessGroupJob < Spree::Imports::BaseJob+ def perform(import_id, row_ids)+ import = Spree::Import.find(import_id)+ rows = import.rows.where(id: row_ids).pending_and_failed++ # Large imports process with events disabled and use bulk_process!;+ # otherwise each row is processed individually via row.process!.+ rows.each { |row| row.process! }++ check_import_completion(import)+ end++ private++ # Increments completed_groups_count, then completes the import only once the+ # last group has finished and no rows are still in flight.+ def check_import_completion(import)+ # completed_groups_count += 1+ import.complete! if import.completed_groups_count >= import.processing_groups_count &&+ import.rows.in_flight.none?+ end+ end+ end+end+```++### GenerateJob (Exports)++Generates CSV files for exports:++```ruby+module Spree+ module Exports+ class GenerateJob < Spree::BaseJob+ queue_as Spree.queues.exports++ def perform(export_id)+ export = Spree::Export.find_by_prefix_id!(export_id)+ export.generate+ end+ end+ end+end+```++---++## Events++Import and export lifecycle events such as [`import.completed` and `export.created`](/api-reference/webhooks-events) can be delivered as webhooks to react when an asynchronous import or export finishes.++### Import Events++| Event | Trigger |+|-------|---------|+| `import.created` | Import record created |+| `import.completed` | All rows processed |++### Export Events++| Event | Trigger |+|-------|---------|+| `export.created` | Export record created (triggers generation) |++### Import Row Events++| Event | Trigger |+|-------|---------|+| `import_row.completed` | Row processed successfully |+| `import_row.failed` | Row processing failed |++---++## Configuration++### Queue Configuration++```ruby config/initializers/spree.rb+# Configure job queues+Spree.queues.imports = :imports+Spree.queues.exports = :exports+```++### Preferences++Imports support configurable delimiter:++```ruby+import.preferred_delimiter = ';' # Default: ','+```++---++## Key Files Reference++| File | Purpose |+|------|---------|+| `core/app/models/spree/import.rb` | Base import model |+| `core/app/models/spree/export.rb` | Base export model |+| `core/app/models/spree/import_schema.rb` | Base schema class |+| `core/app/models/spree/import_mapping.rb` | Field mapping model |+| `core/app/models/spree/import_row.rb` | Row model with processing |+| `core/app/models/spree/imports/products.rb` | Products import type |+| `core/app/models/spree/import_schemas/products.rb` | Products schema |+| `core/app/services/spree/imports/row_processors/base.rb` | Base processor |+| `core/app/services/spree/imports/row_processors/product_variant.rb` | Products processor |+| `core/app/models/spree/exports/products.rb` | Products export |+| `core/app/models/spree/exports/orders.rb` | Orders export |+| `core/app/models/spree/exports/customers.rb` | Customers export |+| `core/app/jobs/spree/imports/create_rows_job.rb` | Row creation job |+| `core/app/jobs/spree/imports/process_rows_job.rb` | Row processing job |+| `core/app/jobs/spree/exports/generate_job.rb` | Export generation job |+| `admin/app/controllers/spree/admin/imports_controller.rb` | Admin imports controller |+| `admin/app/controllers/spree/admin/exports_controller.rb` | Admin exports controller |++## Permissions++Access is controlled via CanCanCan:++```ruby+# Allow admin to manage imports/exports+can :manage, Spree::Import+can :manage, Spree::Export+```++Records are filtered by `current_ability` ensuring users only export data they have access to.++## Related Documentation++- [Admin imports/exports endpoints](/api-reference/admin-api/endpoints) — REST routes and required scopes to trigger imports and exports programmatically.+- [Admin SDK resources](/developer/sdk/admin/resources) — typed TypeScript client for driving these back-office operations.diff --git a/docs/v6/developer/core-concepts/store-credits-gift-cards.mdx b/docs/v6/developer/core-concepts/store-credits-gift-cards.mdxnew file mode 100644index 0000000000..3eee606c5b--- /dev/null+++ b/docs/v6/developer/core-concepts/store-credits-gift-cards.mdx@@ -0,0 +1,422 @@+---+title: Store Credits & Gift Cards+description: How Spree models store credits and gift cards — stored value balances, redeemable codes, and checkout usage for refunds, loyalty, and gifting.+---++import { Since } from '/snippets/since.mdx';++<Since version="5.1" />++## Overview++Spree provides two stored value mechanisms that customers can use at checkout:++- **Store Credits** - Value assigned directly to a customer's account by admins (refunds, loyalty rewards, compensation)+- **Gift Cards** - Value with a redeemable code that can be shared and redeemed by anyone++| Feature | Store Credit | Gift Card |+|---------|--------------|-----------|+| Purpose | Refunds, loyalty rewards, compensation | Gifting, promotions, marketing |+| Requires account | Yes (tied to customer account) | No (guests can use at checkout) |+| Transferable | No | Yes (code can be shared) |+| Has code | No | Yes |+| Created by | Admin | Admin |+| Assignment | Directly to customer | Applied to order via code |+| Expiration | Configurable by type | Configurable per card |++## Store Credits++Store Credits are monetary values assigned directly to a customer's account. They are commonly used for:++- Refunds (instead of returning money to original payment method)+- Loyalty rewards+- Customer compensation+- Promotional credits++### Store Credit Model++```mermaid+erDiagram+ StoreCredit ||--o{ StoreCreditEvent : "has many"+ StoreCredit ||--o{ Payment : "source for"+ StoreCredit }o--|| User : "belongs to"+ StoreCredit }o--|| Store : "belongs to"+ StoreCredit }o--o| StoreCreditCategory : "belongs to"+ StoreCredit }o--o| StoreCreditType : "belongs to"++ StoreCredit {+ decimal amount+ decimal amount_used+ decimal amount_authorized+ string currency+ string memo+ }++ StoreCreditCategory {+ string name+ }++ StoreCreditType {+ string name+ integer priority+ }++ StoreCreditEvent {+ string action+ decimal amount+ string authorization_code+ }+```++### Store Credit Attributes++| Attribute | Description | Example |+|-----------|-------------|---------|+| `amount` | Total credit amount | `100.00` |+| `amount_used` | Amount already spent | `25.00` |+| `amount_authorized` | Amount currently authorized for pending orders | `0.00` |+| `currency` | Currency code | `USD` |+| `memo` | Optional note about the credit | `Refund for order #R123` |++### Store Credit Categories++Categories help organize store credits by their purpose:++| Category | Description |+|----------|-------------|+| Default | General purpose store credit (also the default reimbursement category) |+| Expiring | Store credit that may expire |+| Non-expiring | Store credit that does not expire |++<Info>+"Gift Card" is not a seeded category but a special name recognized by the model: any category named "Gift Card" (or one listed in `Spree::Config[:non_expiring_credit_types]`) is treated as non-expiring via `StoreCreditCategory#non_expiring?`.+</Info>++### Store Credit Types++Types define the priority in which store credits are applied at checkout:++| Type | Description |+|------|-------------|+| Expiring | Credits that may expire (applied first) |+| Non-expiring | Credits that don't expire (applied last) |++### Store Credit Events++Every action on a store credit is recorded as an event for audit purposes:++| Action | Description |+|--------|-------------|+| `allocation` | Initial credit was assigned |+| `authorize` | Credit was authorized for an order |+| `capture` | Authorized credit was captured |+| `void` | Authorization was voided |+| `credit` | Credit was returned (e.g., order canceled) |++### Assigning Store Credits++Store credits are managed in the Admin Panel:++1. Navigate to **Customers** in the Admin Panel+2. Select a customer+3. Go to the **Store Credits** tab+4. Click **Add Store Credit**+5. Enter the amount, category, and optional memo+6. Click **Create**++Store credits can also be created via the [Admin API](/api-reference/admin-api/introduction), as a nested resource under the customer:++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++const credit = await client.customers.storeCredits.create('cus_xxx', {+ amount: '25.00',+ currency: 'USD',+ category_id: 'sccat_xxx',+ memo: 'Goodwill credit for delayed shipment',+})+```++```bash CLI+spree api post /customers/cus_xxx/store_credits -d '{+ "amount": "25.00",+ "currency": "USD",+ "category_id": "sccat_xxx",+ "memo": "Goodwill credit"+}'+```++</CodeGroup>++### Store Credit Events++The store credit system publishes lifecycle events:++| Event | Description |+|-------|-------------|+| `store_credit.created` | Store credit was created |+| `store_credit.updated` | Store credit was updated |++## Gift Cards++Gift Cards are stored value codes created by admins that can be shared and redeemed by customers. When redeemed, they create a Store Credit on the customer's account.++### Gift Card Model++```mermaid+erDiagram+ GiftCard }o--|| Store : "belongs to"+ GiftCard }o--o| User : "belongs to"+ GiftCard }o--o| GiftCardBatch : "belongs to"+ GiftCard ||--o{ StoreCredit : "originator for"++ GiftCard {+ string code+ string status+ decimal amount+ decimal amount_used+ decimal amount_authorized+ string currency+ date expires_at+ datetime redeemed_at+ }++ GiftCardBatch {+ string prefix+ integer codes_count+ decimal amount+ string currency+ date expires_at+ }+```++### Gift Card Attributes++| Attribute | Description | Example |+|-----------|-------------|---------|+| `code` | Unique redemption code | `abc1234def` |+| `amount` | Total gift card value | `50.00` |+| `amount_used` | Amount already redeemed | `0.00` |+| `status` | Current status | `active` |+| `currency` | Currency code | `USD` |+| `expires_at` | Optional expiration date | `2025-12-31` |++### Gift Card Statuses++| Status | Description | How it gets there |+|-------|-------------|-------------------|+| `active` | Available for redemption | The status a card is created with |+| `partially_redeemed` | Some value has been redeemed | `Spree::GiftCards::Redeem`, when a balance remains |+| `redeemed` | Fully redeemed | `Spree::GiftCards::Redeem`, when nothing is left |+| `canceled` | Voided, and no longer spendable | `Spree::GiftCards::Cancel` |++Redemption does not need the caller to choose: `Spree::GiftCards::Redeem`+looks at what is left on the card and marks it partially or fully redeemed+accordingly. A card can be partially redeemed more than once, and each spend+publishes its own event.++Cancelling is refused once a card has been spent against, so cancellation can+never take back value a customer has already used.++<Note>+Gift cards can also be `expired` if `expires_at` date has passed and the card hasn't been fully redeemed.+</Note>++### Gift Card Lifecycle++```mermaid+flowchart TB+ A[Admin creates Gift Card] --> B[Code generated]+ B --> C[Admin shares code with recipient]+ C --> D[Recipient enters code at checkout]+ D --> E[Store Credit created for customer]+ E --> F[Gift Card marked as redeemed]+ F --> G[Customer uses Store Credit]+```++### Creating Gift Cards++#### Single Gift Card++1. Navigate to **Gift Cards** in the Admin Panel+2. Click **Create Gift Card**+3. Enter the amount and optional expiration date+4. Click **Create**+5. Share the generated code with the recipient++Gift cards can also be created via the [Admin API](/api-reference/admin-api/introduction). The code is generated automatically if you don't supply one:++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++const giftCard = await client.giftCards.create({+ amount: '50.00',+ currency: 'USD',+ expires_at: '2026-12-31',+})++console.log(giftCard.code) // share this with the recipient+```++```bash CLI+spree api post /gift_cards -d '{+ "amount": "50.00",+ "currency": "USD",+ "expires_at": "2026-12-31"+}'+```++</CodeGroup>++#### Batch Gift Card Generation++For promotions or bulk distribution, you can create multiple gift cards at once using Gift Card Batches:++1. Navigate to **Gift Cards** in the Admin Panel+2. Click **Create Batch**+3. Enter:+ - **Prefix** - Code prefix for easy identification (e.g., `HOLIDAY`)+ - **Count** - Number of cards to generate+ - **Amount** - Value per card+ - **Expiration** - Optional expiration date+4. Click **Create**++Batches can also be created via the Admin API:++<CodeGroup>++```typescript Admin SDK+const batch = await client.giftCardBatches.create({+ prefix: 'HOLIDAY',+ codes_count: 1000,+ amount: '25.00',+ currency: 'USD',+ expires_at: '2026-12-31',+})+```++```bash CLI+spree api post /gift_card_batches -d '{+ "prefix": "HOLIDAY",+ "codes_count": 1000,+ "amount": "25.00",+ "currency": "USD",+ "expires_at": "2026-12-31"+}'+```++</CodeGroup>++<Info>+Large batches are processed in the background to avoid timeout issues.+</Info>++### Redeeming Gift Cards++Gift cards can be redeemed by both **registered customers** and **guest visitors** at checkout. This is a key difference from Store Credits, which require a customer account.++<Info>+Unlike Store Credits which are tied to a customer account, Gift Cards can be applied directly to an order during checkout - no account required. This makes them ideal for gifting to anyone.+</Info>++When a gift card is applied to an order:+- The gift card value is used to pay for the order+- The gift card is marked as redeemed (or partially redeemed)+- No Store Credit is created for guest checkouts++Gift cards are applied via a dedicated `POST /api/v3/store/carts/:cart_id/gift_cards` endpoint (separate from the `discount_codes` endpoint used for promotion codes); the discount-codes endpoint does not handle gift cards. See the [cart & checkout SDK guide](/developer/sdk/store/cart-checkout) for the full cart flow these calls belong to.++<CodeGroup>++```typescript Store SDK+// Apply gift card code to cart (works for guests and registered customers)+// Gift cards use a dedicated endpoint — they reduce amount_due, not total+const cart = await client.carts.giftCards.apply('cart_abc123', 'abc1234def', {+ spreeToken: '<token>',+})++// Remove gift card (ID from cart.gift_card.id)+await client.carts.giftCards.remove('cart_abc123', cart.gift_card.id, {+ spreeToken: '<token>',+})+```++```bash cURL+# Apply gift card to cart (works for guests and registered customers)+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_abc123/gift_cards' \+ -H 'X-Spree-Api-Key: pk_xxx' \+ -H 'X-Spree-Token: <token>' \+ -H 'Content-Type: application/json' \+ -d '{ "code": "abc1234def" }'+```++</CodeGroup>++### Gift Card Events++The gift card system publishes lifecycle events:++| Event | Description |+|-------|-------------|+| `gift_card.created` | Gift card was created |+| `gift_card.redeemed` | Gift card was fully redeemed |+| `gift_card.partially_redeemed` | Gift card was partially redeemed |++## Using at Checkout++Store Credits and Gift Cards work differently at checkout:++- **Store Credits** - Require a customer account; applied from the customer's balance+- **Gift Cards** - Can be used by anyone (guests included); applied directly to the order via code++### Checkout Flow++```mermaid+flowchart TB+ A[Customer proceeds to payment] --> B{Guest or Registered?}+ B -->|Registered| C{Has Store Credit?}+ B -->|Guest| D{Has Gift Card code?}+ C -->|Yes| E[Display available balance]+ C -->|No| D+ D -->|Yes| F[Apply Gift Card to order]+ D -->|No| G[Show payment methods]+ E --> H{Apply Store Credit?}+ H -->|Yes| I[Authorize store credit]+ H -->|No| D+ F --> J{Covers order total?}+ I --> J+ J -->|Yes| K[Complete order]+ J -->|No| G+ G --> L[Customer pays remaining balance]+ L --> K+```++### Store Credit Priority++When a registered customer has multiple store credits, they are applied in order of priority:++1. **Expiring credits** - Applied first to ensure they're used before expiration+2. **Non-expiring credits** - Applied after expiring credits++## Related Documentation++- [Payments](/developer/core-concepts/payments) — Payment processing and methods+- [Orders](/v6/developer/core-concepts/orders) — Order management+- [Customers](/developer/core-concepts/customers) — Customer management+- [Events](/developer/core-concepts/events) — Event system and subscribers+- [Admin SDK Quickstart](/developer/sdk/admin/quickstart) — Set up and authenticate the Admin SDK+- [Monetary Amounts](/api-reference/store-api/monetary-amounts) — How the API represents `amount`, `amount_used`, and other money fields