npm package: @hg-storefront/gift
Description: A collection of React hooks and plugin configuration for managing gift functionality in the Hemglass storefront.
Latest version: 0.0.30

# @hg-storefront/gift

A collection of React hooks and plugin configuration for managing gift functionality in the Hemglass storefront.

## Installation

This library is part of the Hemglass storefront monorepo and is automatically available when working within the project.

## Plugin Configuration

To use the gift functionality, you need to add the `GiftPlugin` to your `pluginConfigs` in your provider configuration:

```tsx
import { GiftPlugin } from '@hg-storefront/gift'

// In your provider-config.ts
export const providerConfig: VendureDataProviderProps = {
  // ... other config
  options: {
    // ... other options
    pluginConfigs: [
      GiftPlugin,
      // ... other plugins
    ],
  },
}
```

## Hooks

### `useAvailableGifts`

Hook for fetching available gifts for the current order.

```tsx
import { useAvailableGifts } from '@hg-storefront/gift'

function AvailableGiftsList() {
  const { data: gifts, isLoading, error } = useAvailableGifts()

  if (isLoading) return <div>Loading gifts...</div>
  if (error) return <div>Error loading gifts</div>

  return (
    <div>
      {gifts?.gifts?.map((gift) => (
        <div key={gift.id}>
          <h4>{gift.name}</h4>
          {gift.description && <p>{gift.description}</p>}
          <p>Order value per gift: {gift.orderValuePerGift}</p>
          <p>Max quantity: {gift.maxQuantity}</p>
          <p>Eligible: {gift.isEligible ? 'Yes' : 'No'}</p>
          {!gift.isEligible && <p>Amount until eligible: {gift.amountUntilEligible}</p>}
          <p>Quantity in order: {gift.quantityInOrder}</p>
        </div>
      ))}
    </div>
  )
}
```

#### Returns

- `data`: `AvailableGiftSummary` object containing gifts array and summary data
- `isLoading`: Boolean indicating if the query is loading
- `error`: Error object if the query failed

### `useAddGiftToOrder`

Hook for adding a gift to the current order.

```tsx
import { useAddGiftToOrder } from '@hg-storefront/gift'

function AddGiftButton({ giftId }: { giftId: string }) {
  const { addGift, error, isLoading } = useAddGiftToOrder()

  const handleAddGift = async () => {
    try {
      await addGift(giftId)
      console.log('Gift added successfully')
    } catch (error) {
      console.error('Failed to add gift:', error)
    }
  }

  return (
    <button onClick={handleAddGift} disabled={isLoading}>
      {isLoading ? 'Adding...' : 'Add Gift'}
    </button>
  )
}
```

#### Returns

- `addGift`: Function to add a gift to the order
- `error`: Error object if the operation failed
- `isLoading`: Boolean indicating if the operation is in progress

### `useAdjustGiftOnOrder`

Hook for adjusting the quantity of a gift in the current order.

```tsx
import { useAdjustGiftOnOrder } from '@hg-storefront/gift'

function GiftQuantityAdjuster({ orderLineId }: { orderLineId: string }) {
  const { adjustOrderLine, error, isLoading } = useAdjustGiftOnOrder()

  const handleQuantityChange = async (newQuantity: number) => {
    try {
      await adjustOrderLine(orderLineId, newQuantity)
      console.log('Gift quantity updated successfully')
    } catch (error) {
      console.error('Failed to update gift quantity:', error)
    }
  }

  return (
    <div>
      <button onClick={() => handleQuantityChange(1)} disabled={isLoading}>
        Set to 1
      </button>
      <button onClick={() => handleQuantityChange(2)} disabled={isLoading}>
        Set to 2
      </button>
      {error && <div>Error: {error.message}</div>}
    </div>
  )
}
```

#### Returns

- `adjustOrderLine`: Function to adjust gift quantity in the order
- `error`: Error object if the operation failed
- `isLoading`: Boolean indicating if the operation is in progress

## Types

### `AvailableGift`

```tsx
interface AvailableGift {
  id: string
  name: string
  description: string | null
  orderValuePerGift: number
  maxQuantity: number
  enabled: boolean
  productVariant: ProductVariant | null
  channels: Array<{ id: string; code: string }>
  createdAt: string
  updatedAt: string
  isEligible: boolean
  amountUntilEligible: number
  quantityInOrder: number
}
```

### `AvailableGiftSummary`

```tsx
interface AvailableGiftSummary {
  totalGiftValueUsed: number
  remainingGiftValue: number
  totalGifts: number
  gifts: AvailableGift[]
}
```

## Usage Examples

### Complete Gift Management Flow

```tsx
import { useAvailableGifts, useAddGiftToOrder, useAdjustGiftOnOrder } from '@hg-storefront/gift'

function GiftManagement() {
  const { data: giftSummary, isLoading: giftsLoading } = useAvailableGifts()
  const { addGift, isLoading: addingGift } = useAddGiftToOrder()
  const { adjustOrderLine, isLoading: adjustingGift } = useAdjustGiftOnOrder()

  const handleAddGift = async (giftId: string) => {
    try {
      await addGift(giftId)
      // Gift added successfully
    } catch (error) {
      console.error('Failed to add gift:', error)
    }
  }

  const handleAdjustGift = async (orderLineId: string, quantity: number) => {
    try {
      await adjustOrderLine(orderLineId, quantity)
      // Gift quantity adjusted successfully
    } catch (error) {
      console.error('Failed to adjust gift:', error)
    }
  }

  if (giftsLoading) return <div>Loading gifts...</div>

  return (
    <div>
      <h2>Available Gifts</h2>
      {giftSummary?.gifts?.map((gift) => (
        <div key={gift.id}>
          <h3>{gift.name}</h3>
          <p>Eligible: {gift.isEligible ? 'Yes' : 'No'}</p>
          {gift.isEligible && (
            <button onClick={() => handleAddGift(gift.id)} disabled={addingGift}>
              Add Gift
            </button>
          )}
          {gift.quantityInOrder > 0 && (
            <div>
              <p>Quantity: {gift.quantityInOrder}</p>
              <button
                onClick={() => handleAdjustGift(gift.id, gift.quantityInOrder - 1)}
                disabled={adjustingGift}
              >
                Decrease
              </button>
              <button
                onClick={() => handleAdjustGift(gift.id, gift.quantityInOrder + 1)}
                disabled={adjustingGift || gift.quantityInOrder >= gift.maxQuantity}
              >
                Increase
              </button>
            </div>
          )}
        </div>
      ))}
    </div>
  )
}
```

## Dependencies

This library depends on:

- `@haus-storefront-react/core` - For SDK and query functionality
- `@haus-storefront-react/vendure-plugin-configs` - For plugin configuration
- `@haus-storefront-react/shared-types` - For type definitions

## Development

To build this library:

```bash
nx build gift
```

To lint this library:

```bash
nx lint gift
```