Skip to content

Commit

Permalink
Working on email
Browse files Browse the repository at this point in the history
  • Loading branch information
stephanieg467 committed Nov 5, 2024
1 parent e3fc759 commit b0f80cd
Show file tree
Hide file tree
Showing 11 changed files with 1,184 additions and 152 deletions.
1 change: 1 addition & 0 deletions hooks/cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function useCart() {
export interface IUseCartItems extends ICartItem {
thcGrams?: number;
originalQty?: number;
total_price?: number;
}
export const useCartItems = () => {
const dispatch = useAppDispatch();
Expand Down
14 changes: 13 additions & 1 deletion lib/calculator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {ICartItem} from 'boundless-api-client';
import {ICartItem, IDetailedOrder} from 'boundless-api-client';
import currency from 'currency.js';
import {find} from 'lodash';
import _cloneDeep from 'lodash/cloneDeep';
Expand Down Expand Up @@ -89,6 +89,18 @@ export const calcTotalPrice = (
.toString();
};

export const itemsWeight = async (order: IDetailedOrder): Promise<number> => {
const weight = await order.items.reduce(async (accPromise, item) => {
const acc = await accPromise;
const product = await apiClient.catalog.getProduct(item.vwItem.product_id);
const weight = product.props.size?.weight ?? 0;
const product_weight = weight as number * item.qty;
return acc + product_weight;
}, Promise.resolve(0));

return weight;
};

interface ICalcTotalItem {
qty: number;
price: string | number;
Expand Down
60 changes: 36 additions & 24 deletions lib/canadaShippingRate.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,42 @@
import { XMLParser, XMLBuilder } from "fast-xml-parser";
import { XMLParser } from "fast-xml-parser";

export const canadaShippingRate = async (zip: string): Promise<any> => {
// @todo: should not have hardcoded customer number, weight and authorization
export const canadaShippingRate = async (zip: string, weight: number): Promise<any> => {
const XMLdata = `
<mailing-scenario xmlns=”http://www.canadapost.ca/ws/ship/rate-v4”>
<customer-number>0009861747</customer-number>
<mailing-scenario xmlns="http://www.canadapost.ca/ws/ship/rate-v3">
<customer-number>${process.env.CP_CUSTOMER_ID}</customer-number>
<services>
<service-code>DOM.RP</service-code>
</services>
<origin-postal-code>V2A5K6</origin-postal-code>
<parcel-characteristics><weight>1.0</weight></parcel-characteristics>
<destination><domestic><postal-code>${zip}</postal-code></domestic></destination>
<parcel-characteristics><weight>${weight}</weight></parcel-characteristics>
<destination><domestic><postal-code>${zip.trim().replace(/\s+/g, '').toUpperCase()}</postal-code></domestic></destination>
</mailing-scenario>`;
const parser = new XMLParser();
let result = parser.parse(XMLdata);
console.log(JSON.stringify(result, null,4));
const builder = new XMLBuilder();
const output = builder.build(result);
const rates = await fetch('https://soa-gw.canadapost.ca/rs/ship/price', {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/vnd.cpc.ship.rate-v4+xml',
'Accept': 'application/vnd.cpc.ship.rate-v4+xml',
'Authorization': 'Basic ' + btoa('c68ad9c01ff34064:4e5b13b80727ba8364f566'),
'Accept-language': 'en-CA'
},
body: output
})
// @todo: implement proper error handling and handle response
return rates

try {
const headers = new Headers();
headers.append("Accept", "application/vnd.cpc.ship.rate-v3+xml");
headers.append("Content-Type", "application/vnd.cpc.ship.rate-v3+xml");
if (process.env.CP_API_KEY) headers.append("Authorization", "Basic " + btoa(process.env.CP_API_KEY));
headers.append("Accept-language", "en-CA");

const requestOptions = {
method: "POST",
mode: "no-cors" as RequestMode,
headers: headers,
body: XMLdata
};

const resp = await fetch("https://soa-gw.canadapost.ca/rs/ship/price", requestOptions)
.then(async (response) => parser.parse(await response.text()))
.then((result) => {
return result
})
.catch((error) => console.error(error));
return resp;
} catch (error) {
console.error(error);
return null;
}

}
11 changes: 4 additions & 7 deletions lib/hostedPayPage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import axios from 'axios';
import {IOrder} from 'boundless-api-client';
import {isEmpty} from 'lodash';

interface RequestBody {
shipping_charge?: string | null;
Expand All @@ -17,8 +16,9 @@ interface RequestBody {
export const hostedPayPage = async (order: IOrder) => {
const total_price = order.total_price;
const tax_amount = order.tax_amount;
const service_total_price = order.service_total_price ? order.service_total_price : '0.00';
const requestBody: RequestBody = {
amount: Number(total_price) - Number(tax_amount),
amount: Number(total_price) - Number(service_total_price) - Number(tax_amount),
currency: 'CAD',
domain: process.env.HPP_DOMAIN,
tax: tax_amount,
Expand All @@ -32,13 +32,10 @@ export const hostedPayPage = async (order: IOrder) => {
first_name: order.customer?.first_name,
last_name: order.customer?.last_name,
email: order.customer?.email,
// telephone: 'telephone',
// shipping_address: JSON.stringify({address1: "1199 Spiller Rd",city:"P",province:"bc",country:"Canada",postalCode:"v2a8t3"}),
// billing_address: '{"address1": "1199 Spiller Rd","address2":"","city":"P","province":"bc","country":"Canada","postalCode":"v2a8t3"}',
};

if (!isEmpty(order.service_total_price) && order.service_total_price !== '0.00') {
requestBody.shipping_charge = order.service_total_price;
if (service_total_price && service_total_price !== '0.00') {
requestBody.shipping_charge = service_total_price;
}

// ********************************************************
Expand Down
15 changes: 9 additions & 6 deletions lib/updateShippingRate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@ import { IDetailedOrder } from "boundless-api-client";
import {apiClient} from './api';
import { IUpdateOrderRequest } from "boundless-api-client/dist/endpoints/adminOrder";
import { canadaShippingRate } from "./canadaShippingRate";
import { itemsWeight } from "./calculator";

function updateShippingRate(order: IDetailedOrder) {
const title = order?.services[0].serviceDelivery?.delivery?.title;
if (order && title === "Canada Post") {
async function updateShippingRate(order: IDetailedOrder): Promise<void> {
const title = order.services[0].serviceDelivery?.delivery?.title;
const weight = await itemsWeight(order);
if (title === "Canada Post") {
const zip = order.customer ? order.customer.addresses.find((address) => address.type === "shipping")?.zip : '';
const shippingRate = zip ? canadaShippingRate(zip) : null;
// @todo: will cp send shipping update email?
const shippingRate = zip ? await canadaShippingRate(zip, weight) : null;
if (shippingRate !== null) {
apiClient.adminOrder.updateOrder(order.id, {
await apiClient.adminOrder.updateOrder(order.id, {
delivery_id: 25,
delivery_rate: shippingRate,
delivery_rate: shippingRate['price-quotes']['price-quote']['price-details']['base'],
} as unknown as IUpdateOrderRequest);
}
}
Expand Down
Loading

0 comments on commit b0f80cd

Please sign in to comment.