UNPKG

self-serve-integration-service

Version:

Self-Serve Integration Service for managing multiple funder integrations including REST APIs, SOAP APIs, and UI automation

354 lines (275 loc) 9.12 kB
# Lex Autolease API Integration This document describes the integration of the Lex Autolease API with the Self-Serve Integration Service, providing comprehensive quote generation and management capabilities. ## Overview The Lex Autolease API integration allows the Self-Serve platform to: - Calculate vehicle finance quotes - Re-calculate quotes with updated parameters - Complete quotes for proposal submission - Retrieve quote details - Manage the complete quote lifecycle ## Authentication The Lex API uses JWT (JSON Web Token) Bearer authentication. The service automatically generates and manages JWT tokens based on the configuration in your environment variables. ### JWT Token Structure The JWT token includes the following claims as required by Lex: ```json { "sub": "APP_ID", "nbf": "NOT_BEFORE_TIMESTAMP", "exp": "EXPIRATION_TIMESTAMP", "iat": "ISSUED_AT_TIMESTAMP", "lbg_major_dealerid": "MAJOR_DEALER_ID", "lbg_minor_dealerid": "MINOR_DEALER_ID" } ``` ### Environment Variables Add the following variables to your `.env` file: ```bash # Lex Autolease API Configuration LEX_API_BASE_URL=https://training-api.lexautolease.co.uk/api/v1 LEX_APP_ID=your-lex-app-id LEX_SHARED_SECRET=your-lex-shared-secret LEX_DEALER_ID_MAJOR=your-lex-major-dealer-id LEX_DEALER_ID_MINOR=your-lex-minor-dealer-id LEX_JWT_EXPIRY_HOURS=24 ``` ## API Endpoints ### 1. Calculate Quote **POST** `/api/lex/quotes/calculate` Calculates and generates a pre-completed quote reference number. **Request Body:** ```json { "asset": { "cap_id": "CAP12345", "model_year": 2024, "options": ["Navigation", "Leather Seats"] }, "accessories": [ { "type": "DealerFit", "description": "Premium Sound System", "price": 1500.00 } ], "financials": { "contract_type_id": "PCP", "plan": "Standard", "term": 36, "mileage": 15000, "customer_initial_payment": 2000.00, "estimated_sales_value": 8000.00 }, "adjustments": { "off_invoice_support": 500.00, "discount": 750.00 } } ``` **Response:** ```json { "success": true, "message": "Quote calculated successfully", "data": { "quote_id": "Q12345", "quote_reference": "LEX-2024-001", "vehicle_description": "BMW 3 Series 320d M Sport", "price_breakdown": { "monthly_payment": 450.00, "total_amount": 16200.00, "interest_rate": 4.9, "balloon_payment": 8000.00 }, "valid_until": "2024-12-31T23:59:59Z", "status": "ACTIVE" } } ``` ### 2. Re-calculate Quote **POST** `/api/lex/quotes/{qref}/calculate` Re-calculates a quote when there are changes to input parameters. **Parameters:** - `qref`: Quote reference number **Request Body:** Same as Calculate Quote ### 3. Complete Quote **POST** `/api/lex/quotes/{qref}/complete` Completes a pre-calculated quote, generating a completed quote reference number. **Parameters:** - `qref`: Quote reference number **Request Body:** Same as Calculate Quote ### 4. Calculate and Complete Quote **POST** `/api/lex/quotes/complete` Calculates and completes a quote in a single request. **Request Body:** Same as Calculate Quote ### 5. Get Quote **GET** `/api/lex/quotes/{qref}` Retrieves quote details by reference number. **Parameters:** - `qref`: Quote reference number ## Data Models ### LexAsset ```typescript interface LexAsset { cap_id?: string; // CAP ID for the vehicle cap_code?: string; // CAP code for the vehicle model_year?: number; // Model year (required) options?: string[]; // List of vehicle options } ``` ### LexAccessories ```typescript interface LexAccessories { type: 'DealerFit' | 'Third Party'; // Accessory type description: string; // Description (max 150 chars) price: number; // Price (0.00 - 99,999.99) } ``` ### LexFinancials ```typescript interface LexFinancials { contract_type_id: string; // Contract type (required) plan: string; // Plan name (required) term: number; // Term in months (12-60, required) mileage: number; // Annual mileage (5,000-50,000, required) relief_vehicle?: boolean; // Relief vehicle included customer_initial_payment?: number; // Initial payment amount estimated_sales_value?: number; // Estimated sales value cust_reference?: string; // Customer reference estimated_delivery_date?: string; // Delivery date } ``` ### LexAdjustments ```typescript interface LexAdjustments { off_invoice_support?: number; // Off invoice support otrp?: number; // On The Road Price commission?: number; // Commission amount discount?: number; // Discount amount customer_terms?: string; // Customer specific terms co2_emission?: number; // CO2 emission value } ``` ## Validation Rules ### Asset Validation - `model_year` is required and must be between 1900-2030 - Either `cap_id` or `cap_code` is required ### Financial Validation - `contract_type_id`, `plan`, `term`, and `mileage` are required - `term` must be between 12-60 months - `mileage` must be between 5,000-50,000 miles ### Accessories Validation - `type` must be either "DealerFit" or "Third Party" - `description` is required and limited to 150 characters - `price` must be between £0.00 and £99,999.99 ## Rate Limits - **Maximum requests:** 20 per second per IP address - **Response timeout:** 60 seconds - **Token expiry:** Configurable (default: 24 hours) ## Error Handling The API returns standard HTTP status codes and error messages: ```json { "success": false, "message": "Error description", "error": "Detailed error information" } ``` Common error codes: - `400`: Bad Request - Validation error - `401`: Unauthorized - Invalid JWT token - `404`: Not Found - Quote not found - `429`: Too Many Requests - Rate limit exceeded - `500`: Internal Server Error ## Usage Examples ### Node.js/JavaScript ```javascript const axios = require('axios'); // Calculate a quote const calculateQuote = async () => { try { const response = await axios.post('http://localhost:3003/api/lex/quotes/calculate', { asset: { cap_id: 'CAP12345', model_year: 2024 }, financials: { contract_type_id: 'PCP', plan: 'Standard', term: 36, mileage: 15000 } }, { headers: { 'Authorization': 'Bearer YOUR_JWT_TOKEN', 'Content-Type': 'application/json' } }); console.log('Quote calculated:', response.data); } catch (error) { console.error('Error:', error.response?.data || error.message); } }; ``` ### cURL ```bash # Calculate quote curl -X POST http://localhost:3003/api/lex/quotes/calculate \ -H "Authorization: Bearer YOUR_JWT_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "asset": { "cap_id": "CAP12345", "model_year": 2024 }, "financials": { "contract_type_id": "PCP", "plan": "Standard", "term": 36, "mileage": 15000 } }' # Get quote details curl -X GET http://localhost:3003/api/lex/quotes/LEX-2024-001 \ -H "Authorization: Bearer YOUR_JWT_TOKEN" ``` ## Testing Run the test suite to verify the integration: ```bash npm test -- --testPathPattern=lexService.test.ts ``` ## Monitoring and Logging The service logs all Lex API interactions for monitoring and debugging: - **Info level:** Successful operations - **Warn level:** Configuration issues - **Error level:** API failures and errors - **Debug level:** JWT token generation details ## Troubleshooting ### Common Issues 1. **JWT Token Generation Failed** - Check environment variables are set correctly - Verify shared secret format - Ensure dealer IDs are valid 2. **API Request Timeout** - Check network connectivity to Lex API - Verify rate limits aren't exceeded - Check API endpoint availability 3. **Validation Errors** - Review request payload against schema - Check required fields are present - Verify data types and ranges ### Debug Mode Enable debug logging by setting: ```bash LOG_LEVEL=debug ``` This will provide detailed information about JWT token generation and API requests. ## Support For issues with the Lex API integration: 1. Check the service logs for error details 2. Verify environment configuration 3. Test with the provided examples 4. Contact the Self-Serve team for assistance ## References - [Lex Autolease API Documentation](docs/Generic Partner - Quotes API Definition Document v1.7.pdf) - [JWT Token Generation Guide](docs/jwt token.txt) - [API Quotes Examples](docs/quotes.txt)