Skip to content

Commit

Permalink
Merge pull request #648 from deco-cx/magento-feature/option-create-ca…
Browse files Browse the repository at this point in the history
…rt-when-adding-item

feat: adding option to create card to add item
  • Loading branch information
JonasJesus42 authored Jun 12, 2024
2 parents 8446ef4 + 610f433 commit 720b58a
Show file tree
Hide file tree
Showing 9 changed files with 163 additions and 104 deletions.
8 changes: 4 additions & 4 deletions magento/actions/cart/addCoupon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ export interface Props {
}

interface ErrorAddCoupon {
message: string;
status: number;
message: string;
status: number;
}

const action = async (
props: Props,
req: Request,
ctx: AppContext,
): Promise<Cart | ErrorAddCoupon> => {
): Promise<Cart | ErrorAddCoupon | null> => {
const { couponCode } = props;
const { clientAdmin } = ctx;
const cartId = getCartCookie(req.headers);
Expand All @@ -32,7 +32,7 @@ const action = async (
...await cart(undefined, req, ctx),
message: JSON.parse(error.message).message,
status: error.status,
}
};
}
return error;
}
Expand Down
38 changes: 29 additions & 9 deletions magento/actions/cart/addItem.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
import type { AppContext } from "../../mod.ts";
import cart, { Cart } from "../../loaders/cart.ts";
import { getCartCookie } from "../../utils/cart.ts";
import {
createCart,
getCartCookie,
postNewItem,
setCartCookie,
} from "../../utils/cart.ts";

export interface Props {
qty: number;
sku: string;
}

/**
* @title Magento Integration - Add item to cart
* @description Add item action
*/
const action = async (
props: Props,
req: Request,
ctx: AppContext,
): Promise<Cart> => {
): Promise<Cart | null> => {
const { qty, sku } = props;
const { clientAdmin } = ctx;
const { clientAdmin, cartConfigs } = ctx;
const { createCartOnAddItem } = cartConfigs;
const cartId = getCartCookie(req.headers);

const body = {
Expand All @@ -23,12 +34,21 @@ const action = async (
},
};

await clientAdmin["POST /rest/:site/V1/carts/:quoteId/items"]({
quoteId: cartId,
site: ctx.site,
}, { body });

return await cart(undefined, req, ctx);
try{
if (createCartOnAddItem && !cartId) {
const newCartId = (await createCart(ctx, req.headers)).id.toString()
if (!newCartId.length) return null;
body.cartItem.quote_id = newCartId;
await postNewItem(ctx.site, newCartId, body, clientAdmin);
setCartCookie(req.headers, newCartId);
return await cart(undefined, req, ctx);
}

await postNewItem(ctx.site, cartId, body, clientAdmin);
return await cart(undefined, req, ctx)
}catch(error){
throw error
};
};

export default action;
2 changes: 1 addition & 1 deletion magento/actions/cart/removeCoupon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const action = async (
_props: undefined,
req: Request,
ctx: AppContext,
): Promise<Cart> => {
): Promise<Cart | null> => {
const { clientAdmin } = ctx;
const cartId = getCartCookie(req.headers);

Expand Down
2 changes: 1 addition & 1 deletion magento/actions/cart/removeItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const action = async (
{ itemId }: Props,
req: Request,
ctx: AppContext,
): Promise<Cart> => {
): Promise<Cart | null> => {
const { clientAdmin, site } = ctx;
const cartId = getCartCookie(req.headers);

Expand Down
18 changes: 10 additions & 8 deletions magento/actions/cart/setSimulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,24 @@ const action = async (
props: Props,
req: Request,
ctx: AppContext,
): Promise<Cart> => {
): Promise<Cart | null> => {
const { clientAdmin, site } = ctx;

const id = getUserCookie(req.headers);
const cartId = getCartCookie(req.headers);

const { cart: cartResponse } = await clientAdmin["GET /:site/customer/section/load"]({
site,
sections: "cart",
}, { headers: new Headers({ Cookie: `${SESSION_COOKIE}=${id}` }) }).then((
res,
) => res.json());
const { cart: cartResponse } = await clientAdmin
["GET /:site/customer/section/load"]({
site,
sections: "cart",
}, { headers: new Headers({ Cookie: `${SESSION_COOKIE}=${id}` }) }).then((
res,
) => res.json());

const isLoggedIn = cartResponse?.minicart_improvements?.is_logged_in ?? false;
const quoteId = cartId ?? "";
const countryId = cartResponse?.minicart_improvements?.country_id ?? COUNTRY_ID;
const countryId = cartResponse?.minicart_improvements?.country_id ??
COUNTRY_ID;

clientAdmin
["POST /:site/rest/:site2/V1/digitalhub/set-shipping-to-quote"]({
Expand Down
2 changes: 1 addition & 1 deletion magento/actions/cart/updateItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const action = async (
props: Props,
req: Request,
ctx: AppContext,
): Promise<Cart> => {
): Promise<Cart | null> => {
const { qty, itemId, sku } = props;
const { clientAdmin } = ctx;
const cartId = getCartCookie(req.headers);
Expand Down
117 changes: 54 additions & 63 deletions magento/loaders/cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { API } from "../utils/client/client.ts";
import {
createCart,
getCartCookie,
setCartCookie,
toCartItemsWithImages,
} from "../utils/cart.ts";
import {
Expand All @@ -23,83 +22,75 @@ import {
export type Cart = API["GET /rest/:site/V1/carts/:cartId"]["response"];

/**
* @title Magento Integration
* @title Magento Integration - Cart
* @description Cart loader
*/
const loader = async (
_props: undefined,
req: Request,
ctx: AppContext
): Promise<Cart> => {
const { clientAdmin, site, imagesUrl } = ctx;
ctx: AppContext,
): Promise<Cart | null> => {
const { clientAdmin, site, imagesUrl, cartConfigs } = ctx;
const { countProductImageInCart, createCartOnAddItem } = cartConfigs;
const url = new URL(req.url);
const cartId = getCartCookie(req.headers);
const forceNewCart = true;

const getCart = async (cartId: string): Promise<Cart> => {
if (!cartId) {
const getCart = async (cartId: string): Promise<Cart | null> => {
if (!createCartOnAddItem && !cartId) {
return await createCart(ctx, req.headers);
} else {
try {
const [resultPricesCarts, resultCart] = await Promise.all([
clientAdmin["GET /rest/:site/V1/carts/:cartId/totals"]({
cartId,
site,
fields: [
GRAND_TOTAL,
SUBTOTAL,
DISCOUNT_AMOUNT,
BASE_DISCOUNT_AMOUNT,
SHIPPING_AMOUNT,
BASE_SHIPPING_AMOUNT,
SHIPPING_DISCOUNT_AMOUNT,
COUPON_CODE,
BASE_CURRENCY_CODE,
].join(","),
}),
clientAdmin["GET /rest/:site/V1/carts/:cartId"]({
cartId,
site,
}),
]);
}
if (createCartOnAddItem && !cartId) return null;
try {
const [resultPricesCarts, resultCart] = await Promise.all([
clientAdmin["GET /rest/:site/V1/carts/:cartId/totals"]({
cartId,
site,
fields: [
GRAND_TOTAL,
SUBTOTAL,
DISCOUNT_AMOUNT,
BASE_DISCOUNT_AMOUNT,
SHIPPING_AMOUNT,
BASE_SHIPPING_AMOUNT,
SHIPPING_DISCOUNT_AMOUNT,
COUPON_CODE,
BASE_CURRENCY_CODE,
].join(","),
}),
clientAdmin["GET /rest/:site/V1/carts/:cartId"]({
cartId,
site,
}),
]);

const cart = (await resultCart.json()) as Cart;
const prices = await resultPricesCarts.json();
const cart = await resultCart.json() as Cart;
const prices = await resultPricesCarts.json();

const productImagePromises = cart.items.map((item) => {
return clientAdmin["GET /rest/:site/V1/products/:sku"]({
sku: item.sku,
site,
fields: [
MEDIA_GALLERY_ENTRIES,
SKU,
"url",
"custom_attributes",
].join(","),
}).then((res) => res.json());
});
const productImages = await Promise.all(productImagePromises);
const productImagePromises = cart.items.map((item) => {
return clientAdmin["GET /rest/:site/V1/products/:sku"]({
sku: item.sku,
site,
fields: [MEDIA_GALLERY_ENTRIES, SKU, "url", "custom_attributes"]
.join(","),
}).then((res) => res.json());
});
const productImages = await Promise.all(productImagePromises);

return toCartItemsWithImages(
cart,
prices,
productImages,
imagesUrl,
url.origin,
site
) as unknown as Cart;
} catch (_error) {
return createCart(ctx, req.headers, forceNewCart);
}
return toCartItemsWithImages(
cart,
prices,
productImages,
imagesUrl,
url.origin,
site,
countProductImageInCart,
) as unknown as Cart;;
} catch (_error) {
return createCart(ctx, req.headers, forceNewCart);
}
};

const cartDetails = cartId ? await getCart(cartId) : await getCart("");

if (cartDetails.id && !cartId) {
setCartCookie(ctx.response.headers, cartDetails.id.toString());
}

return cartDetails;
return await getCart(cartId);
};
export default loader;
19 changes: 19 additions & 0 deletions magento/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,25 @@ export interface Props {
* @default true
*/
enableCache: boolean;

/**
* @title Cart Configs
*/
cartConfigs: CartConfigs;
}

interface CartConfigs {
/**
* @title Enable create Cart on add item fist time
* @default false
*/
createCartOnAddItem: boolean;

/**
* @title Count Product Image in Cart
* @default 1
*/
countProductImageInCart: number;
}

export interface State extends Props {
Expand Down
Loading

0 comments on commit 720b58a

Please sign in to comment.