Skip to content

Commit

Permalink
wip: magento cart authenticated
Browse files Browse the repository at this point in the history
  • Loading branch information
IncognitaDev committed Dec 19, 2024
1 parent 0e86a21 commit 35a3720
Show file tree
Hide file tree
Showing 5 changed files with 114 additions and 83 deletions.
29 changes: 23 additions & 6 deletions magento/loaders/cart.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { default as extend } from "../../website/loaders/extension.ts";
import { AppContext } from "../mod.ts";
import { handleCartImages } from "../utils/cache.ts";
import { getCartCookie, toCartItemsWithImages } from "../utils/cart.ts";
import { getCartCookie, setCartCookie, toCartItemsWithImages } from "../utils/cart.ts";
import { Cart as CartFromDeco } from "../utils/client/types.ts";
import {
BASE_CURRENCY_CODE,
Expand Down Expand Up @@ -34,15 +34,32 @@ const loader = async (
req: Request,
ctx: AppContext,
): Promise<Cart | null> => {
const { clientAdmin, site, cartConfigs } = ctx;
const { clientAdmin, site, cartConfigs, clientAdminAuthenticated } = ctx;
const { countProductImageInCart, extensions } = cartConfigs;
const url = new URL(req.url);
const cartId = _cartId ?? getCartCookie(req.headers);
let cartId = _cartId ?? getCartCookie(req.headers);

if (!cartId) {
return null;
}
// if (!cartId) {
// return null;
// }
try {
const headers = new Headers();
headers.append("Cookie", req.headers.get("Cookie") ?? "");
const cartAuthenticated = await clientAdminAuthenticated["GET /rest/:site/V1/carts/mine"]({
site,
}, {
headers
}).then((totalizers) => totalizers.json())

if(cartAuthenticated.id) {
console.log("cartAuthenticated", cartAuthenticated)
cartId = cartAuthenticated.id
setCartCookie(ctx.response.headers, cartId)
}
} catch (error) {
console.error("Error getting cart", error);
}

const [prices, cart] = await Promise.all([
clientAdmin["GET /rest/:site/V1/carts/:cartId/totals"]({
cartId,
Expand Down
8 changes: 8 additions & 0 deletions magento/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,13 @@ export default function App(props: Props): App<Manifest, State> {
}),
});

const clientAdminAuthenticated = createHttpClient<API>({
base: apiConfig.baseUrl,
headers: new Headers({
"x-requested-with": "XMLHttpRequest",
}),
});

const clientGraphql = createGraphqlClient({
fetcher: fetchSafe,
endpoint: `${apiConfig.baseUrl}/graphql`,
Expand All @@ -265,6 +272,7 @@ export default function App(props: Props): App<Manifest, State> {
cartConfigs,
clientAdmin,
clientGraphql,
clientAdminAuthenticated
},
middleware,
};
Expand Down
12 changes: 12 additions & 0 deletions magento/utils/cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
ProductWithImagesGraphQL,
} from "./clientGraphql/types.ts";
import { GetProductImages } from "./clientGraphql/queries.ts";
import { setCookie } from "@std/http/cookie";

export const CART_COOKIE = "dataservices_cart_id";

Expand Down Expand Up @@ -161,3 +162,14 @@ export async function getCartImages(
},
);
}


export const setCartCookie = (headers: Headers, cartId: string) => {
setCookie(headers, {
name: CART_COOKIE,
value: cartId,
path: "/",
httpOnly: false,
secure: false,
});
}
64 changes: 31 additions & 33 deletions wake/loaders/productDetailsPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export interface Props {
async function loader(
props: Props,
req: Request,
ctx: AppContext
ctx: AppContext,
): Promise<ProductDetailsPage | null> {
const url = new URL(req.url);
const { slug, buyTogether, includeSameParent } = props;
Expand Down Expand Up @@ -55,7 +55,7 @@ async function loader(
},
{
headers,
}
},
);

const buyListProducts = await Promise.all(
Expand All @@ -64,8 +64,8 @@ async function loader(

const { productId, includeSameParent, quantity } = buyListProduct;

const buyListProductPage =
await ctx.invoke.wake.loaders.productDetailsPage({
const buyListProductPage = await ctx.invoke.wake.loaders
.productDetailsPage({
// 'slug' its just to fit the parse function of loader
slug: `slug-${productId}`,
includeSameParent,
Expand All @@ -81,7 +81,7 @@ async function loader(
});

return buyListProductPage.product;
}) ?? []
}) ?? [],
).then((maybeProductList) =>
maybeProductList.filter((node): node is Product => Boolean(node))
);
Expand All @@ -100,7 +100,7 @@ async function loader(
},
{
headers,
}
},
);

const wakeProductOrBuyList = wakeProduct || wakeBuyList;
Expand All @@ -109,35 +109,34 @@ async function loader(
return null;
}

const variantsItems =
(await ctx.invoke.wake.loaders.productList({
first: MAXIMUM_REQUEST_QUANTITY,
sortDirection: "ASC",
sortKey: "RANDOM",
filters: { productId: [productId] },
})) ?? [];
const variantsItems = (await ctx.invoke.wake.loaders.productList({
first: MAXIMUM_REQUEST_QUANTITY,
sortDirection: "ASC",
sortKey: "RANDOM",
filters: { productId: [productId] },
})) ?? [];

const buyTogetherItens =
buyTogether && !!wakeProductOrBuyList.buyTogether?.length
? (await ctx.invoke.wake.loaders.productList({
first: MAXIMUM_REQUEST_QUANTITY,
sortDirection: "ASC",
sortKey: "RANDOM",
filters: {
productId: wakeProductOrBuyList.buyTogether?.map(
(bt) => bt!.productId
),
mainVariant: true,
},
getVariations: true,
})) ?? []
first: MAXIMUM_REQUEST_QUANTITY,
sortDirection: "ASC",
sortKey: "RANDOM",
filters: {
productId: wakeProductOrBuyList.buyTogether?.map(
(bt) => bt!.productId,
),
mainVariant: true,
},
getVariations: true,
})) ?? []
: [];

const product = toProduct(
wakeProductOrBuyList,
{ base: url },
variantsItems,
variantId
variantId,
);
return {
"@type": "ProductDetailsPage",
Expand All @@ -146,18 +145,17 @@ async function loader(
{
base: url,
},
product
product,
),
product: {
...product,
isAccessoryOrSparePartFor: buyListProducts,
isRelatedTo:
buyTogetherItens?.map((buyItem) => {
return {
...buyItem,
additionalType: "BuyTogether",
};
}) ?? [],
isRelatedTo: buyTogetherItens?.map((buyItem) => {
return {
...buyItem,
additionalType: "BuyTogether",
};
}) ?? [],
},
seo: {
canonical: product.isVariantOf?.url ?? "",
Expand Down
84 changes: 40 additions & 44 deletions wake/loaders/productListingPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,12 @@ const filtersFromParams = (searchParams: URLSearchParams) => {
const searchLoader = async (
props: Props,
req: Request,
ctx: AppContext
ctx: AppContext,
): Promise<ProductListingPage | null> => {
// get url from params
const url =
new URL(req.url).pathname === "/live/invoke"
? new URL(props.pageHref || req.headers.get("referer") || req.url)
: new URL(props.pageHref || req.url);
const url = new URL(req.url).pathname === "/live/invoke"
? new URL(props.pageHref || req.headers.get("referer") || req.url)
: new URL(props.pageHref || req.url);

const { storefront } = ctx;

Expand All @@ -166,13 +165,11 @@ const searchLoader = async (
const limit = Number(url.searchParams.get("tamanho") ?? props.limit ?? 12);

const filters = filtersFromParams(url.searchParams) ?? props.filters;
const sort =
(url.searchParams.get("sort") as SortValue | null) ??
const sort = (url.searchParams.get("sort") as SortValue | null) ??
(url.searchParams.get("ordenacao") as SortValue | null) ??
props.sort ??
"SALES:DESC";
const page =
props.page ??
const page = props.page ??
Number(url.searchParams.get("page")) ??
Number(url.searchParams.get("pagina")) ??
0;
Expand All @@ -181,35 +178,34 @@ const searchLoader = async (

const [sortKey, sortDirection] = sort.split(":") as [
ProductSortKeys,
SortDirection
SortDirection,
];

const onlyMainVariant = props.onlyMainVariant ?? true;
const [minimumPrice, maximumPrice] =
url.searchParams
.getAll("filtro")
?.find((i) => i.startsWith("precoPor"))
?.split(":")[1]
?.split(";")
.map(Number) ??
const [minimumPrice, maximumPrice] = url.searchParams
.getAll("filtro")
?.find((i) => i.startsWith("precoPor"))
?.split(":")[1]
?.split(";")
.map(Number) ??
url.searchParams.get("precoPor")?.split(";").map(Number) ??
[];

const offset = page <= 1 ? 0 : (page - 1) * limit;

const partnerData = partnerAlias
? await storefront.query<GetPartnersQuery, GetPartnersQueryVariables>(
{
variables: { first: 1, alias: [partnerAlias] },
...GetPartners,
},
{ headers }
)
{
variables: { first: 1, alias: [partnerAlias] },
...GetPartners,
},
{ headers },
)
: null;

const partnerAccessToken =
partnerData?.partners?.edges?.[0]?.node?.partnerAccessToken ??
partnerAccessTokenCookie;
partnerAccessTokenCookie;

if (partnerAccessToken) {
try {
Expand All @@ -230,7 +226,7 @@ const searchLoader = async (
},
{
headers,
}
},
);

const isHotsite = urlData.uri?.kind === "HOTSITE";
Expand All @@ -251,20 +247,20 @@ const searchLoader = async (

const data = isHotsite
? await storefront.query<HotsiteQuery, HotsiteQueryVariables>({
variables: {
...commonParams,
url: url.pathname,
},
...Hotsite,
})
variables: {
...commonParams,
url: url.pathname,
},
...Hotsite,
})
: await storefront.query<SearchQuery, SearchQueryVariables>({
variables: {
...commonParams,
query,
operation,
},
...Search,
});
variables: {
...commonParams,
query,
operation,
},
...Search,
});

const products = data?.result?.productsByOffset?.items ?? [];

Expand All @@ -273,7 +269,7 @@ const searchLoader = async (

const hasNextPage = Boolean(
(data?.result?.productsByOffset?.totalCount ?? 0) / limit >
(data?.result?.productsByOffset?.page ?? 0)
(data?.result?.productsByOffset?.page ?? 0),
);

const hasPreviousPage = page > 1;
Expand All @@ -300,16 +296,16 @@ const searchLoader = async (

const title = isHotsite
? (data as HotsiteQuery)?.result?.seo?.find((i) => i?.type === "TITLE")
?.content
?.content
: capitalize(query || "");
const description = isHotsite
? (data as HotsiteQuery)?.result?.seo?.find(
(i) => i?.name === "description"
)?.content
(i) => i?.name === "description",
)?.content
: capitalize(query || "");
const canonical = new URL(
isHotsite ? `/${(data as HotsiteQuery)?.result?.url}` : url,
url
url,
).href;

return {
Expand All @@ -333,7 +329,7 @@ const searchLoader = async (
?.filter((p): p is ProductFragment => Boolean(p))
.map((variant) => {
const productVariations = variations?.filter(
(v) => v.inProductGroupWithID === variant.productId
(v) => v.inProductGroupWithID === variant.productId,
);

return toProduct(variant, { base: url }, productVariations);
Expand Down

0 comments on commit 35a3720

Please sign in to comment.