From 35a3720760ebe07c4bb51673e7d8c128b76c1237 Mon Sep 17 00:00:00 2001 From: Luis Sousa Date: Thu, 19 Dec 2024 08:46:35 -0300 Subject: [PATCH] wip: magento cart authenticated --- magento/loaders/cart.ts | 29 ++++++++--- magento/mod.ts | 8 +++ magento/utils/cart.ts | 12 +++++ wake/loaders/productDetailsPage.ts | 64 +++++++++++------------ wake/loaders/productListingPage.ts | 84 ++++++++++++++---------------- 5 files changed, 114 insertions(+), 83 deletions(-) diff --git a/magento/loaders/cart.ts b/magento/loaders/cart.ts index c8e49dff6..a55671a91 100644 --- a/magento/loaders/cart.ts +++ b/magento/loaders/cart.ts @@ -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, @@ -34,15 +34,32 @@ const loader = async ( req: Request, ctx: AppContext, ): Promise => { - 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, diff --git a/magento/mod.ts b/magento/mod.ts index 18f284014..698415b27 100644 --- a/magento/mod.ts +++ b/magento/mod.ts @@ -245,6 +245,13 @@ export default function App(props: Props): App { }), }); + const clientAdminAuthenticated = createHttpClient({ + base: apiConfig.baseUrl, + headers: new Headers({ + "x-requested-with": "XMLHttpRequest", + }), + }); + const clientGraphql = createGraphqlClient({ fetcher: fetchSafe, endpoint: `${apiConfig.baseUrl}/graphql`, @@ -265,6 +272,7 @@ export default function App(props: Props): App { cartConfigs, clientAdmin, clientGraphql, + clientAdminAuthenticated }, middleware, }; diff --git a/magento/utils/cart.ts b/magento/utils/cart.ts index 366fe7ff4..84d6882ea 100644 --- a/magento/utils/cart.ts +++ b/magento/utils/cart.ts @@ -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"; @@ -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, + }); +} diff --git a/wake/loaders/productDetailsPage.ts b/wake/loaders/productDetailsPage.ts index f88e97e93..03167d7a6 100644 --- a/wake/loaders/productDetailsPage.ts +++ b/wake/loaders/productDetailsPage.ts @@ -26,7 +26,7 @@ export interface Props { async function loader( props: Props, req: Request, - ctx: AppContext + ctx: AppContext, ): Promise { const url = new URL(req.url); const { slug, buyTogether, includeSameParent } = props; @@ -55,7 +55,7 @@ async function loader( }, { headers, - } + }, ); const buyListProducts = await Promise.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, @@ -81,7 +81,7 @@ async function loader( }); return buyListProductPage.product; - }) ?? [] + }) ?? [], ).then((maybeProductList) => maybeProductList.filter((node): node is Product => Boolean(node)) ); @@ -100,7 +100,7 @@ async function loader( }, { headers, - } + }, ); const wakeProductOrBuyList = wakeProduct || wakeBuyList; @@ -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", @@ -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 ?? "", diff --git a/wake/loaders/productListingPage.ts b/wake/loaders/productListingPage.ts index 2c9061f5c..2a5a9bd25 100644 --- a/wake/loaders/productListingPage.ts +++ b/wake/loaders/productListingPage.ts @@ -147,13 +147,12 @@ const filtersFromParams = (searchParams: URLSearchParams) => { const searchLoader = async ( props: Props, req: Request, - ctx: AppContext + ctx: AppContext, ): Promise => { // 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; @@ -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; @@ -181,17 +178,16 @@ 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) ?? []; @@ -199,17 +195,17 @@ const searchLoader = async ( const partnerData = partnerAlias ? await storefront.query( - { - 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 { @@ -230,7 +226,7 @@ const searchLoader = async ( }, { headers, - } + }, ); const isHotsite = urlData.uri?.kind === "HOTSITE"; @@ -251,20 +247,20 @@ const searchLoader = async ( const data = isHotsite ? await storefront.query({ - variables: { - ...commonParams, - url: url.pathname, - }, - ...Hotsite, - }) + variables: { + ...commonParams, + url: url.pathname, + }, + ...Hotsite, + }) : await storefront.query({ - variables: { - ...commonParams, - query, - operation, - }, - ...Search, - }); + variables: { + ...commonParams, + query, + operation, + }, + ...Search, + }); const products = data?.result?.productsByOffset?.items ?? []; @@ -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; @@ -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 { @@ -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);