From 5c70c8be25d775e63a81778bb18f936dcfb8758b Mon Sep 17 00:00:00 2001 From: lytrankieio123 Date: Thu, 30 Sep 2021 17:50:35 +0700 Subject: [PATCH 1/5] :sparkles: feat: get all facets :%s --- framework/vendure/schema.d.ts | 45 +++++++++++++++++++ .../utils/queries/get-all-facets-query.ts | 17 +++++++ pages/product/[slug].tsx | 1 + pages/test.tsx | 34 +++++++++++--- src/components/hooks/facets/index.ts | 3 ++ src/components/hooks/facets/useFacets.tsx | 12 +++++ 6 files changed, 107 insertions(+), 5 deletions(-) create mode 100644 framework/vendure/utils/queries/get-all-facets-query.ts create mode 100644 src/components/hooks/facets/index.ts create mode 100644 src/components/hooks/facets/useFacets.tsx diff --git a/framework/vendure/schema.d.ts b/framework/vendure/schema.d.ts index b0b0170d7..3922f679b 100644 --- a/framework/vendure/schema.d.ts +++ b/framework/vendure/schema.d.ts @@ -93,6 +93,10 @@ export type QueryProductsArgs = { options?: Maybe } +export type QueryFacetsArgs = { + options?: Maybe +} + export type QuerySearchArgs = { input: SearchInput } @@ -2727,6 +2731,13 @@ export type ProductListOptions = { filter?: Maybe } +export type FacetListOptions = { + skip?: Maybe + take?: Maybe + sort?: Maybe + filter?: Maybe +} + export type UpdateOrderItemsResult = | Order | OrderModificationError @@ -2884,6 +2895,23 @@ export type ProductVariantSortParameter = { discountPrice?: Maybe } + +export type FacetFilterParameter = { + createdAt?: Maybe + updatedAt?: Maybe + languageCode?: Maybe + name?: Maybe + code?: Maybe +} + +export type FacetSortParameter = { + id?: Maybe + createdAt?: Maybe + updatedAt?: Maybe + name?: Maybe + code?: Maybe +} + export type CustomerFilterParameter = { createdAt?: Maybe updatedAt?: Maybe @@ -3192,6 +3220,23 @@ export type GetAllProductsQuery = { __typename?: 'Query' } & { } } +export type GetAllFacetsQuery = { __typename?: 'Query' } & { + facets: { __typename?: 'FacetList' } & { + items: Array< + { __typename?: 'Facet' } & Pick< + Facet, + 'id' | 'name' | 'code' + > & { + parent?: Maybe<{ __typename?: 'Facet' } & Pick> + children?: Maybe< + Array<{ __typename?: 'Facet' } & Pick> + > + } + >, + 'totalItems' + } +} + export type ActiveOrderQueryVariables = Exact<{ [key: string]: never }> export type ActiveOrderQuery = { __typename?: 'Query' } & { diff --git a/framework/vendure/utils/queries/get-all-facets-query.ts b/framework/vendure/utils/queries/get-all-facets-query.ts new file mode 100644 index 000000000..906507c69 --- /dev/null +++ b/framework/vendure/utils/queries/get-all-facets-query.ts @@ -0,0 +1,17 @@ +export const getAllFacetsQuery = /* GraphQL */ ` +query facets ($options: FacetListOptions) { + facets (options: $options){ + totalItems, + items { + id + name + code + values { + id + name + code + } + } + } +} +` diff --git a/pages/product/[slug].tsx b/pages/product/[slug].tsx index ab9a1c17c..a8e925df9 100644 --- a/pages/product/[slug].tsx +++ b/pages/product/[slug].tsx @@ -4,6 +4,7 @@ import { ProductInfoDetail, ReleventProducts, ViewedProducts } from 'src/compone import { BLOGS_DATA_TEST, INGREDIENT_DATA_TEST, RECIPE_DATA_TEST } from 'src/utils/demo-data' export default function Slug() { + return <> diff --git a/pages/test.tsx b/pages/test.tsx index b60fe63c7..452b42173 100644 --- a/pages/test.tsx +++ b/pages/test.tsx @@ -1,16 +1,40 @@ +import { QueryFacetsArgs } from '@framework/schema' +import { useMemo, useState } from 'react' import { Layout } from 'src/components/common' -import { useMessage } from 'src/components/contexts' +import { useFacets } from 'src/components/hooks/facets' export default function Test() { - const { showMessageError } = useMessage() + const [keyword, setKeyword] = useState('c') - const handleClick = () => { - showMessageError("Create account successfully") + const optionsFilter = useMemo(() => { + console.log("change options") + return { + options: { + filter: { + name: { + contains: keyword + } + } + } + } as QueryFacetsArgs + }, [keyword]) + + const { items, totalItems } = useFacets(optionsFilter) + + const changeQuery = () => { + setKeyword('ca') } return ( <> - +
Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore, praesentium.
+
+ total: {totalItems} +
+
+ ITEMS: {JSON.stringify(items)} +
+ ) } diff --git a/src/components/hooks/facets/index.ts b/src/components/hooks/facets/index.ts new file mode 100644 index 000000000..f039373e3 --- /dev/null +++ b/src/components/hooks/facets/index.ts @@ -0,0 +1,3 @@ +export { default as useFacets } from './useFacets' + + diff --git a/src/components/hooks/facets/useFacets.tsx b/src/components/hooks/facets/useFacets.tsx new file mode 100644 index 000000000..59d5485ec --- /dev/null +++ b/src/components/hooks/facets/useFacets.tsx @@ -0,0 +1,12 @@ +import { GetAllFacetsQuery, QueryFacetsArgs } from '@framework/schema' +import { getAllFacetsQuery } from '@framework/utils/queries/get-all-facets-query' +import gglFetcher from 'src/utils/gglFetcher' +import useSWR from 'swr' + +const useFacets = (options: QueryFacetsArgs) => { + const { data, isValidating, ...rest } = useSWR([getAllFacetsQuery, options], gglFetcher) + console.log("here", data) + return { items: data?.facets.items, totalItems: data?.facets.totalItems, loading: isValidating, ...rest } +} + +export default useFacets From 8f290f94f66036951fae40ce5c5abb9a1314a31e Mon Sep 17 00:00:00 2001 From: lytrankieio123 Date: Fri, 1 Oct 2021 09:19:34 +0700 Subject: [PATCH 2/5] :fire: remove: log :%s --- src/components/hooks/facets/useFacets.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/components/hooks/facets/useFacets.tsx b/src/components/hooks/facets/useFacets.tsx index 59d5485ec..94630b868 100644 --- a/src/components/hooks/facets/useFacets.tsx +++ b/src/components/hooks/facets/useFacets.tsx @@ -5,7 +5,6 @@ import useSWR from 'swr' const useFacets = (options: QueryFacetsArgs) => { const { data, isValidating, ...rest } = useSWR([getAllFacetsQuery, options], gglFetcher) - console.log("here", data) return { items: data?.facets.items, totalItems: data?.facets.totalItems, loading: isValidating, ...rest } } From 21b0200205e816332de845ae7d7fe2ac33966b6c Mon Sep 17 00:00:00 2001 From: lytrankieio123 Date: Mon, 4 Oct 2021 11:14:38 +0700 Subject: [PATCH 3/5] :raising_hand: test getStaticProps with revalidate --- pages/index.tsx | 51 ++++++++++++++++++++++++++++--- pages/test.tsx | 79 +++++++++++++++++++++++++++---------------------- 2 files changed, 91 insertions(+), 39 deletions(-) diff --git a/pages/index.tsx b/pages/index.tsx index 3fa86079d..aabbb1f94 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -1,19 +1,29 @@ +import commerce from '@lib/api/commerce'; +import { GetStaticPropsContext } from 'next'; import { Layout } from 'src/components/common'; import { FeaturedProductsCarousel, HomeBanner, HomeCategories, HomeCollection, HomeCTA, HomeFeature, HomeRecipe, HomeSubscribe, HomeVideo } from 'src/components/modules/home'; import HomeSpice from 'src/components/modules/home/HomeSpice/HomeSpice'; -export default function Home() { +interface Props { + products: any +} +export default function Home({ products }: Props) { return ( <> +

+ TOTAL: {products?.length} +

+ + {JSON.stringify(products[0])} - - + + - + {/* // todo: uncomment @@ -22,4 +32,37 @@ export default function Home() { ) } + +export async function getStaticProps({ + preview, + locale, + locales, +}: GetStaticPropsContext) { + const config = { locale, locales } + const productsPromise = commerce.getAllProducts({ + // const productsPromise = commerce.getAllFacets({ + variables: { + first: 70, + // filter: { + // name: { + // contains: 'ca' + // } + // } + }, + config, + preview, + // Saleor provider only + ...({ featured: true } as any), + }) + + const { products } = await productsPromise + + + return { + props: { products }, + revalidate: 20, + } +} + + Home.Layout = Layout diff --git a/pages/test.tsx b/pages/test.tsx index 452b42173..6244c3dd6 100644 --- a/pages/test.tsx +++ b/pages/test.tsx @@ -1,42 +1,51 @@ -import { QueryFacetsArgs } from '@framework/schema' -import { useMemo, useState } from 'react' -import { Layout } from 'src/components/common' -import { useFacets } from 'src/components/hooks/facets' - -export default function Test() { - const [keyword, setKeyword] = useState('c') - - const optionsFilter = useMemo(() => { - console.log("change options") - return { - options: { - filter: { - name: { - contains: keyword - } - } - } - } as QueryFacetsArgs - }, [keyword]) - - const { items, totalItems } = useFacets(optionsFilter) - - const changeQuery = () => { - setKeyword('ca') - } +import commerce from '@lib/api/commerce'; +import { GetStaticPropsContext } from 'next'; +import { Layout } from 'src/components/common'; +interface Props { + products: any +} +export default function Home({ products }: Props) { return ( <> -
Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore, praesentium.
-
- total: {totalItems} -
-
- ITEMS: {JSON.stringify(items)} -
- +

+ TOTAL: {products?.length} +

+ {JSON.stringify(products[0])} ) } -Test.Layout = Layout + +export async function getServerSideProps({ + preview, + locale, + locales, +}: GetStaticPropsContext) { + const config = { locale, locales } + const productsPromise = commerce.getAllProducts({ + // const productsPromise = commerce.getAllFacets({ + variables: { + first: 70, + // filter: { + // name: { + // contains: 'ca' + // } + // } + }, + config, + preview, + // Saleor provider only + ...({ featured: true } as any), + }) + + const { products } = await productsPromise + + + return { + props: { products }, + } +} + + +Home.Layout = Layout From 6b7b8e4ad154f22c715ae7af541a6b289f16efe0 Mon Sep 17 00:00:00 2001 From: lytrankieio123 Date: Mon, 4 Oct 2021 11:17:30 +0700 Subject: [PATCH 4/5] :raising_hand: test getStaticProps with revalidate --- framework/commerce/api/operations.ts | 18 ++++ framework/commerce/types/facet.ts | 85 +++++++++++++++++++ framework/vendure/api/index.ts | 16 ++-- .../vendure/api/operations/get-all-facets.ts | 46 ++++++++++ pages/index.tsx | 2 +- src/components/hooks/facets/useFacets.tsx | 2 +- 6 files changed, 160 insertions(+), 9 deletions(-) create mode 100644 framework/commerce/types/facet.ts create mode 100644 framework/vendure/api/operations/get-all-facets.ts diff --git a/framework/commerce/api/operations.ts b/framework/commerce/api/operations.ts index 2910a2d82..8e5137c40 100644 --- a/framework/commerce/api/operations.ts +++ b/framework/commerce/api/operations.ts @@ -23,6 +23,8 @@ export const OPERATIONS = [ 'getAllProductPaths', 'getAllProducts', 'getProduct', + 'getAllFacets', + ] as const export const defaultOperations = OPERATIONS.reduce((ops, k) => { @@ -156,6 +158,22 @@ export type Operations

= { } } +// getAllFacets: { +// (opts: { +// variables?: T['variables'] +// config?: P['config'] +// preview?: boolean +// }): Promise + +// ( +// opts: { +// variables?: T['variables'] +// config?: P['config'] +// preview?: boolean +// } & OperationOptions +// ): Promise +// } + export type APIOperations

= { [K in keyof Operations

]?: (ctx: OperationContext

) => Operations

[K] } diff --git a/framework/commerce/types/facet.ts b/framework/commerce/types/facet.ts new file mode 100644 index 000000000..d1ae5b382 --- /dev/null +++ b/framework/commerce/types/facet.ts @@ -0,0 +1,85 @@ + +export type FacetOption = { + __typename?: 'MultipleChoiceOption' + id: string + displayName: string + values: FacetOptionValues[] +} + +export type FacetOptionValues = { + label: string + hexColors?: string[] +} + +export type FacetVariant = { + id: string | number + options: FacetOption[] + availableForSale?: boolean +} + +export type Facet = { + id: string + name: string + description: string + descriptionHtml?: string + sku?: string + slug?: string + path?: string + images: FacetImage[] + variants: FacetVariant[] + price: FacetPrice + options: FacetOption[] +} + +export type SearchFacetsBody = { + search?: string + categoryId?: string | number + brandId?: string | number + sort?: string + locale?: string +} + +export type FacetTypes = { + facet: Facet + searchBody: SearchFacetsBody +} + +export type SearchFacetsHook = { + data: { + facets: T['facet'][] + found: boolean + } + body: T['searchBody'] + input: T['searchBody'] + fetcherInput: T['searchBody'] +} + +export type FacetsSchema = { + endpoint: { + options: {} + handlers: { + getFacets: SearchFacetsHook + } + } +} + +export type GetAllFacetPathsOperation< + T extends FacetTypes = FacetTypes +> = { + data: { facets: Pick[] } + variables: { first?: number } +} + +export type GetAllFacetsOperation = { + data: { facets: T['facet'][] } + variables: { + relevance?: 'featured' | 'best_selling' | 'newest' + ids?: string[] + first?: number + } +} + +export type GetFacetOperation = { + data: { facet?: T['facet'] } + variables: { path: string; slug?: never } | { path?: never; slug: string } +} diff --git a/framework/vendure/api/index.ts b/framework/vendure/api/index.ts index 6762ee6aa..7e49d6c1f 100644 --- a/framework/vendure/api/index.ts +++ b/framework/vendure/api/index.ts @@ -1,15 +1,16 @@ -import type { APIProvider, CommerceAPIConfig } from '@commerce/api' +import type { CommerceAPIConfig } from '@commerce/api' import { CommerceAPI, getCommerceApi as commerceApi } from '@commerce/api' -import fetchGraphqlApi from './utils/fetch-graphql-api' - -import login from './operations/login' +import getAllFacets from './operations/get-all-facets' import getAllPages from './operations/get-all-pages' -import getPage from './operations/get-page' -import getSiteInfo from './operations/get-site-info' -import getCustomerWishlist from './operations/get-customer-wishlist' import getAllProductPaths from './operations/get-all-product-paths' import getAllProducts from './operations/get-all-products' +import getCustomerWishlist from './operations/get-customer-wishlist' +import getPage from './operations/get-page' import getProduct from './operations/get-product' +import getSiteInfo from './operations/get-site-info' +import login from './operations/login' +import fetchGraphqlApi from './utils/fetch-graphql-api' + export interface VendureConfig extends CommerceAPIConfig {} @@ -40,6 +41,7 @@ const operations = { getAllProductPaths, getAllProducts, getProduct, + getAllFacets, } export const provider = { config, operations } diff --git a/framework/vendure/api/operations/get-all-facets.ts b/framework/vendure/api/operations/get-all-facets.ts new file mode 100644 index 000000000..9187525d3 --- /dev/null +++ b/framework/vendure/api/operations/get-all-facets.ts @@ -0,0 +1,46 @@ +import { Facet } from '@commerce/types/facet' +import { Provider, VendureConfig } from '../' +import { GetAllFacetsQuery } from '../../schema' +import { normalizeSearchResult } from '../../utils/normalize' +import { getAllFacetsQuery } from '../../utils/queries/get-all-facets-query' +import { OperationContext } from '@commerce/api/operations' + +export type FacetVariables = { first?: number } + +export default function getAllFacetsOperation({ + commerce, +}: OperationContext) { + async function getAllFacets(opts?: { + variables?: FacetVariables + config?: Partial + preview?: boolean + }): Promise<{ facets: Facet[] }> + + async function getAllFacets({ + query = getAllFacetsQuery, + variables: { ...vars } = {}, + config: cfg, + }: { + query?: string + variables?: FacetVariables + config?: Partial + preview?: boolean + } = {}): Promise<{ facets: Facet[] | any[] }> { + const config = commerce.getConfig(cfg) + const variables = { + input: { + take: vars.first, + groupByFacet: true, + }, + } + const { data } = await config.fetch(query, { + variables, + }) + + return { + facets: data.search.items.map((item) => normalizeSearchResult(item)), + } + } + + return getAllFacets +} diff --git a/pages/index.tsx b/pages/index.tsx index aabbb1f94..371922e59 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -60,7 +60,7 @@ export async function getStaticProps({ return { props: { products }, - revalidate: 20, + revalidate: 60, } } diff --git a/src/components/hooks/facets/useFacets.tsx b/src/components/hooks/facets/useFacets.tsx index 94630b868..c9a4e85ab 100644 --- a/src/components/hooks/facets/useFacets.tsx +++ b/src/components/hooks/facets/useFacets.tsx @@ -3,7 +3,7 @@ import { getAllFacetsQuery } from '@framework/utils/queries/get-all-facets-query import gglFetcher from 'src/utils/gglFetcher' import useSWR from 'swr' -const useFacets = (options: QueryFacetsArgs) => { +const useFacets = (options?: QueryFacetsArgs) => { const { data, isValidating, ...rest } = useSWR([getAllFacetsQuery, options], gglFetcher) return { items: data?.facets.items, totalItems: data?.facets.totalItems, loading: isValidating, ...rest } } From 77a0432d0745e53f891335f5f377550099370c47 Mon Sep 17 00:00:00 2001 From: lytrankieio123 Date: Mon, 4 Oct 2021 14:16:32 +0700 Subject: [PATCH 5/5] :sparkles: feat: feat fresh and featured products :%s --- framework/commerce/api/operations.ts | 34 ++-- framework/commerce/new-provider.md | 1 + framework/commerce/types/facet.ts | 41 +---- framework/commerce/types/product.ts | 24 ++- .../vendure/api/operations/get-all-facets.ts | 5 +- .../api/operations/get-all-products.ts | 3 +- framework/vendure/schema.d.ts | 4 +- framework/vendure/utils/normalize.ts | 6 +- pages/index.tsx | 66 +++++--- .../home/FreshProducts/FreshProducts.tsx | 148 ++++++++++++++++++ src/components/modules/home/index.ts | 1 + src/utils/constanst.utils.ts | 11 +- src/utils/funtion.utils.ts | 32 +++- 13 files changed, 280 insertions(+), 96 deletions(-) create mode 100644 src/components/modules/home/FreshProducts/FreshProducts.tsx diff --git a/framework/commerce/api/operations.ts b/framework/commerce/api/operations.ts index 8e5137c40..342d6bbc9 100644 --- a/framework/commerce/api/operations.ts +++ b/framework/commerce/api/operations.ts @@ -1,3 +1,4 @@ +import { GetAllFacetsOperation } from './../types/facet'; import type { ServerResponse } from 'http' import type { LoginOperation } from '../types/login' import type { GetAllPagesOperation, GetPageOperation } from '../types/page' @@ -156,23 +157,26 @@ export type Operations

= { } & OperationOptions ): Promise } + + getAllFacets: { + (opts: { + variables?: T['variables'] + config?: P['config'] + preview?: boolean + }): Promise + + ( + opts: { + variables?: T['variables'] + config?: P['config'] + preview?: boolean + } & OperationOptions + ): Promise + } + + } -// getAllFacets: { -// (opts: { -// variables?: T['variables'] -// config?: P['config'] -// preview?: boolean -// }): Promise - -// ( -// opts: { -// variables?: T['variables'] -// config?: P['config'] -// preview?: boolean -// } & OperationOptions -// ): Promise -// } export type APIOperations

= { [K in keyof Operations

]?: (ctx: OperationContext

) => Operations

[K] diff --git a/framework/commerce/new-provider.md b/framework/commerce/new-provider.md index 8c2feeab2..a48e6961b 100644 --- a/framework/commerce/new-provider.md +++ b/framework/commerce/new-provider.md @@ -15,6 +15,7 @@ Adding a commerce provider means adding a new folder in `framework` with a folde - useSearch - getProduct - getAllProducts + - getAllFacets - `wishlist` - useWishlist - useAddItem diff --git a/framework/commerce/types/facet.ts b/framework/commerce/types/facet.ts index d1ae5b382..adfe1e061 100644 --- a/framework/commerce/types/facet.ts +++ b/framework/commerce/types/facet.ts @@ -1,40 +1,14 @@ - -export type FacetOption = { - __typename?: 'MultipleChoiceOption' - id: string - displayName: string - values: FacetOptionValues[] -} - -export type FacetOptionValues = { - label: string - hexColors?: string[] -} - -export type FacetVariant = { - id: string | number - options: FacetOption[] - availableForSale?: boolean -} +import { FacetValue } from './../../vendure/schema.d'; export type Facet = { id: string name: string - description: string - descriptionHtml?: string - sku?: string - slug?: string - path?: string - images: FacetImage[] - variants: FacetVariant[] - price: FacetPrice - options: FacetOption[] + code: string + values: FacetValue[] } export type SearchFacetsBody = { search?: string - categoryId?: string | number - brandId?: string | number sort?: string locale?: string } @@ -63,17 +37,10 @@ export type FacetsSchema = { } } -export type GetAllFacetPathsOperation< - T extends FacetTypes = FacetTypes -> = { - data: { facets: Pick[] } - variables: { first?: number } -} export type GetAllFacetsOperation = { data: { facets: T['facet'][] } variables: { - relevance?: 'featured' | 'best_selling' | 'newest' ids?: string[] first?: number } @@ -81,5 +48,5 @@ export type GetAllFacetsOperation = { export type GetFacetOperation = { data: { facet?: T['facet'] } - variables: { path: string; slug?: never } | { path?: never; slug: string } + variables: { code: string; } | { code?: never; } } diff --git a/framework/commerce/types/product.ts b/framework/commerce/types/product.ts index 6a68d8ad1..fec48a63d 100644 --- a/framework/commerce/types/product.ts +++ b/framework/commerce/types/product.ts @@ -1,3 +1,5 @@ +import { FacetValueFilterInput, LogicalOperator, SearchResultSortParameter } from "@framework/schema" + export type ProductImage = { url: string alt?: string @@ -40,7 +42,6 @@ export type Product = { slug?: string path?: string images: ProductImage[] - variants: ProductVariant[] price: ProductPrice options: ProductOption[] } @@ -79,17 +80,24 @@ export type ProductsSchema = { export type GetAllProductPathsOperation< T extends ProductTypes = ProductTypes -> = { - data: { products: Pick[] } - variables: { first?: number } -} + > = { + data: { products: Pick[] } + variables: { first?: number } + } export type GetAllProductsOperation = { data: { products: T['product'][] } variables: { - relevance?: 'featured' | 'best_selling' | 'newest' - ids?: string[] - first?: number + term?: String + facetValueIds?: string[] + facetValueOperator?: LogicalOperator + facetValueFilters?: FacetValueFilterInput[] + collectionId?: string + collectionSlug?: string + groupByProduct?: Boolean + take?: number + skip?: number + sort?: SearchResultSortParameter } } diff --git a/framework/vendure/api/operations/get-all-facets.ts b/framework/vendure/api/operations/get-all-facets.ts index 9187525d3..c4b002744 100644 --- a/framework/vendure/api/operations/get-all-facets.ts +++ b/framework/vendure/api/operations/get-all-facets.ts @@ -1,9 +1,8 @@ +import { OperationContext } from '@commerce/api/operations' import { Facet } from '@commerce/types/facet' import { Provider, VendureConfig } from '../' import { GetAllFacetsQuery } from '../../schema' -import { normalizeSearchResult } from '../../utils/normalize' import { getAllFacetsQuery } from '../../utils/queries/get-all-facets-query' -import { OperationContext } from '@commerce/api/operations' export type FacetVariables = { first?: number } @@ -38,7 +37,7 @@ export default function getAllFacetsOperation({ }) return { - facets: data.search.items.map((item) => normalizeSearchResult(item)), + facets: data.facets.items, } } diff --git a/framework/vendure/api/operations/get-all-products.ts b/framework/vendure/api/operations/get-all-products.ts index 68d4ce9b7..1f558a7cb 100644 --- a/framework/vendure/api/operations/get-all-products.ts +++ b/framework/vendure/api/operations/get-all-products.ts @@ -5,7 +5,7 @@ import { normalizeSearchResult } from '../../utils/normalize' import { getAllProductsQuery } from '../../utils/queries/get-all-products-query' import { OperationContext } from '@commerce/api/operations' -export type ProductVariables = { first?: number } +export type ProductVariables = { first?: number, facetValueIds?: string[] } export default function getAllProductsOperation({ commerce, @@ -30,6 +30,7 @@ export default function getAllProductsOperation({ const variables = { input: { take: vars.first, + facetValueIds: vars.facetValueIds, groupByProduct: true, }, } diff --git a/framework/vendure/schema.d.ts b/framework/vendure/schema.d.ts index 3922f679b..a817d6799 100644 --- a/framework/vendure/schema.d.ts +++ b/framework/vendure/schema.d.ts @@ -3036,7 +3036,9 @@ export type CartFragment = { __typename?: 'Order' } & Pick< export type SearchResultFragment = { __typename?: 'SearchResult' } & Pick< SearchResult, - 'productId' | 'productName' | 'description' | 'slug' | 'sku' | 'currencyCode' + 'productId' | 'sku' | 'productName' | 'description' | 'slug' | 'sku' | 'currencyCode' + | 'productAsset' | 'price' | 'priceWithTax' | 'currencyCode' + | 'collectionIds' > & { productAsset?: Maybe< { __typename?: 'SearchResultAsset' } & Pick< diff --git a/framework/vendure/utils/normalize.ts b/framework/vendure/utils/normalize.ts index 09c1c6e42..b99aa5096 100644 --- a/framework/vendure/utils/normalize.ts +++ b/framework/vendure/utils/normalize.ts @@ -3,18 +3,20 @@ import { Cart } from '@commerce/types/cart' import { CartFragment, SearchResultFragment } from '../schema' export function normalizeSearchResult(item: SearchResultFragment): Product { + const imageUrl = item.productAsset?.preview ? item.productAsset?.preview + '?w=800&mode=crop' : '' return { id: item.productId, name: item.productName, description: item.description, slug: item.slug, path: item.slug, - images: [{ url: item.productAsset?.preview + '?w=800&mode=crop' || '' }], - variants: [], + images: imageUrl ? [{ url: imageUrl }] : [], price: { + // TODO: check price value: (item.priceWithTax as any).min / 100, currencyCode: item.currencyCode, }, + // TODO: check product option options: [], sku: item.sku, } diff --git a/pages/index.tsx b/pages/index.tsx index 371922e59..3082d1790 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -1,20 +1,22 @@ +import { ProductVariables } from '@framework/api/operations/get-all-products'; +import { Product } from '@framework/schema'; import commerce from '@lib/api/commerce'; import { GetStaticPropsContext } from 'next'; import { Layout } from 'src/components/common'; import { FeaturedProductsCarousel, HomeBanner, HomeCategories, HomeCollection, HomeCTA, HomeFeature, HomeRecipe, HomeSubscribe, HomeVideo } from 'src/components/modules/home'; import HomeSpice from 'src/components/modules/home/HomeSpice/HomeSpice'; +import { getAllFeaturedFacetId, getFreshProductFacetId } from 'src/utils/funtion.utils'; interface Props { - products: any + freshProducts: Product[], + featuredProducts: Product[], + } -export default function Home({ products }: Props) { +export default function Home({ freshProducts, featuredProducts }: Props) { + console.log("total: ", freshProducts.length, featuredProducts.length) + console.log("rs: ", freshProducts, featuredProducts) return ( <> -

- TOTAL: {products?.length} -

- - {JSON.stringify(products[0])} @@ -39,29 +41,51 @@ export async function getStaticProps({ locales, }: GetStaticPropsContext) { const config = { locale, locales } - const productsPromise = commerce.getAllProducts({ - // const productsPromise = commerce.getAllFacets({ + const { facets } = await commerce.getAllFacets({ + variables: {}, + config, + preview, + }) + + + const freshProductvariables: ProductVariables = {} + const freshFacetId = getFreshProductFacetId(facets) + + if (freshFacetId) { + freshProductvariables.facetValueIds = [freshFacetId] + } + const freshProductsPromise = commerce.getAllProducts({ + variables: freshProductvariables, + config, + preview, + }) + + const allFeaturedFacetId = getAllFeaturedFacetId(facets) + const featuredProductsPromise = commerce.getAllProducts({ variables: { - first: 70, - // filter: { - // name: { - // contains: 'ca' - // } - // } + facetValueIds: allFeaturedFacetId }, config, preview, - // Saleor provider only - ...({ featured: true } as any), }) - const { products } = await productsPromise + try { + const rs = await Promise.all([freshProductsPromise, featuredProductsPromise]) + + return { + props: { + freshProducts: rs[0].products, + featuredProducts: rs[1].products + }, + revalidate: 60, + } + } catch (err) { - return { - props: { products }, - revalidate: 60, } + + + } diff --git a/src/components/modules/home/FreshProducts/FreshProducts.tsx b/src/components/modules/home/FreshProducts/FreshProducts.tsx new file mode 100644 index 000000000..b06138079 --- /dev/null +++ b/src/components/modules/home/FreshProducts/FreshProducts.tsx @@ -0,0 +1,148 @@ +import { Product } from '@framework/schema' +import React from 'react' +import { CollectionCarcousel } from '..' +import image5 from '../../../../../public/assets/images/image5.png' +import image6 from '../../../../../public/assets/images/image6.png' +import image7 from '../../../../../public/assets/images/image7.png' +import image8 from '../../../../../public/assets/images/image8.png' +interface FreshProductsProps { + data: Product[] +} +const dataTest = [ + { + name: 'Tomato', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image5.src, + }, + { + name: 'Cucumber', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image6.src, + }, + { + name: 'Carrot', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image7.src, + }, + { + name: 'Salad', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image8.src, + }, + { + name: 'Tomato', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image5.src, + }, + { + name: 'Cucumber', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image6.src, + }, + { + name: 'Tomato', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image5.src, + }, + { + name: 'Cucumber', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image6.src, + }, + { + name: 'Carrot', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image7.src, + }, + { + name: 'Salad', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image8.src, + }, + { + name: 'Tomato', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image5.src, + }, + { + name: 'Cucumber', + weight: '250g', + category: 'VEGGIE', + price: 'Rp 27.500', + imageSrc: image6.src, + }, +] + +const FreshProducts = ({data}: FreshProductsProps) => { + return ( +
+ + + + + + +
+ ) +} + +export default FreshProducts diff --git a/src/components/modules/home/index.ts b/src/components/modules/home/index.ts index 82a0e3d8a..0618812c5 100644 --- a/src/components/modules/home/index.ts +++ b/src/components/modules/home/index.ts @@ -4,6 +4,7 @@ export { default as HomeCategories } from './HomeCategories/HomeCategories' export { default as HomeCTA } from './HomeCTA/HomeCTA' export { default as HomeSubscribe } from './HomeSubscribe/HomeSubscribe' export { default as HomeVideo } from './HomeVideo/HomeVideo' +export { default as FreshProducts } from './FreshProducts/FreshProducts' export { default as HomeCollection } from './HomeCollection/HomeCollection' export { default as HomeRecipe } from './HomeRecipe/HomeRecipe' export { default as FeaturedProductsCarousel } from './FeaturedProductsCarousel/FeaturedProductsCarousel' diff --git a/src/utils/constanst.utils.ts b/src/utils/constanst.utils.ts index f77991604..f66d6a7ea 100644 --- a/src/utils/constanst.utils.ts +++ b/src/utils/constanst.utils.ts @@ -107,7 +107,15 @@ export const CATEGORY = [ link: `${ROUTE.PRODUCTS}/?${QUERY_KEY.BRAND}=chinsu`, }, ] - + +export const FACET = { + FEATURE: { + PARENT_NAME: 'Featured', + FRESH: 'Fresh', + BEST_SELLERS: 'Best seller' + } +} + export const FEATURED = [ { name: 'Best Sellers', @@ -141,3 +149,4 @@ export const STATE_OPTIONS = [ value: 'Hà Nội', }, ] + diff --git a/src/utils/funtion.utils.ts b/src/utils/funtion.utils.ts index 43d517589..d2ad83be1 100644 --- a/src/utils/funtion.utils.ts +++ b/src/utils/funtion.utils.ts @@ -1,11 +1,29 @@ +import { FacetValue } from './../../framework/vendure/schema.d'; +import { Facet } from "@commerce/types/facet"; +import { FACET } from "./constanst.utils"; + export function isMobile() { - return window.innerWidth < 768 + return window.innerWidth < 768 } -export function removeItem(arr: Array, value: T): Array { - const index = arr.indexOf(value); - if (index > -1) { - arr.splice(index, 1); - } - return [...arr]; +export function removeItem(arr: Array, value: T): Array { + const index = arr.indexOf(value); + if (index > -1) { + arr.splice(index, 1); + } + return [...arr]; +} + +export function getFreshProductFacetId(facets: Facet[]) { + const featuredFacet = facets.find((item: Facet) => item.name === FACET.FEATURE.PARENT_NAME) + const freshFacetValue = featuredFacet?.values.find((item: FacetValue) => item.name === FACET.FEATURE.FRESH) + + return freshFacetValue?.id +} + +export function getAllFeaturedFacetId(facets: Facet[]) { + const featuredFacet = facets.find((item: Facet) => item.name === FACET.FEATURE.PARENT_NAME) + const rs = featuredFacet?.values.map((item: FacetValue) => item.id) + + return rs } \ No newline at end of file