# Pre-Auth Cancel - Examples

This document provides comprehensive examples for cancelling pre-authorized transactions.

---

## Table of Contents

1. [Basic Examples](#basic-examples)
2. [Use Case Examples](#use-case-examples)
3. [Error Handling Examples](#error-handling-examples)
4. [Advanced Examples](#advanced-examples)
5. [Integration Patterns](#integration-patterns)

---

## Basic Examples

### Example 1: Basic Cancellation

Cancel a pre-auth transaction:

```typescript
import { PayWayClient } from 'aba-payway-sdk';

const client = new PayWayClient({
  merchantId: 'ec000002',
  apiKey: process.env.PAYWAY_API_KEY!,
  sandbox: true
});

async function basicCancellation() {
  try {
    const result = await client.cancelPreAuth({
      tranId: '17394277693',
      rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
    });

    console.log('✓ Pre-auth cancelled');
    console.log('Transaction Status:', result.transaction_status);
    console.log('Original Amount:', result.grand_total, result.currency);
    console.log('Status Code:', result.status.code);
  } catch (error: any) {
    console.error('❌ Cancellation failed:', error.message);
  }
}

basicCancellation();
```

### Example 2: Cancel with Status Check

Verify transaction status before cancelling:

```typescript
async function safeCancellation(tranId: string) {
  // Step 1: Check transaction status
  const details = await client.getTransactionDetail({ tranId });
  
  console.log('Transaction ID:', details.data.transaction_id);
  console.log('Current Status:', details.data.payment_status);
  console.log('Original Amount:', details.data.original_amount);

  // Step 2: Verify it's in PRE-AUTH status
  if (details.data.payment_status !== 'PRE-AUTH') {
    throw new Error(
      `Cannot cancel: Transaction is ${details.data.payment_status}, not PRE-AUTH`
    );
  }

  // Step 3: Cancel pre-auth
  const result = await client.cancelPreAuth({
    tranId,
    rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
  });

  console.log('✓ Cancellation successful');
  console.log('Funds released:', result.grand_total, result.currency);
  
  return result;
}
```

### Example 3: Cancel with Comprehensive Logging

```typescript
async function cancelWithLogging(
  tranId: string,
  reason: string,
  userId: string
) {
  console.log('='.repeat(50));
  console.log('PRE-AUTH CANCELLATION');
  console.log('='.repeat(50));
  console.log(`Transaction ID: ${tranId}`);
  console.log(`Reason: ${reason}`);
  console.log(`Requested by: ${userId}`);
  console.log(`Timestamp: ${new Date().toISOString()}`);

  try {
    const result = await client.cancelPreAuth({
      tranId,
      rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
    });

    console.log('\n✓ CANCELLATION SUCCESSFUL');
    console.log(`Status: ${result.transaction_status}`);
    console.log(`Funds Released: ${result.grand_total} ${result.currency}`);
    console.log('='.repeat(50));

    return result;
  } catch (error: any) {
    console.error('\n❌ CANCELLATION FAILED');
    console.error(`Error: ${error.message}`);
    console.error(`Code: ${error.statusCode || 'UNKNOWN'}`);
    console.error('='.repeat(50));
    throw error;
  }
}
```

---

## Use Case Examples

### Example 4: Hotel Booking Cancellation

Handle hotel reservation cancellation with refund policy:

```typescript
interface HotelBooking {
  bookingId: string;
  preAuthTranId: string;
  checkInDate: Date;
  guestName: string;
  roomType: string;
  preAuthAmount: number;
}

async function cancelHotelBooking(
  booking: HotelBooking,
  cancellationReason: string
) {
  console.log(`\nCancelling hotel booking for ${booking.guestName}`);
  console.log(`Booking ID: ${booking.bookingId}`);
  console.log(`Room Type: ${booking.roomType}`);
  console.log(`Reason: ${cancellationReason}`);

  try {
    // Cancel the pre-auth hold
    const result = await client.cancelPreAuth({
      tranId: booking.preAuthTranId,
      rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
    });

    if (result.status.code === '00') {
      console.log('✓ Booking cancelled successfully');
      console.log(`Funds released: ${result.grand_total} ${result.currency}`);
      
      // Update booking status in database
      // await updateBookingStatus(booking.bookingId, 'CANCELLED');
      
      // Send cancellation confirmation email
      // await sendCancellationEmail(booking.guestName, booking.bookingId);
      
      return {
        success: true,
        bookingId: booking.bookingId,
        releasedAmount: result.grand_total,
        currency: result.currency,
        status: 'CANCELLED'
      };
    }
  } catch (error) {
    console.error('Failed to cancel booking:', error);
    throw error;
  }
}

// Usage
await cancelHotelBooking({
  bookingId: 'HTL-2026-001',
  preAuthTranId: '17394277693',
  checkInDate: new Date('2026-03-15'),
  guestName: 'John Doe',
  roomType: 'Deluxe Suite',
  preAuthAmount: 200.00
}, 'Guest requested cancellation');
```

### Example 5: Car Rental Cancellation

Cancel car rental with time-based cancellation policy:

```typescript
interface CarRental {
  reservationId: string;
  preAuthTranId: string;
  pickupDate: Date;
  returnDate: Date;
  vehicleType: string;
  customerName: string;
  depositAmount: number;
}

async function cancelCarRental(
  rental: CarRental,
  reason: string
) {
  // Calculate hours until pickup
  const now = new Date();
  const hoursUntilPickup = (rental.pickupDate.getTime() - now.getTime()) / (1000 * 60 * 60);
  
  // Check cancellation policy
  if (hoursUntilPickup < 24) {
    console.warn('⚠️  Cancelling within 24 hours - late cancellation fee may apply');
  }

  console.log('\n=== Car Rental Cancellation ===');
  console.log(`Reservation ID: ${rental.reservationId}`);
  console.log(`Vehicle: ${rental.vehicleType}`);
  console.log(`Customer: ${rental.customerName}`);
  console.log(`Hours until pickup: ${hoursUntilPickup.toFixed(1)}`);

  try {
    const result = await client.cancelPreAuth({
      tranId: rental.preAuthTranId,
      rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
    });

    if (result.status.code === '00') {
      console.log('✓ Reservation cancelled');
      console.log(`Security deposit released: ${result.grand_total} ${result.currency}`);
      
      return {
        reservationId: rental.reservationId,
        cancelled: true,
        depositReleased: result.grand_total,
        lateCancellation: hoursUntilPickup < 24
      };
    }
  } catch (error) {
    console.error('❌ Cancellation failed:', error);
    throw error;
  }
}
```

### Example 6: E-Commerce Order Cancellation

Cancel online order before fulfillment:

```typescript
interface Order {
  orderId: string;
  preAuthTranId: string;
  customerId: string;
  orderDate: Date;
  items: Array<{
    productId: string;
    name: string;
    quantity: number;
    price: number;
  }>;
  totalAmount: number;
  status: string;
}

async function cancelOrder(
  order: Order,
  cancellationReason: string
) {
  console.log('\n=== Order Cancellation ===');
  console.log(`Order ID: ${order.orderId}`);
  console.log(`Customer ID: ${order.customerId}`);
  console.log(`Total Amount: $${order.totalAmount.toFixed(2)}`);
  console.log(`Items: ${order.items.length}`);
  console.log(`Reason: ${cancellationReason}`);

  // Verify order can be cancelled
  if (order.status === 'SHIPPED') {
    throw new Error('Cannot cancel order - already shipped');
  }

  try {
    const result = await client.cancelPreAuth({
      tranId: order.preAuthTranId,
      rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
    });

    if (result.status.code === '00') {
      console.log('✓ Order cancelled successfully');
      console.log(`Customer refund: ${result.grand_total} ${result.currency}`);
      
      // Restore inventory
      console.log('Restoring inventory...');
      // for (const item of order.items) {
      //   await restoreInventory(item.productId, item.quantity);
      // }
      
      // Update order status
      // await updateOrderStatus(order.orderId, 'CANCELLED');
      
      // Send cancellation notification
      // await sendOrderCancellationEmail(order.customerId, order.orderId);
      
      return {
        orderId: order.orderId,
        cancelled: true,
        refundAmount: result.grand_total,
        inventoryRestored: true
      };
    }
  } catch (error) {
    console.error('❌ Order cancellation failed:', error);
    throw error;
  }
}

// Usage
await cancelOrder({
  orderId: 'ORD-2026-12345',
  preAuthTranId: '17394277693',
  customerId: 'CUST-789',
  orderDate: new Date(),
  items: [
    { productId: 'PROD-001', name: 'Product 1', quantity: 2, price: 25.00 },
    { productId: 'PROD-002', name: 'Product 2', quantity: 1, price: 50.00 }
  ],
  totalAmount: 100.00,
  status: 'PENDING'
}, 'Customer changed mind');
```

### Example 7: Event Ticket Cancellation

Cancel event tickets with seat release:

```typescript
interface EventTicket {
  ticketId: string;
  preAuthTranId: string;
  eventId: string;
  eventName: string;
  eventDate: Date;
  seats: string[];
  customerEmail: string;
  ticketPrice: number;
}

async function cancelEventTicket(
  ticket: EventTicket,
  reason: string
) {
  const daysUntilEvent = Math.floor(
    (ticket.eventDate.getTime() - Date.now()) / (1000 * 60 * 60 *24)
  );

  console.log('\n=== Event Ticket Cancellation ===');
  console.log(`Ticket ID: ${ticket.ticketId}`);
  console.log(`Event: ${ticket.eventName}`);
  console.log(`Date: ${ticket.eventDate.toDateString()}`);
  console.log(`Days until event: ${daysUntilEvent}`);
  console.log(`Seats: ${ticket.seats.join(', ')}`);
  console.log(`Reason: ${reason}`);

  // Check cancellation deadline
  if (daysUntilEvent < 7) {
    console.warn('⚠️  Cancelling within 7 days - cancellation fee applies');
  }

  try {
    const result = await client.cancelPreAuth({
      tranId: ticket.preAuthTranId,
      rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
    });

    if (result.status.code === '00') {
      console.log('✓ Ticket cancelled');
      console.log(`Refund amount: ${result.grand_total} ${result.currency}`);
      
      // Release seats back to inventory
      console.log(`Releasing seats: ${ticket.seats.join(', ')}`);
      // await releaseSeats(ticket.eventId, ticket.seats);
      
      // Send cancellation email
      // await sendTicketCancellationEmail(ticket.customerEmail, ticket);
      
      return {
        ticketId: ticket.ticketId,
        cancelled: true,
        refundAmount: result.grand_total,
        seatsReleased: ticket.seats,
        lateCancellation: daysUntilEvent < 7
      };
    }
  } catch (error) {
    console.error('❌ Ticket cancellation failed:', error);
    throw error;
  }
}
```

### Example 8: Service Appointment Cancellation

Cancel service appointment with rescheduling option:

```typescript
interface ServiceAppointment {
  appointmentId: string;
  preAuthTranId: string;
  serviceType: string;
  scheduledDate: Date;
  customerName: string;
  depositAmount: number;
  canReschedule: boolean;
}

async function cancelServiceAppointment(
  appointment: ServiceAppointment,
  reason: string,
  wantsToReschedule: boolean = false
) {
  console.log('\n=== Service Appointment Cancellation ===');
  console.log(`Appointment ID: ${appointment.appointmentId}`);
  console.log(`Service: ${appointment.serviceType}`);
  console.log(`Customer: ${appointment.customerName}`);
  console.log(`Scheduled: ${appointment.scheduledDate.toLocaleString()}`);
  console.log(`Reason: ${reason}`);
  console.log(`Wants to Reschedule: ${wantsToReschedule ? 'Yes' : 'No'}`);

  try {
    const result = await client.cancelPreAuth({
      tranId: appointment.preAuthTranId,
      rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
    });

    if (result.status.code === '00') {
      console.log('✓ Appointment cancelled');
      console.log(`Deposit released: ${result.grand_total} ${result.currency}`);
      
      if (wantsToReschedule && appointment.canReschedule) {
        console.log('Customer can reschedule without new deposit');
        // await createRescheduleToken(appointment.appointmentId);
      }
      
      return {
        appointmentId: appointment.appointmentId,
        cancelled: true,
        depositReleased: result.grand_total,
        rescheduleAvailable: wantsToReschedule && appointment.canReschedule
      };
    }
  } catch (error) {
    console.error('❌ Cancellation failed:', error);
    throw error;
  }
}
```

---

## Error Handling Examples

### Example 9: Comprehensive Error Handling

Handle all possible error scenarios:

```typescript
async function cancelWithFullErrorHandling(tranId: string) {
  try {
    // Attempt cancellation
    const result = await client.cancelPreAuth({
      tranId,
      rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
    });

    if (result.status.code === '00') {
      return {
        success: true,
        status: result.transaction_status,
        amount: result.grand_total,
        currency: result.currency
      };
    } else {
      return {
        success: false,
        error: result.status.message,
        code: result.status.code
      };
    }
  } catch (error: any) {
    // Handle specific error codes
    const errorCode = error.statusCode;
    
    switch (errorCode) {
      case 'PTL59':
        console.error('Pre-auth cannot be cancelled (already completed or cancelled)');
        return {
          success: false,
          error: 'Transaction not eligible for cancellation',
          code: errorCode,
          suggestion: 'Check transaction status first'
        };
      
      case 'PTL36':
        console.error('Invalid transaction ID');
        return {
          success: false,
          error: 'Transaction not found',
          code: errorCode,
          suggestion: 'Verify transaction ID is correct'
        };
      
      case 'PTL02':
        console.error('Invalid hash value');
        return {
          success: false,
          error: 'Hash validation failed',
          code: errorCode,
          suggestion: 'Check API key and hash generation'
        };
      
      case 'PTL168':
        console.error('Concurrent request detected');
        return {
          success: false,
          error: 'Please retry in a few seconds',
          code: errorCode,
          retry: true
        };
      
      case 'PTL62':
        console.error('Invalid merchant information');
        return {
          success: false,
          error: 'Merchant configuration issue',
          code: errorCode,
          suggestion: 'Contact support'
        };
      
      case 'PTL63':
        console.error('No security configuration file');
        return {
          success: false,
          error: 'Merchant not configured',
          code: errorCode,
          suggestion: 'Contact ABA Bank support'
        };
      
      default:
        console.error('Unexpected error:', error.message);
        return {
          success: false,
          error: error.message,
          code: errorCode || 'UNKNOWN'
        };
    }
  }
}
```

### Example 10: Retry Logic for Concurrent Requests

Implement automatic retry for PTL168 errors:

```typescript
async function cancelWithRetry(
  tranId: string,
  maxRetries: number = 3,
  delayMs: number = 1000
) {
  console.log(`\nAttempting to cancel transaction ${tranId}`);
  console.log(`Max retries: ${maxRetries}`);

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    console.log(`\nAttempt ${attempt}/${maxRetries}...`);

    try {
      const result = await client.cancelPreAuth({
        tranId,
        rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
      });

      console.log(`✓ Succeeded on attempt ${attempt}`);
      return {
        success: true,
        data: result,
        attempts: attempt
      };
    } catch (error: any) {
      const errorCode = error.statusCode;

      // Retry only for concurrent request errors
      if (errorCode === 'PTL168' && attempt < maxRetries) {
        const waitTime = delayMs * attempt; // Exponential backoff
        console.log(`⚠️  Concurrent request detected. Waiting ${waitTime}ms...`);
        await new Promise(resolve => setTimeout(resolve, waitTime));
        continue;
      }

      // Don't retry for other errors
      console.error(`❌ Failed on attempt ${attempt}: ${error.message}`);
      return {
        success: false,
        error: error.message,
        code: errorCode,
        attempts: attempt
      };
    }
  }

  return {
    success: false,
    error: 'Maximum retries exceeded',
    attempts: maxRetries
  };
}
```

### Example 11: Graceful Failure with Fallback

Handle cancellation failure with fallback options:

```typescript
async function cancelWithFallback(
  tranId: string,
  onFailure?: () => Promise<void>
) {
  try {
    // Attempt to cancel
    const result = await client.cancelPreAuth({
      tranId,
      rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
    });

    if (result.status.code === '00') {
      console.log('✓ Pre-auth cancelled successfully');
      return { success: true, method: 'direct_cancel' };
    }
  } catch (error: any) {
    console.error('Direct cancellation failed:', error.message);
    
    // Check if pre-auth is already completed
    try {
      const details = await client.getTransactionDetail({ tranId });
      
      if (details.data.payment_status === 'APPROVED') {
        console.log('Pre-auth was already completed. Initiating refund...');
        
        // Fallback: Refund the completed transaction
        const refundResult = await client.refund({
          tranId,
          refundAmount: details.data.original_amount,
          rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
        });
        
        console.log('✓ Refund processed as fallback');
        return { success: true, method: 'refund_fallback' };
      }
    } catch (fallbackError) {
      console.error('Fallback also failed:', fallbackError);
    }
    
    // Execute custom fallback
    if (onFailure) {
      console.log('Executing custom fallback...');
      await onFailure();
    }
    
    return { success: false, method: 'none' };
  }
}
```

---

## Advanced Examples

### Example 12: Batch Cancellation

Cancel multiple pre-auth transactions:

```typescript
interface CancellationRequest {
  tranId: string;
  reference: string;
  reason: string;
}

async function batchCancelPreAuths(
  requests: CancellationRequest[],
  delayMs: number = 500
) {
  console.log(`\n=== Batch Cancellation ===`);
  console.log(`Total transactions: ${requests.length}`);

  const results = [];

  for (const [index, request] of requests.entries()) {
    console.log(`\n[${index + 1}/${requests.length}] Processing ${request.tranId}`);
    console.log(`Reference: ${request.reference}`);
    console.log(`Reason: ${request.reason}`);

    try {
      const result = await client.cancelPreAuth({
        tranId: request.tranId,
        rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
      });

      results.push({
        tranId: request.tranId,
        reference: request.reference,
        success: true,
        status: result.transaction_status,
        amount: result.grand_total
      });

      console.log('✓ Cancelled successfully');
    } catch (error: any) {
      results.push({
        tranId: request.tranId,
        reference: request.reference,
        success: false,
        error: error.message
      });

      console.error('❌ Failed:', error.message);
    }

    // Delay to avoid rate limiting
    if (index < requests.length - 1 && delayMs > 0) {
      await new Promise(resolve => setTimeout(resolve, delayMs));
    }
  }

  // Summary
  const successful = results.filter(r => r.success).length;
  const failed = results.filter(r => !r.success).length;

  console.log(`\n=== Batch Summary ===`);
  console.log(`Total: ${results.length}`);
  console.log(`Successful: ${successful}`);
  console.log(`Failed: ${failed}`);
  console.log(`Success Rate: ${((successful / results.length) * 100).toFixed(1)}%`);

  return {
    total: results.length,
    successful,
    failed,
    results
  };
}

// Usage
await batchCancelPreAuths([
  { tranId: '17394277693', reference: 'ORD-001', reason: 'Customer request' },
  { tranId: '17394277694', reference: 'ORD-002', reason: 'Out of stock' },
  { tranId: '17394277695', reference: 'ORD-003', reason: 'Duplicate order' }
]);
```

### Example 13: Scheduled Cancellation

Schedule pre-auth cancellation for future time:

```typescript
interface ScheduledCancellation {
  tranId: string;
  scheduleFor: Date;
  reason: string;
  reference: string;
}

async function scheduleCancel(
  cancellation: ScheduledCancellation
) {
  const now = new Date();
  const delayMs = cancellation.scheduleFor.getTime() - now.getTime();

  if (delayMs <= 0) {
    throw new Error('Schedule time must be in the future');
  }

  console.log(`\n=== Scheduled Cancellation ===`);
  console.log(`Transaction ID: ${cancellation.tranId}`);
  console.log(`Reference: ${cancellation.reference}`);
  console.log(`Scheduled for: ${cancellation.scheduleFor.toLocaleString()}`);
  console.log(`Delay: ${(delayMs / 1000 / 60).toFixed(1)} minutes`);
  console.log(`Reason: ${cancellation.reason}`);

  // Schedule the cancellation
  setTimeout(async () => {
    console.log(`\n[SCHEDULED] Executing cancellation for ${cancellation.tranId}`);

    try {
      const result = await client.cancelPreAuth({
        tranId: cancellation.tranId,
        rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
      });

      console.log('✓ Scheduled cancellation completed');
      console.log(`Status: ${result.transaction_status}`);
      
      // Notify relevant parties
      // await sendCancellationNotification(cancellation);
    } catch (error) {
      console.error('❌ Scheduled cancellation failed:', error);
      // Handle failure (retry, notify, etc.)
    }
  }, delayMs);

  console.log('✓ Cancellation scheduled');
}
```

### Example 14: Auto-Cancel on Timeout

Automatically cancel pre-auth if not completed within timeframe:

```typescript
async function autoCancel IfTimeout(
  tranId: string,
  timeoutMinutes: number = 30
) {
  console.log(`\n=== Auto-Cancel Setup ===`);
  console.log(`Transaction ID: ${tranId}`);
  console.log(`Timeout: ${timeoutMinutes} minutes`);

  const timeoutMs = timeoutMinutes * 60 * 1000;
  const timeoutDate = new Date(Date.now() + timeoutMs);

  console.log(`Will auto-cancel at: ${timeoutDate.toLocaleString()}`);

  return new Promise((resolve) => {
    const timeoutId = setTimeout(async () => {
      console.log(`\n[AUTO-CANCEL] Timeout reached for ${tranId}`);

      try {
        // Check if still in PRE-AUTH status
        const details = await client.getTransactionDetail({ tranId });

        if (details.data.payment_status === 'PRE-AUTH') {
          console.log('Transaction still in PRE-AUTH status. Cancelling...');

          const result = await client.cancelPreAuth({
            tranId,
            rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
          });

          console.log('✓ Auto-cancelled due to timeout');
          resolve({ autoCancelled: true, result });
        } else {
          console.log(`Transaction is ${details.data.payment_status}. No action needed.`);
          resolve({ autoCancelled: false, currentStatus: details.data.payment_status });
        }
      } catch (error) {
        console.error('❌ Auto-cancel failed:', error);
        resolve({ autoCancelled: false, error });
      }
    }, timeoutMs);

    // Return function to cancel the timeout
    return () => {
      console.log('Auto-cancel timer cleared');
      clearTimeout(timeoutId);
    };
  });
}
```

---

## Integration Patterns

### Example 15: Complete Cancellation Workflow

Full workflow with notification and database update:

```typescript
interface CancellationWorkflow {
  tranId: string;
  bookingId: string;
  customerId: string;
  amount: number;
  reason: string;
  requestedBy: string;
}

async function executeCancellationWorkflow(
  workflow: CancellationWorkflow
) {
  console.log(`\n=== Cancellation Workflow ===`);
  console.log(`Transaction: ${workflow.tranId}`);
  console.log(`Booking: ${workflow.bookingId}`);
  console.log(`Customer: ${workflow.customerId}`);

  try {
    // Step 1: Validate cancellation eligibility
    console.log('\n[Step 1] Validating eligibility...');
    const details = await client.getTransactionDetail({ tranId: workflow.tranId });
    
    if (details.data.payment_status !== 'PRE-AUTH') {
      throw new Error(`Cannot cancel: Status is ${details.data.payment_status}`);
    }
    console.log('✓ Eligible for cancellation');

    // Step 2: Cancel pre-auth
    console.log('\n[Step 2] Cancelling pre-auth...');
    const result = await client.cancelPreAuth({
      tranId: workflow.tranId,
      rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY!
    });
    console.log('✓ Pre-auth cancelled');

    // Step 3: Update database
    console.log('\n[Step 3] Updating database...');
    // await updateDatabase({
    //   bookingId: workflow.bookingId,
    //   status: 'CANCELLED',
    //   cancelledAt: new Date(),
    //   cancelledBy: workflow.requestedBy,
    //   cancellationReason: workflow.reason
    // });
    console.log('✓ Database updated');

    // Step 4: Send notifications
    console.log('\n[Step 4] Sending notifications...');
    // await sendCustomerNotification(workflow.customerId, {
    //   type: 'CANCELLATION_CONFIRMED',
    //   bookingId: workflow.bookingId,
    //   refundAmount: result.grand_total,
    //   currency: result.currency
    // });
    console.log('✓ Customer notified');

    // Step 5: Log audit trail
    console.log('\n[Step 5] Logging audit trail...');
    // await logAuditTrail({
    //   action: 'PRE_AUTH_CANCELLED',
    //   tranId: workflow.tranId,
    //   bookingId: workflow.bookingId,
    //   amount: result.grand_total,
    //   requestedBy: workflow.requestedBy,
    //   timestamp: new Date()
    // });
    console.log('✓ Audit logged');

    console.log('\n✓ Cancellation workflow completed successfully');
    return {
      success: true,
      tranId: workflow.tranId,
      bookingId: workflow.bookingId,
      refundAmount: result.grand_total,
      currency: result.currency
    };
  } catch (error: any) {
    console.error('\n❌ Workflow failed:', error.message);
    
    // Log failure
    // await logFailure({
    //   workflow: 'CANCELLATION',
    //   tranId: workflow.tranId,
    //   error: error.message,
    //   timestamp: new Date()
    // });
    
    throw error;
  }
}
```

---

## Summary

These examples demonstrate:

- ✅ Basic cancellation operations
- ✅ Real-world use cases (hotel, car rental, e-commerce, events)
- ✅ Comprehensive error handling
- ✅ Retry mechanisms
- ✅ Batch processing
- ✅ Scheduled cancellations
- ✅ Complete workflow integration

For complete API reference, see [REFERENCE.md](./REFERENCE.md).
