npm package: @lantern-ai/ecommerce-core-utility
Description: TypeScript utility for ecommerce cart management and order processing with pluggable persistence, built-in validation, and type safety.
Latest version: 0.1.0

# @lantern/ecommerce-core-utility

TypeScript utility for ecommerce cart management and order processing with pluggable persistence, built-in validation, and type safety.

## Installation

```bash
npm install @lantern/ecommerce-core-utility
```

**Peer Dependencies:** `react` (for client hooks), `zod`

## Features

- Type-safe with full TypeScript support
- Built-in Zod validation
- Client & server utilities
- Pluggable persistence adapters
- ESM-first with React 18/19 support
- Comprehensive error handling
- Increment/decrement quantity support

## Usage

### Server-Side

```typescript
import { createCartService, createOrderService } from '@lantern/ecommerce-core-utility';

const cartService = createCartService();
const orderService = createOrderService();

// Add item to cart
await cartService.addToCart({ 
  cartId: 'cart_123',
  item: { id: 'sku_1', name: 'T-shirt', priceCents: 2500, quantity: 1 }
});

// Apply coupon
await cartService.applyCoupon({ 
  cartId: 'cart_123', 
  couponCode: 'SAVE10', 
  discountCents: 1000 
});

// Create order from cart
const cart = (await cartService.getCart('cart_123')).data;
const order = await orderService.createOrder({ cart });
```

### Client-Side

```typescript
import { useCart } from '@lantern/ecommerce-core-utility';

function MyComponent() {
  const { cart, cartId, addItem, updateItem, clear } = useCart();
  
  const handleAdd = () => {
    addItem({ id: 'sku_1', name: 'T-shirt', priceCents: 2500, quantity: 1 });
  };
  
  return <button onClick={handleAdd}>Add to Cart</button>;
}
```

## API Overview

### Cart Service

**`createCartService(options)`** returns an object with:

- **`addToCart(params)`** - Add item to cart (creates cart if needed)
- **`updateItem(params)`** - Update item quantity
- **`removeItem(params)`** - Remove item from cart
- **`incrementItem(params)`** - Increase item quantity by 1
- **`decrementItem(params)`** - Decrease item quantity by 1 (removes if becomes 0)
- **`getCart(cartId)`** - Retrieve cart by ID
- **`clearCart(cartId)`** - Delete cart
- **`getCartSummary(cartId)`** - Get subtotal, discount, total, item count
- **`applyCoupon(params)`** - Apply discount code
- **`removeCoupon(cartId)`** - Remove discount
- **`mergeCarts(params)`** - Merge guest and user carts

### Order Service

**`createOrderService(options)`** returns an object with:

- **`createOrder(params)`** - Create order from cart with total calculation
- **`getOrder(orderId)`** - Retrieve order by ID
- **`markPaid(orderId)`** - Update order status after payment

### Client Utilities

- **`useCart()`** - React hook for local cart state (localStorage)
- **`initEcommerce()`** - Client initialization

### Types

All functions return `Result<T>` type:

```typescript
type Result<T> = 
  | { success: true; data: T }
  | { success: false; error: { message: string; code: string } }
```

**Common Error Codes:**

- `validation` - Invalid input parameters
- `not_found` - Cart or order not found
- `item_not_found` - Item not found in cart

## Key Features

- **Validation**: Built-in Zod schemas validate all parameters
- **Adapter Pattern**: Plug in any database (Postgres, MongoDB, Redis)
- **Quantity Management**: Atomic increment/decrement operations
- **Cart Merging**: Seamlessly combine guest and authenticated user carts
- **Currency Support**: Configurable default currency

## Custom Persistence

```typescript
import { CartPersistenceAdapter } from '@lantern/ecommerce-core-utility';

const dbAdapter: CartPersistenceAdapter = {
  async getCart(id) { return await db.carts.findUnique({ where: { id } }); },
  async saveCart(cart) { await db.carts.upsert({ where: { id: cart.id }, update: cart, create: cart }); },
  async deleteCart(id) { await db.carts.delete({ where: { id } }); }
};

const cartService = createCartService({ adapter: dbAdapter });
```

## Development

```bash
npm install        # Install dependencies
npm run build      # Build the package
npm test           # Run tests
npm run lint       # Lint code
```