Get variant offers
The getProductVariantOffers
function retrieves offers (pricing and availability information) specifically for a product variant. This function is essential for displaying precise pricing information for specific product configurations, enabling users to see exact pricing for their selected variant combination (color, size, specifications, etc.).
Product variant offers provide detailed pricing information tailored to the specific characteristics of each product variant. Unlike general product offers, variant offers reflect pricing differences based on specific attributes such as color premiums, size-based pricing, or configuration-specific costs. This granular pricing approach is crucial for accurate cost calculation and inventory management.
This function is particularly important in B2B scenarios where variant-specific pricing can significantly impact procurement decisions, especially for products with premium configurations or specialized attributes that affect supplier costs and pricing strategies.
Process Flow
sequenceDiagram participant User as User participant Component as Vue Component participant useProduct as useProduct participant SDK as Djust SDK participant API as API Server participant Auth as Auth Service User->>Component: Select Product Variant Component->>useProduct: getProductVariantOffers(params) useProduct->>useProduct: Validate Variant ID useProduct->>SDK: useFetch('/api/product-variants/{id}/offers') SDK->>Auth: Verify Authentication Token Auth-->>SDK: Token Valid SDK->>API: GET /api/product-variants/{productVariantId}/offers alt Success Response API-->>SDK: 200 - Variant Offers SDK-->>useProduct: GetProductVariantOffersResponse useProduct->>useProduct: Process Variant Pricing useProduct-->>Component: Variant-Specific Offers Component-->>User: Display Precise Pricing else No Offers Found API-->>SDK: 404 - No Variant Offers SDK-->>useProduct: Empty Response useProduct->>useProduct: Log No Offers useProduct-->>Component: Empty Offers List Component-->>User: "No pricing for this variant" else Authentication Error Auth-->>SDK: 401 - Unauthorized SDK-->>useProduct: Auth Error useProduct-->>Component: Authentication Error Component-->>User: Redirect to Login else Permission Error API-->>SDK: 403 - Pricing Access Denied SDK-->>useProduct: Permission Error useProduct-->>Component: Access Denied Component-->>User: "Variant pricing not accessible" else Server Error API-->>SDK: 500 - Internal Error SDK-->>useProduct: Server Error useProduct->>useProduct: Log Server Error useProduct-->>Component: Error Response Component-->>User: "Unable to load variant pricing" end
Call Parameters
The function accepts a GetProductVariantOffersRequest
object with the following structure:
GetProductVariantOffersRequest Interface (from SDK)
interface GetProductVariantOffersRequest {
productIdentifier: string;
productIdType?: ProductIdType;
currency?: string;
}
type ProductIdType = "EXTERNAL_ID" | "SKU" | "ID" | "VARIANT_SKU";
Parameter Details
Parameter | Type | Required | Default | Example | Business Impact |
---|---|---|---|---|---|
productIdentifier | string | ✅ Yes | - | "LAPTOP-VARIANT-16GB-SILVER" | Critical: Variant identifier for specific pricing |
productIdType | ProductIdType | ❌ Optional | "EXTERNAL_ID" | "VARIANT_SKU" , "ID" | Important: Determines variant lookup strategy |
currency | string | ❌ Optional | Runtime config | "EUR" , "USD" | Pricing: Currency for variant price display |
Complete Example Call
const variantOffersParams: GetProductVariantOffersRequest = {
productIdentifier: "LAPTOP-DELL-16GB-SILVER",
productIdType: "VARIANT_SKU",
currency: "EUR",
};
const response = await getProductVariantOffers(variantOffersParams);
Returns from Composable
The function returns a GetProductVariantOffersResponse
object with the following structure:
GetProductVariantOffersResponse Interface (from SDK)
interface GetProductVariantOffersResponse {
success: boolean;
offers: ProductVariantOffer[];
totalElements: number;
}
interface ProductVariantOffer {
id: string;
variantSku: string;
productSku: string;
supplierId: string;
supplierName: string;
price: VariantPrice;
availability: VariantAvailability;
specifications: VariantSpecifications;
terms: VariantOfferTerms;
validFrom: string;
validTo?: string;
minimumQuantity: number;
leadTime: number;
variantAttributes: VariantAttribute[];
}
interface VariantPrice {
basePrice: number;
variantPremium: number;
totalPrice: number;
currency: string;
taxIncluded: boolean;
attributePricing: AttributePricing[];
discounts: VariantDiscount[];
}
interface VariantAvailability {
inStock: boolean;
quantity?: number;
stockLocation: string;
variantStatus: "AVAILABLE" | "LIMITED" | "OUT_OF_STOCK" | "DISCONTINUED";
estimatedAvailability?: string;
}
interface VariantSpecifications {
weight?: number;
dimensions?: ProductDimensions;
attributes: Record<string, any>;
packaging: PackagingInfo;
}
interface AttributePricing {
attributeId: string;
attributeValue: string;
priceImpact: number;
impactType: "FIXED" | "PERCENTAGE";
}
Realistic Example JSON Response
{
"success": true,
"offers": [
{
"id": "variant-offer-001",
"variantSku": "LAPTOP-DELL-16GB-SILVER",
"productSku": "LAPTOP-DELL-BASE",
"supplierId": "supplier-tech-pro",
"supplierName": "TechPro Distribution",
"price": {
"basePrice": 849.99,
"variantPremium": 50.0,
"totalPrice": 899.99,
"currency": "EUR",
"taxIncluded": false,
"attributePricing": [
{
"attributeId": "RAM_SIZE",
"attributeValue": "16GB",
"priceImpact": 50.0,
"impactType": "FIXED"
},
{
"attributeId": "COLOR",
"attributeValue": "Silver",
"priceImpact": 0.0,
"impactType": "FIXED"
}
],
"discounts": [
{
"type": "VARIANT_PROMOTION",
"percentage": 5.0,
"description": "5% off on Silver variants this month",
"validUntil": "2024-01-31T23:59:59Z"
}
]
},
"availability": {
"inStock": true,
"quantity": 45,
"stockLocation": "Warehouse Paris - Section A",
"variantStatus": "AVAILABLE",
"estimatedAvailability": "2024-01-25T10:00:00Z"
},
"specifications": {
"weight": 2.1,
"dimensions": {
"length": 35.6,
"width": 23.4,
"height": 1.8,
"unit": "cm"
},
"attributes": {
"ramSize": "16GB DDR4",
"storageType": "SSD",
"storageCapacity": "512GB",
"color": "Silver",
"processor": "Intel i7-11370H"
},
"packaging": {
"type": "RETAIL_BOX",
"weight": 3.2,
"includesAccessories": true
}
},
"terms": {
"paymentTerms": "NET30",
"warranty": "24 months manufacturer + 12 months extended",
"returnPolicy": "30 days DOA, 14 days buyer's remorse",
"shippingTerms": "FOB destination",
"variantSpecificTerms": [
"Color matching guarantee",
"Configuration tested and certified"
]
},
"validFrom": "2024-01-01T00:00:00Z",
"validTo": "2024-03-31T23:59:59Z",
"minimumQuantity": 1,
"leadTime": 2,
"variantAttributes": [
{
"name": "RAM Size",
"value": "16GB",
"impact": "Performance boost for multitasking"
},
{
"name": "Color",
"value": "Silver",
"impact": "Professional appearance"
}
]
},
{
"id": "variant-offer-002",
"variantSku": "LAPTOP-DELL-16GB-SILVER",
"productSku": "LAPTOP-DELL-BASE",
"supplierId": "supplier-euro-tech",
"supplierName": "EuroTech Solutions",
"price": {
"basePrice": 869.99,
"variantPremium": 60.0,
"totalPrice": 929.99,
"currency": "EUR",
"taxIncluded": false,
"attributePricing": [
{
"attributeId": "RAM_SIZE",
"attributeValue": "16GB",
"priceImpact": 60.0,
"impactType": "FIXED"
},
{
"attributeId": "COLOR",
"attributeValue": "Silver",
"priceImpact": 0.0,
"impactType": "FIXED"
}
],
"discounts": []
},
"availability": {
"inStock": true,
"quantity": 12,
"stockLocation": "Warehouse Amsterdam - High-End Section",
"variantStatus": "LIMITED",
"estimatedAvailability": "2024-01-27T15:00:00Z"
},
"specifications": {
"weight": 2.0,
"dimensions": {
"length": 35.6,
"width": 23.4,
"height": 1.8,
"unit": "cm"
},
"attributes": {
"ramSize": "16GB DDR4 Premium",
"storageType": "NVMe SSD",
"storageCapacity": "512GB",
"color": "Premium Silver",
"processor": "Intel i7-11370H"
},
"packaging": {
"type": "PREMIUM_BOX",
"weight": 3.5,
"includesAccessories": true
}
},
"terms": {
"paymentTerms": "NET15",
"warranty": "36 months comprehensive",
"returnPolicy": "45 days full satisfaction guarantee",
"shippingTerms": "CIF",
"variantSpecificTerms": [
"Premium color finish guarantee",
"Extended testing and burn-in",
"White-glove delivery available"
]
},
"validFrom": "2024-01-01T00:00:00Z",
"minimumQuantity": 1,
"leadTime": 4,
"variantAttributes": [
{
"name": "RAM Size",
"value": "16GB Premium",
"impact": "Enhanced performance with premium memory modules"
},
{
"name": "Color",
"value": "Premium Silver",
"impact": "Enhanced finish with anti-fingerprint coating"
}
]
}
],
"totalElements": 2
}
Error Management
HTTP Error Codes and Handling
Error Code | Cause | System Action | User Message | Return Format |
---|---|---|---|---|
400 | Invalid variant identifier or parameters | Log validation error, return null | "Invalid variant information" | null |
401 | Authentication token missing/invalid | Trigger re-authentication flow | "Please log in to view variant pricing" | Authentication redirect |
403 | User lacks variant pricing permissions | Log access attempt, return null | "Variant pricing not accessible" | null |
404 | No offers found for variant | Log not found, return empty list | "No pricing available for this variant" | { success: true, offers: [], totalElements: 0 } |
412 | Precondition failed (business rules) | Log business rule violation | "Variant pricing restricted for your account" | null |
500 | Internal server error | Log server error, return null | "Unable to load variant pricing" | null |
Error Handling Example Code
// Global error handling in composable
const getProductVariantOffers = async ({
productIdentifier,
productIdType,
currency,
}: GetProductVariantOffersRequest): Promise<GetProductVariantOffersResponse | null> => {
try {
// Parameter validation
if (!productIdentifier?.trim()) {
console.error("Product variant identifier is required for offers lookup");
return null;
}
const { data, error } = await useFetch<GetProductVariantOffersResponse>(
`/api/product-variants/${productIdentifier}/offers`,
{
method: "GET",
params: {
productIdType,
currency,
},
}
);
if (error.value) {
console.error("Failed to fetch product variant offers:", {
productIdentifier,
productIdType,
currency,
error: error.value,
});
return null;
}
return data.value || null;
} catch (err) {
console.error(
"Unexpected error while fetching product variant offers:",
err
);
return null;
}
};
// Component-level error handling
const handleVariantOffersFetch = async (variantId: string) => {
try {
const response = await getProductVariantOffers({
productIdentifier: variantId,
productIdType: "VARIANT_SKU",
currency: userCurrency.value,
});
if (!response?.success || !response.offers) {
throw new Error("Variant offers not available");
}
// Process successful response
variantOffers.value = response.offers;
totalVariantOffers.value = response.totalElements;
} catch (error) {
// User notification
useToast().add({
title: "Variant Pricing Error",
description: "Unable to load pricing for selected variant",
color: "yellow",
});
// Fallback to empty state
variantOffers.value = [];
totalVariantOffers.value = 0;
}
};
Use Cases
1. Variant Selection Pricing
Display precise pricing when user selects specific product variant configurations.
Scenario: User changes product variant (color, size, specs) and needs to see updated pricing for that specific combination.
Parameters: { productIdentifier: selectedVariant.sku, productIdType: "VARIANT_SKU", currency: "EUR" }
Expected Outcome: Real-time pricing updates reflecting variant-specific costs and premiums.
2. Configuration Cost Impact
Show how different variant attributes affect pricing to help users make informed configuration choices.
Scenario: User compares pricing impact of different RAM sizes, colors, or storage options.
Parameters: { productIdentifier: variant.id, currency: userCurrency.value }
Expected Outcome: Detailed breakdown showing base price, attribute premiums, and total variant cost.
3. Inventory and Availability Check
Verify stock availability and lead times for specific variant configurations.
Scenario: User wants to check availability and delivery time for their exact variant selection.
Parameters: { productIdentifier: variantSku, productIdType: "VARIANT_SKU" }
Expected Outcome: Accurate stock levels, availability dates, and delivery estimates for the specific variant.
4. Procurement Optimization
Enable buyers to compare variant-specific pricing and terms for bulk purchasing decisions.
Scenario: Procurement team evaluates different variant options for enterprise purchasing to optimize cost and specifications.
Parameters: { productIdentifier: enterpriseVariant.sku, currency: "EUR" }
Expected Outcome: Detailed variant pricing with volume discounts, terms, and supplier-specific configurations.
Important Points
Performance Considerations
- Variant-Specific Caching: Cache offers by variant ID to avoid redundant API calls for the same configuration
- Attribute Impact Calculation: Client-side calculation of attribute pricing impact for responsive user experience
- Stock Status Updates: Real-time inventory updates for accurate variant availability information
- Price Comparison Optimization: Efficient loading when comparing multiple variants simultaneously
Security Aspects
- Variant Access Control: Verify user permissions for specific variant pricing and availability
- Configuration Validation: Ensure user can access requested variant combinations based on account restrictions
- Pricing Sensitivity: Protect premium variant pricing information based on user role and contracts
- Inventory Privacy: Filter stock information based on user's supplier relationships and agreements
Flexibility Features
- Attribute-Based Pricing: Support for complex pricing models based on multiple variant attributes
- Currency Adaptation: Automatic currency conversion for variant-specific pricing
- Supplier-Specific Variants: Handle cases where different suppliers offer different variant configurations
- Dynamic Pricing: Support for time-based pricing changes specific to certain variants
Integration Capabilities
- Cart Integration: Seamless addition of specific variants with accurate pricing to shopping cart
- Quote Generation: Direct integration with quote system for variant-specific bulk pricing requests
- Inventory Management: Real-time integration with inventory systems for accurate variant stock levels
- Configuration Tools: Integration with product configurators for dynamic variant pricing display
Technical Implementation
Composable Function with Complete JSDoc
/**
* Retrieves offers for a specific product variant
*
* @param params - Product variant offers request parameters
* @param params.productIdentifier - Variant identifier (SKU, ID, External ID)
* @param params.productIdType - Type of identifier used for variant lookup
* @param params.currency - Currency for pricing display
* @returns Promise resolving to variant offers response or null
*
* @example
* ```typescript
* const { getProductVariantOffers } = useProduct();
*
* const response = await getProductVariantOffers({
* productIdentifier: "LAPTOP-16GB-SILVER",
* productIdType: "VARIANT_SKU",
* currency: "EUR"
* });
*
* if (response?.success) {
* console.log('Variant offers found:', response.totalElements);
* response.offers.forEach(offer => {
* console.log(`${offer.supplierName}: €${offer.price.totalPrice} (Premium: €${offer.price.variantPremium})`);
* });
* }
* ```
*
* @throws {Error} When network request fails or invalid variant identifier provided
* @since 1.0.0
*/
const getProductVariantOffers = async ({
productIdentifier,
productIdType,
currency,
}: GetProductVariantOffersRequest): Promise<GetProductVariantOffersResponse | null> => {
try {
// Parameter validation
if (!productIdentifier?.trim()) {
throw new Error(
"Product variant identifier is required for offers lookup"
);
}
// Runtime configuration for defaults
const runtimeConfig = useRuntimeConfig();
const defaultCurrency = currency || runtimeConfig.public.currency;
const { data, error } = await useFetch<GetProductVariantOffersResponse>(
`/api/product-variants/${productIdentifier}/offers`,
{
method: "GET",
params: {
productIdType: productIdType || "EXTERNAL_ID",
currency: defaultCurrency,
},
// Enable caching with unique key
key: `variant-offers-${productIdentifier}-${defaultCurrency}`,
// Default response structure
default: () => ({
success: false,
offers: [],
totalElements: 0,
}),
}
);
if (error.value) {
console.error("Failed to fetch product variant offers:", {
productIdentifier,
productIdType,
currency: defaultCurrency,
error: error.value,
});
return null;
}
return data.value || null;
} catch (err) {
console.error(
"Unexpected error while fetching product variant offers:",
err
);
return null;
}
};
Execution Flow
Step-by-Step Process
-
Parameter Validation
// Validate required variant identifier if (!productIdentifier?.trim()) { throw new Error( "Product variant identifier is required for offers lookup" ); }
-
Configuration Setup
// Apply runtime defaults const runtimeConfig = useRuntimeConfig(); const effectiveCurrency = currency || runtimeConfig.public.currency; const effectiveIdType = productIdType || "EXTERNAL_ID";
-
Permission Verification
// Check variant pricing permissions const userStore = useUserStore(); const canViewVariantPricing = userStore.account?.permissions?.canViewVariants && userStore.account?.permissions?.canViewPricing;
-
Request Construction
// Build variant-specific API request const requestUrl = `/api/product-variants/${productIdentifier}/offers`; const requestParams = { productIdType: effectiveIdType, currency: effectiveCurrency, };
-
Network Request Execution
// Execute variant offers fetch const { data, error } = await useFetch<GetProductVariantOffersResponse>( requestUrl, { method: "GET", params: requestParams, } );
-
Response Processing
// Handle response and errors if (error.value) { logError("Failed to fetch variant offers", { productIdentifier, error: error.value, }); return null; }
-
Data Validation
// Validate variant offers response structure if (!data.value?.offers) { console.warn("No variant offers in response"); return { success: true, offers: [], totalElements: 0 }; }
-
Return Processed Response
// Return variant-specific offers data return { success: true, offers: data.value.offers, totalElements: data.value.totalElements, };
Updated about 2 months ago