Sample codes > Defining delivery dates
Defining delivery dates
As with any LLM AI model outputs, always verify the generated code for accuracy before deploying it live.
For the sample prompts here, your might get different responses since AI models have random elements.
AI Prompt:
Generate a shipping rate code for a standard shipping with $10 flat rate and express shipping with $20 flat rate.
The standard shipping is delivered between 4 to 8 business days; the express shipping between 2 to 3 business days.
Business days do not include weekends. Include the delivery dates in the rates.
Modify the description to show the maximum delivery date in the format "Estimated delivery before Tue, Nov1, 2023"
AI Output:
export async function calculateShippingRates(DATA, env) {
try {
// Helper function to add business days, excluding weekends
function addBusinessDays(startDate, numberOfDays) {
let currentDate = new Date(startDate);
while (numberOfDays > 0) {
currentDate = new Date(currentDate.setDate(currentDate.getDate() + 1));
// Exclude weekends
if (currentDate.getDay() !== 0 && currentDate.getDay() !== 6) {
numberOfDays--;
}
}
return currentDate;
}
// Function to format date
function formatDate(date) {
const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' };
return date.toLocaleDateString("en-US", options);
}
// Calculate delivery dates for standard and express shipping
const standardMinDeliveryDate = addBusinessDays(new Date(), 4);
const standardMaxDeliveryDate = addBusinessDays(new Date(), 8);
const expressMinDeliveryDate = addBusinessDays(new Date(), 2);
const expressMaxDeliveryDate = addBusinessDays(new Date(), 3);
// Prepare shipping rates
const rates = [
{
service_name: "Standard Shipping",
service_code: "STD_FLAT_RATE",
total_price: "1000", // $10 flat rate in cents
description: `Estimated delivery before ${formatDate(standardMaxDeliveryDate)}`,
currency: DATA.currency,
min_delivery_date: standardMinDeliveryDate.toISOString().split('T')[0],
max_delivery_date: standardMaxDeliveryDate.toISOString().split('T')[0]
},
{
service_name: "Express Shipping",
service_code: "EXP_FLAT_RATE",
total_price: "2000", // $20 flat rate in cents
description: `Estimated delivery before ${formatDate(expressMaxDeliveryDate)}`,
currency: DATA.currency,
min_delivery_date: expressMinDeliveryDate.toISOString().split('T')[0],
max_delivery_date: expressMaxDeliveryDate.toISOString().split('T')[0]
}
];
return { rates };
} catch (error) {
// Return error message in case of exceptions
return {
rates: [{
service_name: "Error",
service_code: "ERR",
total_price: null,
description: error.message,
currency: DATA.currency,
min_delivery_date: "",
max_delivery_date: ""
}]
};
}
}
How it appears at checkout page
Video demo
The following video demonstrates how to use JsRates GPT to generate the code.