ekatra/product-sdk

Ekatra Product SDK for PHP - Transform your product data into Ekatra Co-Deciding format

Installs: 33

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/ekatra/product-sdk

2.1.8 2025-12-12 06:42 UTC

This package is auto-updated.

Last update: 2026-01-12 06:57:21 UTC


README

A powerful PHP SDK for transforming your product data into the standardized Ekatra format. This SDK allows you to easily convert your existing product data structures into the Ekatra product format, making it simple to integrate with Ekatra's ecosystem.

Features

  • ๐Ÿš€ Smart Auto-Transformation - Automatically converts simple data to complex Ekatra structure
  • ๐Ÿง  Intelligent Detection - Detects data complexity and applies appropriate transformation
  • ๐Ÿ”„ Robust Field Mapping - Maps 50+ field variations across different naming conventions
  • โœ… Educational Validation - Clear error messages with actionable suggestions
  • ๐Ÿ› ๏ธ Manual Setup Guide - Step-by-step instructions for complex requirements
  • ๐ŸŽฏ Laravel Integration - Full Laravel support with facades, commands, and service providers
  • ๐Ÿงช Customer Testing Tools - Easy verification tools for customers
  • ๐Ÿ“š Comprehensive Documentation - Complete guides, examples, and troubleshooting

Installation

Via Composer

composer require ekatra/product-sdk

Laravel Integration

The SDK automatically registers with Laravel. If you're using Laravel 5.5+, the service provider will be auto-discovered.

For older Laravel versions, add the service provider to config/app.php:

'providers' => [
    // ...
    Ekatra\Product\Laravel\ServiceProvider::class,
],

Quick Start

๐Ÿš€ Smart Flexible Transformation (v2.0.0 - RECOMMENDED)

For Laravel Users (Option B - Recommended)

use Ekatra\Product\EkatraSDK;

class ProductController extends Controller
{
    public function getProduct($id)
    {
        $myProduct = Product::findOrFail($id);
        
        // One line transformation!
        $result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());
        
        if ($result['status'] === 'success') {
            // Apply your business rules (Option B)
            $limitedQuantityIds = [20051, 20052, 20053];
            if (in_array($result['data']['productId'], $limitedQuantityIds)) {
                $result['additionalInfo']['maxQuantity'] = 1;
            }
            
            return response()->json($result);
        }
        
        return response()->json(['status' => 'error'], 400);
    }
}

For Direct Usage

use Ekatra\Product\EkatraSDK;

// Your simple product data (any format)
$customerData = [
    'product_id' => 20051,
    'title' => 'Multicolor Gemstone Orb Earrings',
    'description' => 'Beautiful earrings with gemstones',
    'currency' => 'USD',
    'existing_url' => 'https://mystore.com/earrings',
    'product_keywords' => 'earrings,studs',
    'variant_name' => 'earrings',
    'variant_quantity' => 15,
    'variant_mrp' => 2257,
    'variant_selling_price' => 2118,
    'max_quantity' => 1,  // โœจ NEW: Set quantity limit for ready-to-ship products
    'image_urls' => 'url1,url2,url3'
];

// One line transformation with new v2.0.0 structure!
$result = EkatraSDK::smartTransformProductFlexible($customerData);

if ($result['status'] === 'success') {
    // Get your perfectly formatted Ekatra product
    $ekatraProduct = $result['data'];
    $maxQuantity = $result['metadata']['maxQuantity'];
    echo "โœ… Auto-transformed successfully!";
    echo $maxQuantity ? "Max quantity: $maxQuantity" : "No quantity limit";
} else {
    // Get clear error guidance
    foreach ($result['metadata']['validation']['errors'] as $error) {
        echo "โŒ $error";
    }
}

๐Ÿ”„ Product Sync Methods (NEW in v2.1.4)

For bulk product syncing to Ekatra APIs, use these methods to transform minimal product data into the standardized Ekatra format.

syncProductData() - Single Product (Returns Data Only)

Transforms a single product and returns just the product data array. Throws exception on validation failure.

Required fields (flexible field names supported):

  • productId: productId, product_id, id, item_id, sku, productCode, etc.
  • title: title, name, product_name, product_title, productName, etc.
  • currency: currency, currency_code, currencyCode, curr, etc.
  • imageUrl: imageUrl, image_url, image_urls, images, thumbnail, photo, thumbnailUrl, etc.
use Ekatra\Product\EkatraSDK;
use Ekatra\Product\Exceptions\EkatraValidationException;

try {
    // Accepts flexible field names
    $productData = [
        'product_id' => '20269',
        'title' => 'Geometric Rose Gold Diamond Stud Earrings',
        'currency' => 'INR',
        'image_urls' => 'https://example.com/image1.jpg,https://example.com/image2.jpg'
    ];
    
    // Returns just the product data (no wrapper)
    $transformedProduct = EkatraSDK::syncProductData($productData);
    
    // $transformedProduct contains complete Ekatra structure with defaults:
    // - productId, title, currency
    // - searchKeywords: ""
    // - specifications: []
    // - offers: [{productOfferDetails: [{}]}]
    // - variants: [{_id, color: "unknown", variations: [...], weight: 1, ...}]
    // - sizes: [{_id, name: "freestyle"}]
    
} catch (EkatraValidationException $e) {
    echo "Validation failed: " . $e->getMessage();
    print_r($e->getErrors());
}

syncProductsBatch() - Multiple Products (Batch Processing)

Transforms multiple products and returns successful transformations and failures separately. Perfect for bulk operations.

use Ekatra\Product\EkatraSDK;

// Array of products (each with flexible field names)
$products = [
    [
        'product_id' => '20269',
        'title' => 'Product 1',
        'currency' => 'INR',
        'image_urls' => 'https://example.com/img1.jpg'
    ],
    [
        'productId' => '20270',
        'name' => 'Product 2',
        'currency_code' => 'USD',
        'images' => ['https://example.com/img2.jpg']
    ],
    [
        'title' => 'Invalid Product'  // Missing required fields
    ]
];

// Transform all products
$result = EkatraSDK::syncProductsBatch($products);

// Successful transformations
$successfulProducts = $result['successful'];
// Array of transformed product data

// Failed transformations (with original input for retry)
$failedProducts = $result['failed'];
// [
//   [
//     'index' => 2,
//     'input' => ['title' => 'Invalid Product', ...],
//     'error' => 'Product ID is required',
//     'validation' => ['errors' => [...], 'code' => 422]
//   ]
// ]

// Summary
$summary = $result['summary'];
// ['total' => 3, 'successful' => 2, 'failed' => 1]

Building Event Structure for API Sync

Use the batch method to transform products and build event structures for syncing to Ekatra APIs:

use Ekatra\Product\EkatraSDK;

// Step 1: Get raw products from your system
$rawProducts = [
    ['product_id' => '20269', 'title' => 'Product 1', 'currency' => 'INR', 'image_urls' => '...'],
    ['product_id' => '20270', 'title' => 'Product 2', 'currency' => 'INR', 'image_urls' => '...'],
    // ... more products
];

// Step 2: Transform all products
$result = EkatraSDK::syncProductsBatch($rawProducts);

// Step 3: Build event structure with successful products
$event = [
    'eventType' => 'PRODUCT_CREATE',
    'eventId' => 'evt_' . time(),
    'timestamp' => date('c'), // ISO 8601 format
    'products' => $result['successful']  // Only successful transformations
];

// Step 4: Send to Ekatra API
// sendToEkatraAPI($event);

// Step 5: Handle failures (log, notify, retry, etc.)
if (!empty($result['failed'])) {
    foreach ($result['failed'] as $failure) {
        // Log with original input for debugging/retry
        error_log("Product at index {$failure['index']} failed: {$failure['error']}");
        error_log("Original input: " . json_encode($failure['input']));
        
        // Optionally: Fix and retry
        // $fixed = fixProductData($failure['input']);
        // $retryResult = EkatraSDK::syncProductData($fixed);
    }
}

// Step 6: Report summary
echo "Processed: {$result['summary']['total']}\n";
echo "Successful: {$result['summary']['successful']}\n";
echo "Failed: {$result['summary']['failed']}\n";

syncProduct() - Single Product (With Response Wrapper)

Returns the full ResponseBuilder format (status, data, metadata, message). Use this when you need validation details and error handling.

use Ekatra\Product\EkatraSDK;

$productData = [
    'productId' => '20269',
    'title' => 'Product Name',
    'currency' => 'INR',
    'imageUrl' => 'https://example.com/image.jpg'
];

$result = EkatraSDK::syncProduct($productData);

if ($result['status'] === 'success') {
    $product = $result['data'];
    $metadata = $result['metadata'];
    // Full response with validation details
} else {
    // Error response with validation details
    $errors = $result['metadata']['validation']['errors'];
}

Supported Input Formats

All sync methods accept flexible field names and handle various input formats:

Field Name Variations:

  • Product ID: productId, product_id, id, item_id, sku, productCode, product_code, etc.
  • Title: title, name, product_name, product_title, productName, item_name, etc.
  • Currency: currency, currency_code, currencyCode, curr, curr_code, etc.
  • Image URL: imageUrl, image_url, image_urls, images, thumbnail, photo, thumbnailUrl, thumbnail_url, etc.

Nested Structures:

// Handles nested structures automatically
$data = [
    'product_details' => [
        'product_id' => '123',
        'title' => 'Product',
        'currency' => 'USD',
        'image_url' => 'https://...'
    ]
];

// Also handles: 'product', 'data', 'result' keys

Image Formats:

// Single URL string
'imageUrl' => 'https://example.com/image.jpg'

// Comma-separated URLs (uses first)
'image_urls' => 'url1,url2,url3'

// Array of URLs (uses first)
'images' => ['url1', 'url2', 'url3']

// Array of objects
'images' => [
    ['url' => 'https://...'],
    ['src' => 'https://...']
]

โš ๏ธ Legacy Method (DEPRECATED - Will be removed in v3.0.0)

// โŒ DEPRECATED: Use smartTransformProductFlexible() instead
$result = EkatraSDK::smartTransformProduct($customerData);

Manual Setup (For Complex Requirements)

use Ekatra\Product\EkatraSDK;

// Create product manually
$product = EkatraSDK::product();
$product->setBasicInfo("PROD001", "My Product", "Description", "USD");
$product->setUrl("https://mystore.com/product");
$product->setKeywords(["jewelry", "ring"]);

// Create variant with variations
$variant = EkatraSDK::variant();
$variant->setBasicInfo("Gold Ring", 10, 1000, 800);
$variant->setColor("gold");

// Add variation
$variant->addVariation([
    'sizeId' => 'size-s',
    'mrp' => 1000,
    'sellingPrice' => 800,
    'availability' => true,
    'quantity' => 10,
    'size' => 'Small',
    'variantId' => 'var-001'
]);

// Add media
$variant->addMedia([
    'mediaType' => 'IMAGE',
    'playUrl' => 'https://example.com/image.jpg',
    'mimeType' => 'image/jpeg',
    'playerTypeEnum' => 'IMAGE'
]);

$product->addVariant($variant);
$product->addSize("size-s", "Small");

// Transform to Ekatra format
$result = $product->toEkatraFormatWithValidation();

Basic Usage (Legacy)

use Ekatra\Product\EkatraSDK;

// Transform your product data
$customerData = [
    'id' => 'PROD001',
    'name' => 'Silver Ring',
    'description' => 'Beautiful silver ring',
    'url' => 'https://mystore.com/products/ring001',
    'keywords' => 'rings,silver,jewelry',
    'variants' => [
        [
            'name' => 'Silver Ring - Size 6',
            'price' => 850,
            'originalPrice' => 1000,
            'stock' => 25,
            'color' => 'Silver',
            'size' => '6',
            'images' => ['img1.jpg', 'img2.jpg']
        ]
    ]
];

$result = EkatraSDK::transformProduct($customerData);

if ($result['status'] === 'success') {
    echo "Transformation successful!";
    $ekatraFormat = $result['data'];
} else {
    echo "Transformation failed: " . $result['error'];
}

Laravel Usage

๐Ÿš€ Recommended: smartTransformProductFlexible (v2.0.0)

use Ekatra\Product\EkatraSDK;

class ProductController extends Controller
{
    public function getProduct($id)
    {
        $myProduct = Product::findOrFail($id);
        
        // Transform using the new flexible method
        $result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());
        
        if ($result['status'] === 'success') {
            // Option B: Override maxQuantity based on business logic
            $limitedQuantityProductIds = [20051, 20052, 20053]; // Products with quantity limits
            
            if (in_array($result['data']['productId'], $limitedQuantityProductIds)) {
                $result['additionalInfo']['maxQuantity'] = 1;
            }
            
            return response()->json($result);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'Product transformation failed',
                'additionalInfo' => $result['additionalInfo']
            ], 400);
        }
    }
}

๐ŸŽฏ Advanced Laravel Implementation

class ProductController extends Controller
{
    private $limitedQuantityProducts = [
        'premium' => [20051, 20052],
        'exclusive' => [30001, 30002],
        'limited_edition' => [40001, 40002, 40003],
    ];
    
    public function getProduct($id)
    {
        $myProduct = Product::findOrFail($id);
        $result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());
        
        if ($result['status'] === 'success') {
            // Apply business rules for quantity limits
            $this->applyQuantityLimits($result);
            
            // Add custom API fields
            $result['apiVersion'] = '2.0.0';
            $result['transformedAt'] = now()->toISOString();
            
            return response()->json($result);
        }
        
        return $this->handleTransformationError($result);
    }
    
    private function applyQuantityLimits(&$result)
    {
        $productId = $result['data']['productId'];
        
        foreach ($this->limitedQuantityProducts as $category => $ids) {
            if (in_array($productId, $ids)) {
                $result['additionalInfo']['maxQuantity'] = 
                    ($category === 'limited_edition') ? 2 : 1;
                $result['additionalInfo']['productCategory'] = $category;
                break;
            }
        }
    }
    
    private function handleTransformationError($result)
    {
        return response()->json([
            'status' => 'error',
            'message' => 'Product transformation failed',
            'validation' => $result['metadata']['validation'] ?? null,
            'suggestions' => $result['metadata']['suggestions'] ?? []
        ], 400);
    }
}

โš ๏ธ Legacy Laravel Usage (DEPRECATED)

// โŒ DEPRECATED: Use smartTransformProductFlexible() instead
class ProductController extends Controller
{
    public function getProduct($id)
    {
        $myProduct = Product::findOrFail($id);
        $ekatraProduct = EkatraSDK::productFromData($myProduct->toArray());
        
        return response()->json($ekatraProduct->toEkatraFormatWithValidation());
    }
}

๐Ÿš€ Flexible API Transformation (NEW in v1.1.0)

The SDK now supports flexible field mapping that works with any API response format! This is the recommended approach for maximum compatibility.

Supported API Formats

  • Shopify: {id, title, variants: [...], images: [...]}
  • WooCommerce: {id, name, price, regular_price, tags: [...]}
  • Magento: {id, name, custom_attributes: [...]}
  • Generic E-commerce: {item_id, product_name, price, images: [...]}
  • Minimal: {id, name, price} (just the basics!)

Flexible Transformation Methods

smartTransformProductFlexible() - RECOMMENDED

use Ekatra\Product\EkatraSDK;

// Works with ANY API format!
$result = EkatraSDK::smartTransformProductFlexible($customerData);

if ($result['status'] === 'success') {
    echo "โœ… Transformation successful!";
    echo json_encode($result['data'], JSON_PRETTY_PRINT);
} else {
    echo "โŒ Transformation failed:";
    foreach ($result['metadata']['validation']['errors'] as $error) {
        echo "- " . $error;
    }
}

transformProductFlexible() - ALIAS

// Same as smartTransformProductFlexible() but shorter
$result = EkatraSDK::transformProductFlexible($customerData);

Real-World Examples

Shopify API Format

$shopifyData = [
    'id' => 123456789,
    'title' => 'Classic T-Shirt',
    'body_html' => '<p>Comfortable cotton t-shirt</p>',
    'price' => '29.99',
    'compare_at_price' => '39.99',
    'variants' => [
        [
            'id' => 987654321,
            'title' => 'Small / Red',
            'price' => '29.99',
            'compare_at_price' => '39.99',
            'inventory_quantity' => 10
        ]
    ],
    'images' => [
        ['src' => 'https://cdn.shopify.com/tshirt-red.jpg']
    ]
];

$result = EkatraSDK::smartTransformProductFlexible($shopifyData);
// โœ… Works perfectly!

Minimal Format

$minimalData = [
    'id' => 999,
    'name' => 'Basic Product',
    'price' => 50.00
];

$result = EkatraSDK::smartTransformProductFlexible($minimalData);
// โœ… Works perfectly! Creates default variant automatically

Migration from Old Methods

โšก Old way (DEPRECATED):

$result = EkatraSDK::smartTransformProduct($customerData);
if ($result['status'] === 'success') { // Old boolean format
    $data = $result['data'];
}

โœ… New way (RECOMMENDED):

$result = EkatraSDK::smartTransformProductFlexible($customerData);
if ($result['status'] === 'success') { // New string format
    $data = $result['data'];
    $validation = $result['metadata']['validation'];
    $maxQuantity = $result['metadata']['maxQuantity'];
}

๐Ÿš€ Laravel Migration Guide

From Legacy Laravel Usage:

// โŒ OLD: Manual product creation
$result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());
return response()->json($result);

To New Flexible Approach:

// โœ… NEW: One-line transformation with business logic
$result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());

if ($result['status'] === 'success') {
            // Apply your business rules
            if ($this->hasQuantityLimit($result['data']['productId'])) {
                $result['additionalInfo']['maxQuantity'] = 1;
            }
    
    return response()->json($result);
}

Key Changes:

  • โœ… Use smartTransformProductFlexible() instead of manual product creation
  • โœ… Check $result['status'] === 'success' instead of $result['success']
  • โœ… Access validation via $result['metadata']['validation']
  • โœ… Override maxQuantity in $result['metadata']['maxQuantity']

๐Ÿ› ๏ธ Laravel Implementation Guide (Option B)

๐ŸŽฏ Recommended Approach for Laravel Users

The Option B approach gives you complete control over quantity limits and business logic:

use Ekatra\Product\EkatraSDK;

class ProductController extends Controller
{
    public function getProduct($id)
    {
        $myProduct = Product::findOrFail($id);
        
        // Step 1: Transform using SDK
        $result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());
        
        if ($result['status'] === 'success') {
            // Step 2: Apply your business rules
            $this->applyBusinessRules($result);
            
            // Step 3: Return customized response
            return response()->json($result);
        }
        
        return $this->handleError($result);
    }
    
    private function applyBusinessRules(&$result)
    {
        $productId = $result['data']['productId'];
        
        // Your quantity limit business logic
        if ($this->hasQuantityLimit($productId)) {
            $result['additionalInfo']['maxQuantity'] = 1;
            $result['additionalInfo']['quantityStatus'] = 'limited';
        }
        
        // Add custom fields for your API
        $result['additionalInfo']['apiVersion'] = '2.0.0';
        $result['additionalInfo']['processedAt'] = now()->toISOString();
    }
    
    private function hasQuantityLimit($productId)
    {
        $limitedQuantityIds = [20051, 20052, 20053, 20054];
        return in_array($productId, $limitedQuantityIds);
    }
}

๐Ÿš€ Benefits of Option B

  • โœ… Complete Control - You decide which products have quantity limits
  • โœ… Dynamic Configuration - Easy to update business rules
  • โœ… No Data Changes - No need to modify your product database
  • โœ… API Flexibility - Customize response for your frontend needs
  • โœ… Easy Testing - Simple to test different scenarios
  • โœ… Business Logic Separation - Keep quantity rules separate from product data

๐Ÿ› ๏ธ Response Modification (Option B)

You can easily customize the response for your API needs:

Basic Response Modification

use Ekatra\Product\EkatraSDK;

$result = EkatraSDK::smartTransformProductFlexible($customerData);

if ($result['status'] === 'success') {
    // Modify the response as needed
    $result['message'] = "Custom success message for API";
    $result['additionalInfo']['maxQuantity'] = 1; // Override quantity limit
    $result['additionalInfo']['customField'] = "Custom value";
    
    return $result; // Return modified response
} else {
    return [
        'status' => 'error',
        'message' => 'Custom error message for API',
        'additionalInfo' => $result['additionalInfo']
    ];
}

Advanced Response Customization

function transformProductForApi($customerData, $maxQuantity = null, $customMessage = null) {
    $result = EkatraSDK::smartTransformProductFlexible($customerData);
    
    // Extract core data
    $data = $result['data'];
    $validation = $result['metadata']['validation'];
    $dataType = $result['additionalInfo']['dataType'];
    
    // Build custom response
    return [
        'status' => 'success',
        'data' => $data,
        'additionalInfo' => [
            'validation' => $validation,
            'dataType' => $dataType,
            'maxQuantity' => $maxQuantity ?? $result['additionalInfo']['maxQuantity'],
            'apiVersion' => '2.0.0',
            'transformedAt' => date('Y-m-d H:i:s'),
            'customField' => 'Your custom value'
        ],
        'message' => $customMessage ?? $result['message']
    ];
}

// Usage
$apiResponse = transformProductForApi($customerData, 1, "Product with quantity limit applied");

Utility Methods

// Check if data can be auto-transformed
$canTransform = EkatraSDK::canAutoTransformFlexible($customerData);

// Get supported API formats
$formats = EkatraSDK::getSupportedApiFormats();
// Returns: ['shopify' => '...', 'WooCom' => '...', etc.]

API Reference

Smart Transformation Methods

Flexible API Transformation (RECOMMENDED for v1.1.0+)

// NEW: Flexible transformation - works with ANY API format
$result = EkatraSDK::smartTransformProductFlexible($customerData);

// Alias for convenience
$result = EkatraSDK::transformProductFlexible($customerData);

// Check if data can be auto-transformed with flexible transformer
$canTransform = EkatraSDK::canAutoTransformFlexible($customerData);

// Get supported API formats
$formats = EkatraSDK::getSupportedApiFormats();

Legacy Methods (Still Supported)

// โŒ DEPRECATED: Original smart transformation (legacy)
$result = EkatraSDK::smartTransformProduct($customerData);

// โŒ DEPRECATED: Check if data can be auto-transformed with old transformer
$canTransform = EkatraSDK::canAutoTransform($customerData);

// โŒ DEPRECATED: Get educational validation
$validation = EkatraSDK::getEducationalValidation($customerData);

// โŒ DEPRECATED: Get manual setup guide
$guide = EkatraSDK::getManualSetupGuide();

// โŒ DEPRECATED: Get code examples
$examples = EkatraSDK::getCodeExamples();

// โŒ DEPRECATED: Get troubleshooting guide
$troubleshooting = EkatraSDK::getTroubleshootingGuide();

Core Classes

EkatraProduct

The main product class for handling complete product information.

use Ekatra\Product\Core\EkatraProduct;

$product = new EkatraProduct();
$product->setBasicInfo('PROD001', 'Product Title', 'Description', 'INR')
        ->setUrl('https://example.com/product')
        ->setKeywords(['keyword1', 'keyword2'])
        ->addVariant($variant);

EkatraVariant

Handles individual product variants.

use Ekatra\Product\Core\EkatraVariant;

$variant = new EkatraVariant();
$variant->setBasicInfo('Variant Name', 10, 100, 90)
        ->setAttributes('Red', 'M')
        ->setMedia(['image1.jpg'], ['video1.mp4']);

SDK Methods

EkatraSDK::transformProduct(array $data)

Transforms customer product data to Ekatra format.

Parameters:

  • $data (array) - Customer product data

Returns:

[
    'success' => true|false,
    'data' => array|null,
    'validation' => [
        'valid' => true|false,
        'errors' => array
    ],
    'error' => string|null
]

EkatraSDK::validateProduct(array $data)

Validates customer product data without transformation.

Parameters:

  • $data (array) - Customer product data

Returns:

[
    'valid' => true|false,
    'errors' => array
]

Field Mapping

The SDK automatically maps various field names to the Ekatra format:

Product Fields

Ekatra Field Mapped From
productId id, sku, product_id, item_id
title name, title, product_name, item_name
description desc, description, details, summary
existingUrl url, productUrl, product_url, link
keywords keywords, searchKeywords, tags

Variant Fields

Ekatra Field Mapped From
name name, title, variant_name, item_name
color color, colour, variant_color, item_color
size size, variant_size, item_size
quantity quantity, stock, available, inventory
mrp mrp, originalPrice, listPrice, price_original
sellingPrice price, salePrice, current_price, sale_price

Testing

The SDK includes comprehensive testing tools for customers.

Quick Test

# Test with sample data using the customer guide
php customer_test_guide.md

Customer Testing Guide

The customer_test_guide.md file provides comprehensive testing instructions:

  1. Simple Data Test - Tests auto-transformation
  2. Complex Data Test - Tests complex structure handling
  3. Invalid Data Test - Tests error handling
  4. Manual Setup Test - Tests manual product creation

Laravel Testing

# Test mapping with Artisan command
php artisan ekatra:test-mapping

# Test with custom data file
php artisan ekatra:test-mapping --file=path/to/test-data.json

# Test with JSON string
php artisan ekatra:test-mapping --data='{"id":"PROD001","name":"Test Product"}'

# Test only variants
php artisan ekatra:test-mapping --variant

# Test with validation
php artisan ekatra:test-mapping --validate

# Show formatted output
php artisan ekatra:test-mapping --format

Test Endpoints

The SDK provides test endpoints for easy testing:

# Test product mapping
POST /ekatra/test/product
Content-Type: application/json

{
    "id": "PROD001",
    "name": "Test Product",
    "description": "Test Description",
    "variants": [...]
}

# Test variant mapping
POST /ekatra/test/variant
Content-Type: application/json

{
    "name": "Test Variant",
    "price": 100,
    "stock": 10
}

# Get sample data
GET /ekatra/test/sample

Configuration

Publish the configuration file:

php artisan vendor:publish --tag=ekatra-config

This creates config/ekatra.php with customizable settings:

return [
    'default_currency' => 'INR',
    'supported_currencies' => ['INR', 'USD', 'EUR', 'GBP'],
    'validation' => [
        'strict_mode' => false,
        'log_errors' => true,
    ],
    // ... more options
];

Error Handling

The SDK provides flexible error handling:

Validation Errors

$result = EkatraSDK::transformProduct($data);

if ($result['status'] !== 'success') {
    if (isset($result['validation']['errors'])) {
        foreach ($result['validation']['errors'] as $error) {
            echo "Validation Error: $error\n";
        }
    }
}

Exceptions

use Ekatra\Product\Exceptions\EkatraValidationException;

try {
    $product = EkatraSDK::productFromData($data);
    $ekatraFormat = $product->toEkatraFormat();
} catch (EkatraValidationException $e) {
    echo "Validation failed: " . $e->getMessage();
    $errors = $e->getErrors();
}

Examples

Complete Product Example

use Ekatra\Product\EkatraSDK;

$customerData = [
    'id' => 'PROD001',
    'name' => 'Premium Silver Ring',
    'description' => 'High-quality silver ring with premium finish',
    'url' => 'https://mystore.com/products/ring001',
    'keywords' => 'rings,silver,jewelry,premium',
    'currency' => 'INR',
    'specifications' => [
        ['key' => 'Material', 'value' => 'Premium Silver Alloy'],
        ['key' => 'Weight', 'value' => '250g']
    ],
    'offers' => [
        [
            'title' => 'Special Offer',
            'productOfferDetails' => [
                [
                    'title' => 'SAVE20',
                    'description' => '20% off on all silver jewelry'
                ]
            ]
        ]
    ],
    'variants' => [
        [
            'name' => 'Silver Ring - Size 6',
            'price' => 850,
            'originalPrice' => 1000,
            'stock' => 25,
            'color' => 'Silver',
            'size' => '6',
            'images' => ['img1.jpg', 'img2.jpg'],
            'videos' => ['video1.mp4']
        ]
    ]
];

$result = EkatraSDK::transformProduct($customerData);

if ($result['status'] === 'success') {
    $ekatraFormat = $result['data'];
    // Use the transformed data
} else {
    // Handle errors
    $errors = $result['validation']['errors'] ?? [];
}

Laravel Controller Example

class ProductController extends Controller
{
    public function getProduct($id)
    {
        try {
            $product = Product::findOrFail($id);
            $result = EkatraSDK::smartTransformProductFlexible($product->toArray());
            return response()->json($result);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'data' => null,
                'metadata' => ['validation' => ['valid' => false, 'errors' => [$e->getMessage()]]],
                'message' => 'Product transformation failed'
            ], 500);
        }
    }
}

Requirements

  • PHP 8.1 or higher
  • Composer
  • Laravel 9+ (for Laravel integration)

Dependencies

  • Guzzle HTTP (for future API features)
  • Illuminate Support (for Laravel integration)
  • Illuminate Validation (for validation features)

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

This SDK is licensed under the MIT License. See the LICENSE file for details.

Support

For support and questions:

Changelog

Version 1.0.0

  • Initial release
  • Core product and variant classes
  • Smart field mapping
  • Comprehensive validation
  • Laravel integration
  • Testing tools
  • Documentation and examples

Version 1.0.1

  • Fixed default size to 'freestyle' for consistency
  • Improved sizeId linking between variations and sizes arrays
  • Enhanced SmartTransformer size matching logic

Version 1.0.2

  • Fixed discount calculation for simple variant data
  • Added missing discount logic to transformSimpleToComplex method
  • Ensures all transformation paths calculate discounts correctly

Version 2.0.0 - V2 API STRUCTURE & QUANTITY FIXES ๐Ÿš€

โœจ New Features

  • Flattened Response Structure: Moved validation metadata into additionalInfo object
  • Status Field Enhancement: Changed success: boolean โ†’ status: string
  • MaxQuantity Support: New maxQuantity field in additionalInfo for quantity limits
  • Media Object Alignment: Updated mediaList โ†’ media, mediaType โ†’ type, playUrl โ†’ url
  • Thumbnail Enhancement: Added thumbnailUrl field within media objects
  • Quantity Bug Fix: Fixed issue where quantity was showing 0 instead of actual input values

๐Ÿ› ๏ธ Response Structure Changes

  • Old Structure: {success: true, data: {...}, validation: {...}}
  • New Structure: {status: "success", data: {...}, metadata: {validation: {...}, maxQuantity: number, sdkVersion: "2.0.5"}}

๐Ÿ”ง New Methods

  • extractMaxQuantity() - Extracts quantity limits from input data
  • Enhanced smartTransformProductFlexible() - Now returns v2.0.0 structure

Version 1.0.5 - FLEXIBLE API TRANSFORMATION (PREVIOUS)

โœจ New Features

  • Flexible API Transformation: New smartTransformProductFlexible() method that works with ANY API format
  • Multi-Platform Support: Handles Shopify, WooCommerce, Magento, and generic e-commerce formats
  • Smart Field Mapping: Automatically maps 50+ field variations across different naming conventions
  • Nested Data Extraction: Handles complex nested structures like {success: true, product_details: {...}}
  • Default Variant Creation: Creates sensible defaults for minimal data formats
  • Backward Compatibility: All existing methods continue to work unchanged

๐Ÿ”ง New Methods

  • EkatraSDK::smartTransformProductFlexible($data) - RECOMMENDED for new implementations
  • EkatraSDK::transformProductFlexible($data) - Alias for convenience
  • EkatraSDK::canAutoTransformFlexible($data) - Check transformation capability
  • EkatraSDK::getSupportedApiFormats() - List supported API formats

๐Ÿ› ๏ธ Technical Improvements

  • PSR-4 Autoloading: Fixed autoloader configuration for better compatibility
  • Enhanced Validation: More flexible validation with smart defaults
  • Better Error Handling: Clearer error messages and suggestions
  • CI/CD Pipeline: Added GitHub Actions for automated testing

๐Ÿ“š Documentation

  • Updated README with comprehensive examples for all supported formats
  • Added migration guide for existing users
  • Real-world examples for each API format

๐Ÿ”ง Technical Improvements

  • PSR-4 Autoloading: Fixed autoloader configuration for better compatibility
    • Migration: Run composer dump-autoload after updating
    • Impact: None - backward compatible, just better autoloading