> For the complete documentation index, see [llms.txt](https://docs.liquidcommerce.cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.liquidcommerce.cloud/use-cases/presales.md). Agents can also search and read this documentation through its [MCP server](https://docs.liquidcommerce.cloud/~gitbook/mcp).

# Presales

## Presale Feature Guide

### Overview

The LiquidCommerce SDK provides comprehensive support for presale products, allowing merchants to offer products for purchase before general availability. This guide covers how to integrate presale functionality into your application.

### What are Presales?

Presales enable customers to reserve and purchase products before they become widely available. Key features include:

* **Advanced Purchase**: Customers can buy products before stock arrival
* **Limited Quantities**: Presale products often have purchase limits
* **Scheduled Availability**: Products have defined presale windows
* **Exclusive Access**: First-come, first-served inventory reservation

### Working with Presale Products

#### Identifying Presale Products

Use the catalog search to find presale products:

```typescript
const presaleProducts = await liquidCommerce.catalog.search({
  filters: [{
    key: ENUM_FILTER_KEYS.PRESALE,
    values: ENUM_BINARY_FILTER.YES
  }],
  loc: {
    address: {
      one: '123 Main St',
      city: 'New York',
      state: 'NY',
      zip: '10001'
    }
  }
});

// Extract presale information from products
presaleProducts.products.forEach(product => {
  product.sizes.forEach(size => {
    const presale = size.attributes?.presale;
    if (presale?.isActive) {
      console.log({
        product: product.name,
        availableFrom: presale.canPurchaseOn,
        estimatedShipping: presale.estimatedShipBy,
        status: 'Active Presale'
      });
    }
  });
});
```

#### Cart Response Structure

When working with presale items, the cart response includes additional fields:

```typescript
interface ICart {
  id: string;
  // ... standard cart fields
  
  // Presale-specific fields
  isPresaleLocked: boolean;        // Indicates cart contains presale items
  presaleExpiresAt: string | null; // Reservation expiration time
  
  events: ICartEvent[];            // Contains presale-related events
}
```

### Adding Presale Items to Cart

#### Basic Implementation

```typescript
const cartResponse = await liquidCommerce.cart.update({
  id: cartId, // Use existing cart ID or create new
  items: [{
    partNumber: 'WHISKEY_PRESALE_2024_retailer_abc',
    quantity: 1,
    fulfillmentId: 'shipping_fulfillment_123'
  }],
  loc: {
    address: {
      one: '456 Oak Avenue',
      city: 'Los Angeles',
      state: 'CA',
      zip: '90001'
    }
  }
});

// Check if presale was successfully added
if (cartResponse.isPresaleLocked) {
  console.log('Presale item reserved successfully');
  console.log(`Complete checkout by: ${cartResponse.presaleExpiresAt}`);
}
```

#### Handling Presale Events

The SDK provides specific event types for presale scenarios:

```typescript
// Available presale events
enum CART_EVENT_ENUM {
  PRESALE_ITEMS_NOT_ALLOWED = 'PresaleItemsNotAllowed',
  PRESALE_LIMIT_EXCEEDED = 'PresaleLimitExceeded',
  PRESALE_NOT_STARTED = 'PresaleNotStarted',
  PRESALE_EXPIRED = 'PresaleExpired',
  PRESALE_MIXED_CART = 'PresaleMixedCart',
}
```

Example event handling:

```typescript
function handlePresaleEvents(cart: ICart) {
  cart.events.forEach(event => {
    switch(event.type) {
      case CART_EVENT_ENUM.PRESALE_NOT_STARTED:
        // Presale hasn't begun yet
        alert('This presale has not started. Please check back later.');
        break;
        
      case CART_EVENT_ENUM.PRESALE_LIMIT_EXCEEDED:
        // Requested quantity exceeds available inventory
        alert('Sorry, not enough inventory available. Please try a smaller quantity.');
        break;
        
      case CART_EVENT_ENUM.PRESALE_EXPIRED:
        // Presale period has ended
        alert('This presale has ended.');
        break;
        
      case CART_EVENT_ENUM.PRESALE_MIXED_CART:
        // Cannot mix presale with other items
        alert('Presale items must be purchased separately.');
        break;
    }
  });
}
```

### Checkout Process

#### Preparing Checkout

Complete the checkout process promptly when `isPresaleLocked` is true:

```typescript
async function checkoutPresaleCart(cartId: string) {
  // Step 1: Prepare checkout
  const checkoutPrep = await liquidCommerce.checkout.prepare({
    cartId: cartId,
    customer: {
      firstName: "Sarah",
      lastName: "Johnson",
      email: "sarah.johnson@email.com",
      phone: "3105551234",
      birthDate: "1985-06-15"
    },
    billingAddress: {
      firstName: "Sarah",
      lastName: "Johnson",
      email: "sarah.johnson@email.com",
      phone: "3105551234",
      one: "789 Pine Street",
      two: "Suite 100",
      city: "San Francisco",
      state: "CA",
      zip: "94102"
    },
    hasSubstitutionPolicy: true,
    marketingPreferences: {
      canEmail: true,
      canSms: false
    }
  });

  // Step 2: Process payment
  // Assuming payment element is already mounted
  const paymentToken = await liquidCommerce.payment.generateToken();
  
  if ('id' in paymentToken) {
    // Step 3: Complete checkout
    const order = await liquidCommerce.checkout.complete({
      token: checkoutPrep.token,
      payment: paymentToken.id
    });
    
    return order;
  }
}
```

#### Time-Sensitive Checkout

Monitor the reservation time when dealing with presales:

```typescript
class PresaleCheckoutManager {
  private expirationTimer?: NodeJS.Timeout;
  
  startCheckout(cart: ICart) {
    if (!cart.isPresaleLocked || !cart.presaleExpiresAt) {
      return;
    }
    
    const expiresAt = new Date(cart.presaleExpiresAt);
    const now = new Date();
    const timeRemaining = expiresAt.getTime() - now.getTime();
    
    // Show countdown to user
    this.displayCountdown(timeRemaining);
    
    // Warn before expiration
    if (timeRemaining > 60000) { // More than 1 minute
      this.expirationTimer = setTimeout(() => {
        this.warnUserAboutExpiration();
      }, timeRemaining - 60000);
    }
  }
  
  private displayCountdown(milliseconds: number) {
    const minutes = Math.floor(milliseconds / 60000);
    const seconds = Math.floor((milliseconds % 60000) / 1000);
    console.log(`Time remaining: ${minutes}:${seconds.toString().padStart(2, '0')}`);
  }
  
  private warnUserAboutExpiration() {
    alert('Your presale reservation expires in 1 minute!');
  }
  
  cleanup() {
    if (this.expirationTimer) {
      clearTimeout(this.expirationTimer);
    }
  }
}
```

### Best Practices

#### 1. Clear User Communication

```typescript
// Display presale information prominently
function displayPresaleInfo(product: IProduct) {
  const presaleInfo = product.sizes[0]?.attributes?.presale;
  
  if (presaleInfo?.isActive) {
    return {
      status: 'PRESALE',
      availableDate: presaleInfo.canPurchaseOn,
      shippingDate: presaleInfo.estimatedShipBy,
      message: `Pre-order now, ships ${formatDate(presaleInfo.estimatedShipBy)}`
    };
  }
}
```

#### 2. Cart Separation

```typescript
// Check before adding items to existing cart
async function addToCart(item: ICartUpdateItem, existingCartId?: string) {
  if (existingCartId) {
    // Check if existing cart has presale items
    const existingCart = await liquidCommerce.cart.get(existingCartId);
    
    if (existingCart.isPresaleLocked) {
      // Create new cart for non-presale items
      console.log('Creating new cart - existing cart contains presale items');
      return await liquidCommerce.cart.update({
        id: 'new',
        items: [item],
        loc: existingCart.loc
      });
    }
  }
  
  // Safe to use existing cart
  return await liquidCommerce.cart.update({
    id: existingCartId || 'new',
    items: [item],
    loc: { /* location */ }
  });
}
```

#### 3. Error Recovery

```typescript
async function robustPresalePurchase(
  partNumber: string,
  quantity: number,
  maxRetries: number = 3
) {
  let attempts = 0;
  
  while (attempts < maxRetries) {
    try {
      const cart = await liquidCommerce.cart.update({
        id: 'new',
        items: [{ partNumber, quantity, fulfillmentId: 'shipping_123' }],
        loc: { /* location */ }
      });
      
      // Check for presale events
      const hasPresaleError = cart.events.some(e => 
        e.type === CART_EVENT_ENUM.PRESALE_LIMIT_EXCEEDED ||
        e.type === CART_EVENT_ENUM.PRESALE_EXPIRED
      );
      
      if (hasPresaleError) {
        throw new Error('Presale not available');
      }
      
      if (cart.isPresaleLocked) {
        return { success: true, cart };
      }
      
    } catch (error) {
      attempts++;
      if (attempts >= maxRetries) {
        return { success: false, error: error.message };
      }
      // Wait before retry
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }
}
```

### Common Integration Patterns

#### Pattern 1: Presale Product Page

```typescript
class PresaleProductPage {
  async displayProduct(productId: string) {
    // Fetch product details
    const availability = await liquidCommerce.catalog.availability({
      ids: [productId],
      loc: this.getUserLocation()
    });
    
    const product = availability.products[0];
    const presaleSize = product.sizes.find(s => 
      s.attributes?.presale?.isActive
    );
    
    if (presaleSize) {
      this.showPresaleBadge();
      this.showEstimatedShipping(presaleSize.attributes.presale.estimatedShipBy);
      this.enablePresalePurchase(presaleSize);
    }
  }
  
  private async enablePresalePurchase(size: IProductSize) {
    // Set up purchase button
    const purchaseButton = document.getElementById('purchase-btn');
    purchaseButton.onclick = async () => {
      const cart = await liquidCommerce.cart.update({
        id: 'new',
        items: [{
          partNumber: size.variants[0].partNumber,
          quantity: 1,
          fulfillmentId: size.variants[0].fulfillments[0]
        }],
        loc: this.getUserLocation()
      });
      
      if (cart.isPresaleLocked) {
        // Redirect to checkout
        window.location.href = `/checkout?cartId=${cart.id}`;
      }
    };
  }
}
```

#### Pattern 2: Presale Collection Page

```typescript
async function createPresaleCollection() {
  // Fetch all active presales
  const presales = await liquidCommerce.catalog.search({
    filters: [{
      key: ENUM_FILTER_KEYS.PRESALE,
      values: ENUM_BINARY_FILTER.YES
    }],
    orderBy: ENUM_ORDER_BY.PRICE,
    orderDirection: ENUM_NAVIGATION_ORDER_DIRECTION_TYPE.ASC,
    page: 1,
    perPage: 20,
    loc: { /* user location */ }
  });
  
  // Group by availability date
  const groupedPresales = presales.products.reduce((acc, product) => {
    product.sizes.forEach(size => {
      const presale = size.attributes?.presale;
      if (presale?.isActive && presale.canPurchaseOn) {
        const date = new Date(presale.canPurchaseOn).toDateString();
        if (!acc[date]) acc[date] = [];
        acc[date].push({ product, size });
      }
    });
    return acc;
  }, {});
  
  return groupedPresales;
}
```

### Presale and Regular Items in One Cart

A presale can share the cart with regular items. The shopper adds one presale and any regular items to the same cart and pays for all of them in one checkout.

{% hint style="info" %}
On integrations where presale items still need a cart of their own, adding a presale to a cart with other items drops those items with `PresaleMixedCart`, as described above.
{% endhint %}

#### Choosing the Flow: `checkoutFlow`

Each presale tells your storefront how to sell it, in `size.attributes.presale.checkoutFlow`:

| Value                  | What the storefront does                                                                                                          |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `checkout`, or not set | Sends the shopper straight to checkout with the presale on a cart of its own, as in [Pattern 1](#pattern-1-presale-product-page). |
| `cart`                 | Adds the presale to the shopper's current cart, next to their other items.                                                        |

The flow follows how fast the presale is expected to sell:

* **`checkout`** suits a presale that can sell out fast, such as a limited release. The shopper goes straight to checkout and can buy the bottle while their hold on it lasts, without stopping in the cart.
* **`cart`** suits a presale that stays open longer. The shopper can keep browsing and buy the presale together with their other items in one order.

`checkoutFlow` is set per presale and only guides the storefront: the cart accepts a presale either way. Where presale items need a cart of their own, it is always `checkout`.

```typescript
function goesToCart(size: IProductSize): boolean {
  const presale = size.attributes?.presale;
  return presale?.isActive === true && presale.checkoutFlow === 'cart';
}

async function preOrder(size: IProductSize, cartId: string, loc: ILoc) {
  const item = {
    partNumber: size.variants[0].partNumber,
    quantity: 1,
    fulfillmentId: size.variants[0].fulfillments[0]
  };

  if (goesToCart(size)) {
    // Add the presale to the shopper's cart; their other items stay
    return await liquidCommerce.cart.update({ id: cartId, items: [item], loc });
  }

  // Straight to checkout with the presale alone
  const cart = await liquidCommerce.cart.update({ id: 'new', items: [item], loc });
  window.location.href = `/checkout?cartId=${cart.id}`;
}
```

#### Finding the Presale Line

A cart line that belongs to a presale has `customerPlacement` set to `pre_sale`:

```typescript
const presaleLine = cart.items.find(item => item.customerPlacement === 'pre_sale');
```

#### Checking an Add

The cart response can carry events about lines other than the one just added, such as a presale hold that ended. To find out whether the add went through, look only at events that name the added line, or that name no line:

```typescript
const PRESALE_REFUSALS = [
  CART_EVENT_ENUM.PRESALE_EXPIRED,
  CART_EVENT_ENUM.PRESALE_LIMIT_EXCEEDED,
  CART_EVENT_ENUM.PRESALE_NOT_STARTED,
  CART_EVENT_ENUM.PRESALE_ALREADY_IN_CART,
  CART_EVENT_ENUM.PRESALE_NOT_FOUND
];

function presaleRefusal(cart: ICart, added: { partNumber: string; fulfillmentId: string }) {
  return cart.events.find(event =>
    PRESALE_REFUSALS.includes(event.type) &&
    (!event.items?.length || event.items.some(item =>
      item.partNumber === added.partNumber && item.fulfillmentId === added.fulfillmentId
    ))
  );
}
```

#### One Presale per Cart

A cart holds the items of one presale. When the shopper adds items of a second presale, the cart keeps the presale it already has, does not add the new items, and returns `PresaleAlreadyInCart`. To switch presales, remove the first presale's line (quantity `0`) before adding the second.

#### The Presale Hold in a Mixed Cart

* The hold starts when the presale line is added: `isPresaleLocked` is `true` and `presaleExpiresAt` is when the hold ends.
* The hold has a fixed length, set per presale (5 minutes by default). Editing the cart, including the presale's quantity, does not extend it.
* If the shopper raises the presale quantity beyond what is left, the line keeps the quantity already held and the cart returns `PresaleLimitExceeded`.
* When the hold ends, the next cart request removes the presale line with `PresaleExpired`. The regular items stay in the cart, `isPresaleLocked` becomes `false` and `presaleExpiresAt` becomes `null`. Adding the presale again starts a new hold, if stock is left.

Fetch the cart again when `presaleExpiresAt` passes, so the shopper sees that the presale was removed and the rest of their cart is still there. A device clock can run ahead of the server; if the cart is still held, try again a few seconds later.

```typescript
function watchPresaleHold(cart: ICart, onHoldEnded: (cart: ICart) => void) {
  if (!cart.isPresaleLocked || !cart.presaleExpiresAt) {
    return;
  }

  const check = async () => {
    const latest = await liquidCommerce.cart.get(cart.id);

    if (latest.isPresaleLocked) {
      // Device clock ahead of the server: try once more
      setTimeout(async () => {
        const retried = await liquidCommerce.cart.get(cart.id);
        if (retried.events.some(e => e.type === CART_EVENT_ENUM.PRESALE_EXPIRED)) {
          onHoldEnded(retried);
        }
      }, 10000);
      return;
    }

    if (latest.events.some(e => e.type === CART_EVENT_ENUM.PRESALE_EXPIRED)) {
      // e.g. "Your pre-order reservation has ended. The rest of your cart is still here."
      onHoldEnded(latest);
    }
  };

  const wait = new Date(cart.presaleExpiresAt).getTime() - Date.now();
  return setTimeout(check, Math.max(0, wait));
}
```

#### Checkout with a Mixed Cart

* Checkout prepare copies the cart's hold: the checkout's `isPresaleLocked` and `presaleExpiresAt` match the cart's, and preparing again does not extend them.
* Checkout prepare does not fail when the presale line changed. It returns the presale events (`PresaleExpired`, `PresaleLimitExceeded`, `PresaleNotFound`, `PresaleAlreadyInCart`, `PresaleExcludedFromDiscount`) so you can show the shopper what changed.
* Checkout complete fails when the presale line was removed or reduced after the checkout was prepared, so an order never goes through without the shopper knowing. Prepare the checkout again to show the updated cart, then complete it.

| Code | Meaning                                                                        |
| ---- | ------------------------------------------------------------------------------ |
| 5519 | The hold ended and the presale line was removed.                               |
| 5520 | The presale quantity requested is no longer available.                         |
| 5521 | The other items were removed because this cart cannot mix them with a presale. |
| 5522 | The presale is no longer offered and its line was removed.                     |

#### Promo Codes and Presale Items

A promo code can be set to exclude presale items:

* On a cart with presale and regular items, the code discounts the regular items only, and the cart returns `PresaleExcludedFromDiscount` naming the presale line. This is a notice, not an error: the code is applied.
* On a cart with only presale items, the code is not applied.

Promo codes without this setting discount presale items too.

#### New Presale Events

```typescript
enum CART_EVENT_ENUM {
  // ...
  PRESALE_ALREADY_IN_CART = 'PresaleAlreadyInCart',             // Items of a second presale were not added
  PRESALE_NOT_FOUND = 'PresaleNotFound',                        // The presale is no longer offered
  PRESALE_EXCLUDED_FROM_DISCOUNT = 'PresaleExcludedFromDiscount' // The promo code skipped the presale line
}
```

### Limitations and Considerations

#### System Limitations

* **Cart Exclusivity**: Presale items require dedicated carts
* **Time Constraints**: Reservations have expiration times
* **Quantity Restrictions**: Limited inventory per customer
* **Geographic Availability**: Some presales may be region-specific

#### User Experience Considerations

1. **Transparency**: Always show presale status and estimated shipping
2. **Urgency**: Display reservation timers when applicable
3. **Clarity**: Explain why presale items need separate orders
4. **Feedback**: Provide clear error messages for presale-specific issues

### Summary

The presale feature in LiquidCommerce SDK enables:

* Early access to limited products
* Automated inventory management
* Time-based reservations
* Clear event-driven feedback

Successful presale integration requires careful attention to:

* Event handling for various presale states
* Time-sensitive checkout flows
* Clear user communication
* Proper cart segregation

By following this guide and the provided examples, you can create a smooth presale experience that maximizes conversion while maintaining inventory integrity.
