Skip to content

Commit

Permalink
feat(Bookstore): use new Lulu shipping-options endpoint (#283)
Browse files Browse the repository at this point in the history
  • Loading branch information
ethanaturner committed Mar 21, 2024
1 parent 1a28b6d commit 1dd901c
Show file tree
Hide file tree
Showing 4 changed files with 118 additions and 64 deletions.
51 changes: 32 additions & 19 deletions API/bookstore.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,29 +149,47 @@ app.post(basePath + '/create-lulu-checkout-session', async (req, res) => {
const beta = req.query.beta;
let totalQuantity = 0;
const operatingCost = 0.16; // percent in decimal!!

//turn items into lineItems
let lineItems = shoppingCart;
let maxNumPages = 1;
let costCalculation = lineItems.map((item) => {
totalQuantity += item.quantity;
if (item.metadata.numPages > maxNumPages) {
maxNumPages = item.metadata.numPages;
}
return {
"page_count": item.metadata.numPages,
"pod_package_id": `0850X1100${item.color ? 'FC' : 'BW'}STD${item.hardcover ? 'CW' : 'PB'}060UW444MXX`,
"quantity": item.quantity
page_count: item.metadata.numPages,
pod_package_id: `0850X1100${item.color ? 'FC' : 'BW'}STD${item.hardcover ? 'CW' : 'PB'}060UW444MXX`,
quantity: item.quantity
}
});

//calculate shipping cost using Lulu API
let shipping;

const generateShippingOptionsRequest = (country, state_code) => fetch('https://api.lulu.com/shipping-options', {
method: 'POST',
body: JSON.stringify({
line_items: [{
page_count: maxNumPages,
pod_package_id: '0850X1100BWSTDCW060UW444MXX',
quantity: totalQuantity,
}],
shipping_address: {
country,
...(state_code && { state_code }),
}
}),
headers: {
'Content-Type': 'application/json'
}
});

switch (shippingLocation) {
default:
case "US": //United States
shipping = fetch(`https://api.lulu.com/print-shipping-options?iso_country_code=US&state_code=US-CA&quantity=${totalQuantity}&level=${shippingSpeed}&pod_package_id=0850X1100BWSTDCW060UW444MXX`, {
headers: {
// 'Cache-Control': 'no-cache',
'Content-Type': 'application/json'
}
});
shipping = generateShippingOptionsRequest('US', 'US-CA');
costCalculation = await LuluAPI('https://api.lulu.com/print-job-cost-calculations/', {
method: 'POST',
headers: {
Expand All @@ -193,12 +211,7 @@ app.post(basePath + '/create-lulu-checkout-session', async (req, res) => {
});
break;
case "CA": //Canada
shipping = fetch(`https://api.lulu.com/print-shipping-options?iso_country_code=CA&quantity=${totalQuantity}&level=${shippingSpeed}&pod_package_id=0850X1100BWSTDCW060UW444MXX`, {
headers: {
// 'Cache-Control': 'no-cache',
'Content-Type': 'application/json'
}
});
shipping = generateShippingOptionsRequest('CA');
costCalculation = await LuluAPI('https://api.lulu.com/print-job-cost-calculations/', {
method: 'POST',
headers: {
Expand Down Expand Up @@ -258,7 +271,7 @@ app.post(basePath + '/create-lulu-checkout-session', async (req, res) => {
})
/* Process shipping */
shipping = await (await shipping).json();
shipping = shipping.results[0];
shipping = shipping.find((s) => s.level === shippingSpeed);
lineItems.push({
price_data: {
currency: 'usd',
Expand All @@ -268,7 +281,7 @@ app.post(basePath + '/create-lulu-checkout-session', async (req, res) => {
},
unit_amount: Math.ceil(costCalculation.shipping_cost.total_cost_excl_tax * 100 * taxMultiplier) + (shippingSurcharge ? shippingSurcharge.price * 100 : 0) //amount in cents
},
description: `Estimated arrival in ${shipping.total_days_min}-${shipping.total_days_max} days. ${shippingSurcharge ? `Includes ${shippingSurcharge.name} surcharge` : ''}`,
description: `Estimated arrival in ${shipping?.total_days_min}-${shipping?.total_days_max} days. ${shippingSurcharge ? `Includes ${shippingSurcharge.name} surcharge` : ''}`,
quantity: 1,
});
/* Add Operating Cost */
Expand Down Expand Up @@ -557,7 +570,7 @@ async function LuluAPI(url, options, beta) {
const client = new ClientCredentials(config);
let accessToken;
try {
accessToken = await client.getToken();
accessToken = await client.getToken(undefined, { json: 'force' });
} catch (error) {
console.log('Access Token error', error);
}
Expand Down
2 changes: 1 addition & 1 deletion public/Henry Agnew/Bookstore/build/getOrderBundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -83304,7 +83304,7 @@ function GetOrder(props) {
width: "350",
height: "124"
}), /*#__PURE__*/_react["default"].createElement("p", null, /*#__PURE__*/_react["default"].createElement(_Tooltip["default"], {
title: "Version ".concat(new Date("Wed Sep 20 2023 21:24:29 GMT-0700 (Pacific Daylight Time)"))
title: "Version ".concat(new Date("Wed Mar 20 2024 21:17:49 GMT-0700 (Pacific Daylight Time)"))
}, /*#__PURE__*/_react["default"].createElement("span", null, " Coded with \u2764")))));
}
}
Expand Down
85 changes: 54 additions & 31 deletions public/Henry Agnew/Bookstore/build/standaloneBundle.js

Large diffs are not rendered by default.

44 changes: 31 additions & 13 deletions public/Henry Agnew/Bookstore/src/pages/BookstoreSingle.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,29 +129,47 @@ function BookstoreSingle(props) {
})();
}, []);

/**
* Update selected shipping speed if no longer available after quantity/options updates.
*/
useEffect(() => {
if (shippingData?.length) {
const foundSpeed = shippingData.find((s) => s.level === shippingSpeed);
const defaultSpeed = shippingData[shippingData.length - 1]?.level;
if (!foundSpeed && defaultSpeed !== shippingSpeed) {
setShippingSpeed(defaultSpeed);
}
}
}, [shippingData, shippingSpeed]);

useEffect(() => {
(async function () {
try {
let shipping;
setShippingData([]);
switch (shippingLocation) {
case "CA":
shipping = 'iso_country_code=CA';
break;
case "US":
default:
shipping = 'iso_country_code=US&state_code=US-CA';
}
shipping = await fetch(`https://api.lulu.com/print-shipping-options?${shipping}&quantity=${quantity}&pod_package_id=0850X1100BWSTDCW060UW444MXX`, {
let shipping = await fetch('https://api.lulu.com/shipping-options', {
method: 'POST',
body: JSON.stringify({
line_items: [{
page_count: props.item.numPages,
pod_package_id: '0850X1100BWSTDCW060UW444MXX',
quantity,
}],
shipping_address: {
country: shippingLocation,
...(shippingLocation === 'US' && { state_code: 'US-CA' }),
},
}),
headers: {
// 'Cache-Control': 'no-cache',
'Content-Type': 'application/json'
}
});
shipping = await shipping.json()
shipping = shipping.results.sort((a, b) => b.cost_excl_tax - a.cost_excl_tax);
setShippingData(shipping);
setShippingSurcharge(false);
if (Array.isArray(shipping)) {
shipping.sort((a, b) => b.cost_excl_tax - a.cost_excl_tax);
setShippingData(shipping);
setShippingSurcharge(false);
}
} catch (e) {
console.error(e)
}
Expand Down

0 comments on commit 1dd901c

Please sign in to comment.