id
stringlengths
12
53
messages
listlengths
3
3
code_search-engine-example_55bbd0cb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/clients/search.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n AppClient,\n InstanceOptions,\n IOContext,\n RequestConfig,\n SegmentData,\n CacheType,\n} from '@vtex/api'\nimport { stringify } from 'qs'\n\nimport { searchEncodeURI, SearchCrossSellingTypes } from '../resolvers/search/utils'\n\ninterface AutocompleteArgs {\n maxRows: number | string\n searchTerm: string\n}\n\nenum SimulationBehavior {\n SKIP = 'skip',\n DEFAULT = 'default'\n}\n\n\nconst inflightKey = ({ baseURL, url, params, headers }: RequestConfig) => {\n return (\n baseURL! +\n url! +\n stringify(params, { arrayFormat: 'repeat', addQueryPrefix: true }) +\n `&segmentToken=${headers['x-vtex-segment']}`\n )\n}\n\ninterface SearchPageTypeResponse {\n id: string\n pageType: string\n name: string\n url: string\n title: string | null\n metaTagDescription: string | null\n}\n\n/** Search API\n * Docs: https://documenter.getpostman.com/view/845/catalogsystem-102/Hs44\n */\nexport class Search extends AppClient {\n private searchEncodeURI: (x: string) => string\n\n public constructor(ctx: IOContext, opts?: InstanceOptions) {\n super('vtex.catalog-api-proxy@0.x', ctx, opts)\n\n this.searchEncodeURI = searchEncodeURI(ctx.account)\n }\n\n public pageType = (path: string, query: string = '') => {\n const pageTypePath = path.startsWith('/') ? path.substr(1) : path\n\n const pageTypeQuery = !query || query.startsWith('?') ? query : `?${query}`\n\n return this.get<SearchPageTypeResponse>(\n `/pub/portal/pagetype/${pageTypePath}${pageTypeQuery}`,\n { metric: 'search-pagetype' }\n )\n }\n\n public product = (slug: string) =>\n this.get<SearchProduct[]>(\n `/pub/products/search/${this.searchEncodeURI(slug && slug.toLowerCase())}/p`,\n { metric: 'search-product' }\n )\n\n public productByEan = (id: string) =>\n this.get<SearchProduct[]>(\n `/pub/products/search?fq=alternateIds_Ean:${id}`,\n {\n metric: 'search-productByEan',\n }\n )\n\n public productsByEan = (ids: string[]) =>\n this.get<SearchProduct[]>(\n `/pub/products/search?${ids\n .map(id => `fq=alternateIds_Ean:${id}`)\n .join('&')}`,\n { metric: 'search-productByEan' }\n )\n\n public productById = (id: string, cacheable: boolean = true) => {\n const isVtex = this.context.platform === 'vtex'\n const url = isVtex ? '/pub/products/search?fq=productId:' : '/products/'\n return this.get<SearchProduct[]>(`${url}${id}`, {\n metric: 'search-productById',\n ...(cacheable ? {} : { cacheable: CacheType.None })\n })\n }\n\n public productsById = (ids: string[]) =>\n this.get<SearchProduct[]>(\n `/pub/products/search?${ids.map(id => `fq=productId:${id}`).join('&')}`,\n { metric: 'search-productById' }\n )\n\n public productByReference = (id: string) =>\n this.get<SearchProduct[]>(\n `/pub/products/search?fq=alternateIds_RefId:${id}`,\n {\n metric: 'search-productByReference',\n }\n )\n\n public productsByReference = (ids: string[]) =>\n this.get<SearchProduct[]>(\n `/pub/products/search?${ids\n .map(id => `fq=alternateIds_RefId:${id}`)\n .join('&')}`,\n { metric: 'search-productByReference' }\n )\n\n public productBySku = (skuIds: string[]) =>\n this.get<SearchProduct[]>(\n `/pub/products/search?${skuIds\n .map(skuId => `fq=skuId:${skuId}`)\n .join('&')}`,\n { metric: 'search-productBySku' }\n )\n\n public productsRaw = (args: SearchArgs) => {\n return this.getRaw<SearchProduct[]>(this.productSearchUrl(args), {\n metric: 'search-products',\n })\n }\n\n public products = (args: SearchArgs) => {\n return this.get<SearchProduct[]>(this.productSearchUrl(args), {\n metric: 'search-products',\n })\n }\n\n public productsQuantity = async (args: SearchArgs) => {\n const {\n headers: { resources },\n } = await this.getRaw(this.productSearchUrl(args))\n const quantity = resources.split('/')[1]\n return parseInt(quantity, 10)\n }\n\n public brands = () =>\n this.get<Brand[]>('/pub/brand/list', { metric: 'search-brands' })\n\n public brand = (id: number) =>\n this.get<Brand[]>(`/pub/brand/${id}`, { metric: 'search-brands' })\n\n public categories = (treeLevel: number) =>\n this.get<CategoryTreeResponse[]>(`/pub/category/tree/${treeLevel}/`, {\n metric: 'search-categories',\n })\n\n public getCategoryChildren = (id: number) =>\n this.get<Record<string, string>>(`/pub/category/categories/children?id=${id}`, {\n metric: 'search-category-children'\n })\n\n public facets = (facets: string = '') => {\n const [path, options] = decodeURI(facets).split('?')\n return this.get<SearchFacets>(\n `/pub/facets/search/${encodeURI(this.searchEncodeURI(\n `${path.trim()}${options ? '?' + options : ''}`\n ))}`,\n { metric: 'search-facets' }\n )\n }\n\n public category = (id: string | number) =>\n this.get<CategoryByIdResponse>(`/pub/category/${id}`, {\n metric: 'search-category',\n })\n\n public crossSelling = (id: string, type: SearchCrossSellingTypes) =>\n this.get<SearchProduct[]>(`/pub/products/crossselling/${type}/${id}`, {\n metric: 'search-crossSelling',\n })\n\n public autocomplete = ({ maxRows, searchTerm }: AutocompleteArgs) =>\n this.get<{ itemsReturned: SearchAutocompleteUnit[] }>(\n `/buscaautocomplete?maxRows=${maxRows}&productNameContains=${\n encodeURIComponent(this.searchEncodeURI(searchTerm))\n }`,\n { metric: 'search-autocomplete' }\n )\n\n private get = <T = any>(url: string, config: RequestConfig = {}) => {\n const segmentData: SegmentData | undefined = (this\n .context! as CustomIOContext).segment\n const { channel: salesChannel = '' } = segmentData || {}\n\n config.params = {\n ...config.params,\n ...(!!salesChannel && { sc: salesChannel }),\n }\n config.inflightKey = inflightKey\n\n return this.http.get<T>(`/proxy/catalog${url}`, config)\n }\n\n public getField = (id: number) =>\n this.get<FieldResponseAPI>(\n `/pub/specification/fieldGet/${id}`,\n { metric: 'catalog-get-field-by-id' }\n )\n\n private getRaw = <T = any>(url: string, config: RequestConfig = {}) => {\n const segmentData: SegmentData | undefined = (this\n .context! as CustomIOContext).segment\n const { channel: salesChannel = '' } = segmentData || {}\n\n config.params = {\n ...config.params,\n ...(!!salesChannel && { sc: salesChannel }),\n }\n config.inflightKey = inflightKey\n\n return this.http.getRaw<T>(`/proxy/catalog${url}`, config)\n }\n\n private productSearchUrl = ({\n query = '',\n category = '',\n specificationFilters,\n priceRange = '',\n collection = '',\n salesChannel = '',\n orderBy = '',\n from = 0,\n to = 9,\n map = '',\n hideUnavailableItems = false,\n simulationBehavior = SimulationBehavior.DEFAULT,\n }: SearchArgs) => {\n const sanitizedQuery = encodeURIComponent(\n this.searchEncodeURI(decodeURIComponent(query || '').trim())\n )\n if (hideUnavailableItems) {\n const segmentData = (this.context as CustomIOContext).segment\n salesChannel = (segmentData && segmentData.channel.toString()) || ''\n }\n let url = `/pub/products/search/${sanitizedQuery}?`\n if (category && !query) {\n url += `&fq=C:/${category}/`\n }\n if (specificationFilters && specificationFilters.length > 0) {\n url += specificationFilters.map(filter => `&fq=${filter}`)\n }\n if (priceRange) {\n url += `&fq=P:[${priceRange}]`\n }\n if (collection) {\n url += `&fq=productClusterIds:${collection}`\n }\n if (salesChannel) {\n url += `&fq=isAvailablePerSalesChannel_${salesChannel}:1`\n }\n if (orderBy) {\n url += `&O=${orderBy}`\n }\n if (map) {\n url += `&map=${map}`\n }\n if (from != null && from > -1) {\n url += `&_from=${from}`\n }\n if (to != null && to > -1) {\n url += `&_to=${to}`\n }\n if (simulationBehavior === SimulationBehavior.SKIP) {\n url += `&simulation=false`\n }\n return url\n }\n}\n\n```" } ]
code_search-engine-example_f944a0af
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/clients/checkout.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n JanusClient,\n RequestConfig,\n} from '@vtex/api'\n\nimport { statusToError } from '../utils'\n\n/**\n * Checkout client to connect with VTEX Core Commerce APIs about Sales Channel and Checkout Simulation\n *\n */\nexport class Checkout extends JanusClient {\n public constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...(options && options.headers),\n },\n })\n }\n\n private getChannelQueryString = () => {\n const { segment } = this.context as CustomIOContext\n const channel = segment && segment.channel\n const queryString = channel ? `?sc=${channel}` : ''\n return queryString\n }\n\n public simulation = (simulation: SimulationPayload) =>\n this.post<OrderForm>(\n this.routes.simulation(this.getChannelQueryString()),\n simulation,\n {\n metric: 'checkout-simulation',\n }\n )\n\n protected post = <T>(url: string, data?: any, config: RequestConfig = {}) => {\n return this.http.post<T>(url, data, config).catch(statusToError) as Promise<\n T\n >\n }\n\n private get routes() {\n const base = '/api/checkout/pub'\n return {\n simulation: (queryString: string) =>\n `${base}/orderForms/simulation${queryString}`,\n }\n }\n}\n\n```" } ]
code_search-engine-example_c57cb243
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/clients/index.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport { Search } from './search'\nimport { Checkout } from './checkout'\nimport { customSearchEngineClient } from './customEngine'\n\n/**\n * On this file you'll name and export the custom clients created by this app. \n * \n * The Search and Checkout clients will be used to connect with VTEX APIs, and the customSearchEngine with the API to be integrated.\n */\nexport class Clients extends IOClients {\n public get search() {\n return this.getOrSet('search', Search)\n }\n public get checkout() {\n return this.getOrSet('checkout', Checkout)\n }\n public get customSearchEngine() {\n return this.getOrSet('customSearchEngine', customSearchEngineClient)\n }\n}\n\n```" } ]
code_search-engine-example_6b8bd33f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/clients/customEngine.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\n\n/**\n * The client used for connecting with the Search Engine external API.\n * \n * Don't forget to also add the host on the manifest.json's policies as well!\n */\nexport class customSearchEngineClient extends ExternalClient {\n private store: string\n\n public constructor(context: IOContext, options?: InstanceOptions) {\n super('https://api.customsearchengine.com/v1', context, options)\n\n const { account } = context\n this.store = account\n }\n\n /**\n * This is where will be implemented the appropriate methods to retrieve data from the search engine API.\n * \n * Clients on VTEX IO may have retries, timeouts and cache configured. Check it on our documentation about Clients.\n * \n * Also, don't forget to add the `metric` option when fetching HTTP. It may be used for billing purposes or to track problematic connections.\n * \n * Example method:\n */\n\n public async suggestionSearches(args: SuggestionSearchesArgs): Promise<any> {\n const { term } = args\n\n const result = await this.http.get<any>(\n `${this.store}/api/suggestion_searches`,\n {\n params: {\n term,\n },\n metric: 'suggestion-searches',\n }\n )\n\n return result\n }\n\n}\n\n```" } ]
code_search-engine-example_f94b0720
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/commons/compatibility-layer.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport VtexSeller from './models/VtexSeller'\nimport unescape from 'unescape'\n\nexport enum IndexingType {\n API = 'API',\n XML = 'XML',\n}\n\n// Probably all code here should change acccordingly to the search engine to be integrated. Keeping it here for reference.\nexport const convertBiggyProduct = (\n product: any,\n tradePolicy?: string,\n indexingType?: IndexingType\n) => {\n const categories: string[] = product.categories\n ? product.categories.map((_: any, index: number) => {\n const subArray = product.categories.slice(0, index)\n return `/${subArray.join('/')}/`\n })\n : []\n\n const skus: any[] = (product.skus || []).map(\n convertSKU(product, indexingType, tradePolicy)\n )\n\n return {\n categories,\n cacheId: product.link,\n productId: product.product || product.id,\n productName: product.name,\n productReference: product.reference || product.product || product.id,\n linkText: product.link,\n brand:\n product.brand ||\n product.extraInfo['marca'] ||\n product.extraInfo['brand'] ||\n '',\n brandId: -1,\n link: product.url,\n description: product.description,\n items: skus,\n sku: skus.find(sku => sku.sellers && sku.sellers.length > 0),\n }\n}\n\nconst getSellersIndexedByApi = (\n product: any,\n sku: any,\n tradePolicy?: string\n) => {\n const selectedPolicy = tradePolicy\n ? sku.policies.find((policy: any) => policy.id === tradePolicy)\n : sku.policies[0]\n\n const biggySellers = (selectedPolicy && selectedPolicy.sellers) || []\n\n return biggySellers.map((seller: any) => {\n const price = seller.price || sku.price || product.price\n const oldPrice = seller.oldPrice || sku.oldPrice || product.oldPrice\n const installment = seller.installment || product.installment\n\n return new VtexSeller(seller.id, price, oldPrice, installment)\n })\n}\n\nconst getSellersIndexedByXML = (product: any) => {\n const { installment, price, oldPrice } = product\n return [new VtexSeller('1', price, oldPrice, installment)]\n}\n\nconst getImageId = (imageUrl: string) => {\n const baseUrlRegex = new RegExp(/.+ids\\/(\\d+)/)\n return baseUrlRegex.test(imageUrl)\n ? baseUrlRegex.exec(imageUrl)![1]\n : undefined\n}\n\nconst elasticImageToVtexImage = (image: ElasticImage, imageId: string) => {\n return {\n imageId,\n cacheId: imageId,\n imageLabel: image.name,\n imageText: image.name,\n imageUrl: image.value,\n }\n}\n\nconst convertImages = (images: ElasticImage[], indexingType?: IndexingType) => {\n const vtexImages: VtexImage[] = []\n\n if (indexingType && indexingType === IndexingType.XML) {\n const selectedImage: ElasticImage = images[0]\n const imageId = getImageId(selectedImage.value)\n\n return imageId ? [elasticImageToVtexImage(selectedImage, imageId)] : []\n }\n\n images.forEach(image => {\n const imageId = getImageId(image.value)\n imageId ? vtexImages.push(elasticImageToVtexImage(image, imageId)) : []\n })\n\n return vtexImages\n}\n\nconst convertSKU = (\n product: any,\n indexingType?: IndexingType,\n tradePolicy?: string\n) => (sku: any) => {\n const images = convertImages(product.images, indexingType)\n\n const sellers =\n indexingType === IndexingType.XML\n ? getSellersIndexedByXML(product)\n : getSellersIndexedByApi(product, sku, tradePolicy)\n\n return {\n sellers,\n images,\n seller: sellers[0],\n itemId: sku.id,\n name: product.name,\n nameComplete: product.name,\n complementName: product.name,\n referenceId: [\n {\n Key: 'RefId',\n Value: sku.reference,\n },\n ],\n }\n}\n\nexport const biggyAttributesToVtexFilters = (attributes: any) =>\n attributes.map((attribute: any) => {\n const isNumber = attribute.type === 'number'\n\n return {\n name: attribute.label,\n type: isNumber ? 'PRICERANGE' : attribute.type.toUpperCase(),\n values: isNumber\n ? [\n {\n quantity: attribute.values.reduce(\n (acum: number, value: any) => acum + value.count,\n 0\n ),\n name: unescape(attribute.label),\n key: attribute.key,\n value: attribute.key,\n range: {\n from: attribute.minValue,\n to: attribute.maxValue,\n },\n },\n ]\n : attribute.values.map((value: any) => {\n return {\n quantity: value.count,\n name: unescape(value.label),\n key: attribute.key,\n value: value.key,\n selected: value.active,\n }\n }),\n }\n })\n\n/**\n * Convert from VTEX OrderBy into Biggy's sort.\n *\n * @export\n * @param {OrderBy} orderBy VTEX OrderBy.\n * @returns {string} Biggy's sort.\n */\nexport const convertOrderBy = (orderBy?: string): string => {\n switch (orderBy) {\n case 'OrderByPriceDESC':\n return 'price:desc'\n case 'OrderByPriceASC':\n return 'price:asc'\n case 'OrderByTopSaleDESC':\n return 'orders:desc'\n case 'OrderByReviewRateDESC':\n return '' // TODO: Not Supported\n case 'OrderByNameDESC':\n return 'name:desc'\n case 'OrderByNameASC':\n return 'name:asc'\n case 'OrderByReleaseDateDESC':\n return 'fields.release:desc'\n case 'OrderByBestDiscountDESC':\n return 'discount:desc'\n default:\n return ''\n }\n}\n\nexport const buildBreadcrumb = (selectedFacets: SelectedFacet[]) => {\n const pivotValue: string[] = []\n const pivotMap: string[] = []\n\n return selectedFacets\n .filter(selectedFacet => selectedFacet.key !== 'priceRange')\n .map(selectedFacet => {\n pivotValue.push(selectedFacet.value)\n pivotMap.push(selectedFacet.key)\n\n return {\n name: decodeURIComponent(selectedFacet.value),\n href: `/${pivotValue.join('/')}?map=${pivotMap.join(',')}`,\n }\n })\n}\n\nexport const buildAttributePath = (selectedFacets: SelectedFacet[]) => {\n return selectedFacets.reduce(\n (attributePath, facet) => {\n if (facet.key === 'priceRange') {\n facet.key = 'price'\n facet.value = facet.value.replace(` TO `, ':')\n }\n\n return facet.key !== 'ft'\n ? `${attributePath}${facet.key}/${facet.value}/`\n : attributePath\n },\n\n ''\n )\n}\n\n```" } ]
code_search-engine-example_052bb8f7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/commons/products.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { convertBiggyProduct } from './compatibility-layer'\nimport { map, prop, isEmpty, sort, indexOf } from 'ramda'\nimport { queries } from '../resolvers/search'\n\n// Probably all code here should change acccordingly to the search engine to be integrated. Keeping it here for reference.\nexport const productsBiggy = async (searchResult: any, ctx: any) => {\n const { segment } = ctx.vtex\n const products: any[] = []\n\n searchResult.products.forEach((product: any) => {\n try {\n products.push(convertBiggyProduct(product, segment && segment.channel))\n } catch (e) {\n // TODO: add logging\n }\n })\n\n return products\n}\n\nexport const productsCatalog = async (searchResult: any, ctx: any) => {\n let products: any[] = searchResult.products\n const productIds = map<any, string>((product: any) => {\n return prop('product', product) || prop('id', product) || ''\n }, products)\n\n if (!isEmpty(productIds)) {\n // Get products' model from VTEX search API\n products = await queries.productsByIdentifier(\n undefined,\n {\n field: 'id',\n values: productIds,\n },\n ctx\n )\n\n // Maintain customSearchEngine's order.\n products = sort(\n (a, b) =>\n indexOf(a.productId, productIds) - indexOf(b.productId, productIds),\n products\n )\n }\n\n return products\n}\n\n```" } ]
code_search-engine-example_cc095670
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/typings/unescape.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'unescape' {\n export default function(codedString: string): string\n}\n\n```" } ]
code_search-engine-example_24967764
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/typings/Search.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface SegmentData {\n campaigns?: any\n channel: number\n priceTables?: any\n utm_campaign: string\n regionId?: string\n utm_source: string\n utmi_campaign: string\n currencyCode: string\n currencySymbol: string\n countryCode: string\n cultureInfo: string\n [key: string]: any\n}\n\ninterface ElasticImage {\n name: string\n value: string\n}\n\ninterface VtexImage {\n cacheId: string\n imageId: string\n imageLabel: string\n imageUrl: string\n imageText: string\n}\n\nenum IndexingType {\n API = 'API',\n XML = 'XML',\n}\n\ninterface SearchResultArgs {\n attributePath: string\n query: string\n page: number\n count: number\n sort: string\n operator: string\n fuzzy: string\n leap?: boolean\n tradePolicy?: number\n segment?: SegmentData\n indexingType?: IndexingType\n}\n\ninterface SuggestionProductsArgs {\n term: string\n attributeKey?: string\n attributeValue?: string\n tradePolicy?: string\n segment?: SegmentData\n indexingType?: IndexingType\n}\n\ninterface SuggestionSearchesArgs {\n term: string\n}\n\ninterface SelectedFacet {\n value: string\n key: string\n}\n\ninterface FacetsInput {\n selectedFacets: SelectedFacet[]\n fullText: string\n query: string\n}\n\ninterface ProductSearchInput {\n query: string\n from: number\n to: number\n selectedFacets: SelectedFacet[]\n fullText: string\n fuzzy: string\n operator: string\n orderBy: string\n productOriginVtex: boolean\n}\n\n```" } ]
code_search-engine-example_3f447a7d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/typings/Checkout.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface OrderFormMarketingData {\n utmCampaign?: string\n utmMedium?: string\n utmSource?: string\n utmiCampaign?: string\n utmiPart?: string\n utmipage?: string\n marketingTags?: string\n}\n\ninterface CheckoutAddress {\n addressType: string\n receiverName: string\n addressId: string\n postalCode: string\n city: string\n state: string\n country: string\n street: string\n number: string\n neighborhood: string\n complement: string\n reference: string | null\n geoCoordinates: [number, number]\n}\ninterface OrderFormItem {\n id: string\n name: string\n detailUrl: string\n imageUrl: string\n productRefId: string\n skuName: string\n quantity: number\n uniqueId: string\n productId: string\n refId: string\n ean: string\n priceValidUntil: string\n price: number\n tax: number\n listPrice: number\n sellingPrice: number\n rewardValue: number\n isGift: boolean\n parentItemIndex: number | null\n parentAssemblyBinding: string | null\n productCategoryIds: string\n priceTags: string[]\n measurementUnit: string\n additionalInfo: {\n brandName: string\n brandId: string\n offeringInfo: any | null\n offeringType: any | null\n offeringTypeId: any | null\n }\n productCategories: Record<string, string>\n seller: string\n sellerChain: string[]\n availability: string\n unitMultiplier: number\n}\ninterface OrderForm {\n orderFormId: string\n salesChannel: string\n loggedIn: boolean\n isCheckedIn: boolean\n storeId: string | null\n checkedInPickupPointId: string | null\n allowManualPrice: boolean\n canEditData: boolean\n userProfileId: string | null\n userType: string | null\n ignoreProfileData: boolean\n value: number\n messages: any[]\n items: OrderFormItem[]\n selectableGifts: any[]\n totalizers: { id: string; name: string; value: number }[]\n shippingData: {\n address: CheckoutAddress\n logisticsInfo: {\n itemIndex: number\n selectedSla: string\n selectedDeliveryChannel: string\n addressId: string\n slas: {\n id: string\n deliveryChannel: string\n name: string\n deliveryIds: {\n courierId: string\n warehouseId: string\n dockId: string\n courierName: string\n quantity: number\n }[]\n shippingEstimate: string\n shippingEstimateDate: string | null\n lockTTL: string | null\n availableDeliveryWindows: any[]\n deliveryWindow: string | null\n price: number\n listPrice: number\n tax: number\n pickupStoreInfo: {\n isPickupStore: boolean\n friendlyName: string | null\n\n address: CheckoutAddress | null\n additionalInfo: any | null\n dockId: string | null\n }\n pickupPointId: string | null\n pickupDistance: number\n polygonName: string | null\n }[]\n shipsTo: string[]\n itemId: string\n deliveryChannels: { id: string }[]\n }[]\n selectedAddresses: CheckoutAddress[]\n availableAddresses: CheckoutAddress[]\n pickupPoints: {\n friendlyName: string\n address: CheckoutAddress\n additionalInfo: string\n id: string\n businessHours: {\n DayOfWeek: number\n OpeningTime: string\n ClosingTime: string\n }[]\n }[]\n }\n clientProfileData: any | null\n paymentData: {\n installmentOptions: {\n paymentSystem: string\n bin: string | null\n paymentName: string | null\n paymentGroupName: string | null\n value: number\n installments: {\n count: number\n hasInterestRate: false\n interestRate: number\n value: number\n total: number\n sellerMerchantInstallments: {\n count: number\n hasInterestRate: false\n interestRate: number\n value: number\n total: number\n }[]\n }[]\n }[]\n paymentSystems: {\n id: string\n name: string\n groupName: string\n validator: {\n regex: string\n mask: string\n cardCodeRegex: string\n cardCodeMask: string\n weights: number[]\n useCvv: boolean\n useExpirationDate: boolean\n useCardHolderName: boolean\n useBillingAddress: boolean\n }\n stringId: string\n template: string\n requiresDocument: boolean\n isCustom: boolean\n description: string | null\n requiresAuthentication: boolean\n dueDate: string\n availablePayments: any | null\n }[]\n payments: any[]\n giftCards: any[]\n giftCardMessages: any[]\n availableAccounts: any[]\n availableTokens: any[]\n }\n marketingData: OrderFormMarketingData | null\n sellers: {\n id: string\n name: string\n logo: string\n }[]\n clientPreferencesData: {\n locale: string\n optinNewsLetter: any | null\n }\n commercialConditionData: any | null\n storePreferencesData: {\n countryCode: string\n saveUserData: boolean\n timeZone: string\n currencyCode: string\n currencyLocale: number\n currencySymbol: string\n currencyFormatInfo: {\n currencyDecimalDigits: number\n currencyDecimalSeparator: string\n currencyGroupSeparator: string\n currencyGroupSize: number\n startsWithCurrencySymbol: boolean\n }\n }\n giftRegistryData: any | null\n openTextField: any | null\n invoiceData: any | null\n customData: any | null\n itemMetadata: {\n items: MetadataItem[]\n }\n hooksData: any | null\n ratesAndBenefitsData: {\n rateAndBenefitsIdentifiers: any[]\n teaser: any[]\n }\n subscriptionData: any | null\n itemsOrdination: any | null\n}\n\ninterface PayloadItem {\n id: string\n quantity: number\n seller: string\n parentItemIndex?: number | null\n parentAssemblyBinding?: string | null\n}\n\ninterface SimulationPayload {\n country?: string\n items: PayloadItem[]\n postalCode?: string\n isCheckedIn?: boolean\n priceTables?: string[]\n marketingData?: Record<string, string>\n}\n\n```" } ]
code_search-engine-example_1abed926
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/typings/SearchMetadata.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface SearchMetadataArgs {\n query?: string | null\n map?: string | null\n selectedFacets?: SelectedFacet[]\n}\n\ninterface SearchMetadata {\n titleTag?: string | null\n metaTagDescription?: string | null\n}\n\n```" } ]
code_search-engine-example_c26dacf7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/typings/ItemMetadata.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/**\n * Assembly options related types\n */\n\ninterface CompositionItem {\n id: string\n minQuantity: number\n maxQuantity: number\n initialQuantity: number\n priceTable: string\n seller: string\n}\n\ninterface Composition {\n minQuantity: number\n maxQuantity: number\n items: CompositionItem[]\n}\n\ninterface AssemblyOption {\n id: string\n name: string\n composition: Composition | null\n inputValues: InputValues\n}\n\ninterface InputValues {\n [key: string]: RawInputValue\n}\n\ninterface RawInputValue {\n maximumNumberOfCharacters: number\n domain: string[]\n}\n\ninterface SearchMetadataItem {\n Name: string\n NameComplete: string\n MainImage: string\n BrandName: string\n CategoryId: number\n ProductId: number\n id: string\n seller: string\n assemblyOptions: AssemblyOption[]\n}\n\ninterface MetadataItem {\n id: string\n name: string\n imageUrl: string\n detailUrl: string\n seller: string\n assemblyOptions: AssemblyOption[]\n skuName: string\n productId: string\n refId: string\n ean: string | null\n}\ninterface AddedItem {\n choiceType: string\n compositionItem: CompositionItem\n extraQuantity: number\n item: OrderFormItem\n normalizedQuantity: number\n}\n\ninterface RemovedItem {\n initialQuantity: number\n name: string\n removedQuantity: number\n}\n\n```" } ]
code_search-engine-example_fe66fb09
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/typings/Catalog.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Range {\n from: number\n to: number\n}\n\ninterface SelectedFacet {\n key: string\n value: string\n}\n\ninterface QueryArgs {\n query: string\n map?: string\n selectedFacets?: SelectedFacet[]\n}\n\ninterface SearchArgs extends QueryArgs {\n category: string | null\n specificationFilters: string[] | null\n priceRange?: string | null\n collection: string | null\n salesChannel: string | null\n orderBy: string | null\n from: number | null\n to: number | null\n hideUnavailableItems: boolean | null\n simulationBehavior: 'skip' | 'default' | null\n}\n\ninterface Metadata {\n metaTagDescription?: string\n titleTag?: string\n}\n\ninterface Brand {\n id: string\n name: string\n isActive: boolean\n title: string | null\n metaTagDescription: string | null\n imageUrl: string | null\n}\n\ninterface CategoryTreeResponse {\n id: number\n name: string\n hasChildren: boolean\n url: string\n children: CategoryTreeResponse[]\n Title: string\n MetaTagDescription: string\n}\n\ninterface CategoryByIdResponse {\n parentId: number | null\n GlobalCategoryId: number\n GlobalCategoryName: string\n position: number\n slug: string\n id: number\n name: string\n hasChildren: boolean\n url: string\n children: null\n Title: string\n MetaTagDescription: string\n}\n\ninterface FacetsArgs extends QueryArgs {\n hideUnavailableItems?: boolean\n behavior?: FacetsBehavior\n}\n\nenum FacetsBehavior {\n STATIC = 'Static',\n DYNAMIC = 'Dynamic',\n}\n\ninterface SearchProduct {\n productId: string\n productName: string\n brand: string\n brandId: number\n linkText: string\n productReference: string\n categoryId: string\n productTitle: string\n metaTagDescription: string\n clusterHighlights: Record<string, string>\n productClusters: Record<string, string>\n searchableClusters: Record<string, string>\n categories: string[]\n categoriesIds: string[]\n link: string\n description: string\n items: SearchItem[]\n itemMetadata: {\n items: SearchMetadataItem[]\n }\n titleTag: string\n Specifications?: string[]\n allSpecifications?: string[]\n allSpecificationsGroups?: string[]\n}\n\ninterface SearchItem {\n itemId: string\n name: string\n nameComplete: string\n complementName: string\n ean: string\n referenceId: { Key: string; Value: string }[]\n measurementUnit: string\n unitMultiplier: number\n modalType: any | null\n images: SearchImage[]\n Videos: string[]\n variations: string[]\n sellers: Seller[]\n attachments: {\n id: number\n name: string\n required: boolean\n domainValues: string\n }[]\n isKit: boolean\n kitItems?: {\n itemId: string\n amount: number\n }[]\n}\n\ninterface SearchImage {\n imageId: string\n imageLabel: string | null\n imageTag: string\n imageUrl: string\n imageText: string\n}\n\ninterface SearchInstallment {\n Value: number\n InterestRate: number\n TotalValuePlusInterestRate: number\n NumberOfInstallments: number\n PaymentSystemName: string\n PaymentSystemGroupName: string\n Name: string\n}\n\ninterface CommertialOffer {\n DeliverySlaSamplesPerRegion: Record<\n string,\n { DeliverySlaPerTypes: any[]; Region: any | null }\n >\n Installments: SearchInstallment[]\n DiscountHighLight: any[]\n GiftSkuIds: string[]\n Teasers: any[]\n BuyTogether: any[]\n ItemMetadataAttachment: any[]\n Price: number\n ListPrice: number\n PriceWithoutDiscount: number\n RewardValue: number\n PriceValidUntil: string\n AvailableQuantity: number\n Tax: number\n DeliverySlaSamples: {\n DeliverySlaPerTypes: any[]\n Region: any | null\n }[]\n GetInfoErrorMessage: any | null\n CacheVersionUsedToCallCheckout: string\n}\n\ninterface Seller {\n sellerId: string\n sellerName: string\n addToCartLink: string\n sellerDefault: boolean\n commertialOffer: CommertialOffer\n}\n\ninterface SearchFacet {\n Quantity: number\n Name: string\n Link: string\n LinkEncoded: string\n Map: string\n Value: string\n}\n\ninterface SearchFacetCategory {\n Id: number\n Quantity: number\n Name: string\n Link: string\n LinkEncoded: string\n Map: string\n Value: string\n Children: SearchFacetCategory[]\n}\n\ninterface SummaryItem {\n DisplayedItems: number\n TotalItems: number\n}\n\ninterface SearchFacets {\n Departments: SearchFacet[]\n Brands: SearchFacet[]\n SpecificationFilters: Record<string, SearchFacet[]>\n CategoriesTrees: SearchFacetCategory[]\n PriceRanges: {\n Slug: string\n Quantity: number\n Name: string\n Link: string\n LinkEncoded: string\n Map: null\n Value: string\n }[]\n Summary: {\n Departments: SummaryItem\n CategoriesTrees: SummaryItem\n Brands: SummaryItem\n PriceRanges: SummaryItem\n SpecificationFilters: Record<string, SummaryItem>\n }\n}\n\ninterface SearchAutocompleteItem {\n productId: string\n itemId: string\n name: string\n nameComplete: string\n imageUrl: string\n}\n\ninterface SearchAutocompleteUnit {\n items: SearchAutocompleteItem[]\n thumb: string\n thumbUrl: string | null\n name: string\n href: string\n criteria: string\n}\n\ninterface FieldTreeResponseAPI {\n Name: string\n CategoryId: number\n FieldId: number\n IsActive: boolean\n IsStockKeepingUnit: boolean\n}\n\ninterface FieldResponseAPI {\n Name: string\n CategoryId: number | null\n FieldId: number\n IsActive: boolean\n IsRequired: boolean\n FieldTypeId: number\n FieldTypeName: string\n FieldValueId: string | null\n Description: string | null\n IsStockKeepingUnit: boolean\n IsFilter: boolean\n IsOnProductDetails: boolean\n Position: number\n IsWizard: boolean\n IsTopMenuLinkActive: boolean\n IsSideMenuLinkActive: boolean\n DefaultValue: string | null\n FieldGroupId: number\n FieldGroupName: string\n}\n\n```" } ]
code_search-engine-example_d15d12fd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/utils/categoryTreeSearch.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { searchSlugify } from \"./slug\"\n\n\nexport const categoryTreeSearch = (categoryTree: CategoryTreeResponse[], query: string) => {\n const querySegments = query.startsWith('/')? query.split('/').slice(1): query.split('/')\n return bfsCategory(categoryTree, querySegments, 0)\n}\n\nconst bfsCategory = (categoryTree: CategoryTreeResponse[], segments: string[], depth: number): CategoryTreeResponse[] => {\n if(segments.length === 0 || segments.length === depth){\n return []\n }\n\n for (const categoryNode of categoryTree){\n if(searchSlugify(categoryNode.name) === segments[depth]){\n return [categoryNode, ...bfsCategory(categoryNode.children, segments, depth + 1)]\n }\n }\n\n segments.shift()\n return []\n}\n```" } ]
code_search-engine-example_ad279010
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/utils/slug.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport slugify from 'slugify'\nimport { toLower } from 'ramda'\n\nexport function Slugify(str: any) {\n return slugify(str, { lower: true, remove: /[*+~.()'\"!:@]/g })\n}\n\nconst from =\n 'ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a·/_,:;'\nconst to =\n 'AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa------'\nconst removeAccents = (str: string) => {\n let newStr = str.slice(0)\n for (let i = 0; i < from.length; i++) {\n newStr = newStr.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i))\n }\n return newStr\n}\n\n// Parameter \"S. Coifman\" should output \"s--coifman\"\nexport function searchSlugify(str: string) {\n // According to Bacelar, the search API uses a legacy method for slugifying strings.\n // replaces special characters with dashes, remove accents and lower cases everything\n // eslint-disable-next-line no-useless-escape\n const noCommas = str.replace(/,/g, '')\n const replaced = noCommas.replace(/[*+~.()'\"!:@&\\[\\]`/ %$#?{}|><=_^]/g, '-')\n return toLower(removeAccents(replaced))\n}\n\n```" } ]
code_search-engine-example_14b90df7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/utils/string.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const toTitleCase = (str: string) => {\n return str\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\n```" } ]
code_search-engine-example_0e4a84cb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/utils/vbase.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { VBase } from '@vtex/api'\nimport { createHash } from 'crypto'\n\nexport const staleFromVBaseWhileRevalidate = async <T>(\n vbase: VBase,\n bucket: string,\n filePath: string,\n validateFunction: (params?: any) => Promise<T>,\n params?: any,\n options?: { expirationInMinutes?: number}\n): Promise<T> => {\n const normalizedFilePath = normalizedJSONFile(filePath)\n const cachedData = await vbase.getJSON<StaleRevalidateData<T>>(bucket, normalizedFilePath, true).catch() as StaleRevalidateData<T>\n if(!cachedData){\n const endDate = getTTL(options?.expirationInMinutes)\n return await revalidate<T>(vbase, bucket, normalizedFilePath, endDate, validateFunction, params)\n }\n\n const { data, ttl} = cachedData as StaleRevalidateData<T>\n \n const today = new Date()\n const ttlDate = new Date(ttl)\n if(today < ttlDate){\n return data\n }\n const endDate = getTTL(options?.expirationInMinutes)\n revalidate<T>(vbase, bucket, normalizedFilePath, endDate, validateFunction, params)\n return data\n}\n\nconst getTTL = (expirationInMinutes?: number) => {\n const ttl = new Date()\n ttl.setMinutes(ttl.getMinutes() + (expirationInMinutes || 30 ))\n return ttl\n}\n\nconst revalidate = async<T> (\n vbase: VBase, bucket: string, filePath: string,\n endDate: Date, validateFunction: (params?: any) => Promise<T>, params?: any) => {\n const data = await validateFunction(params)\n const revalidatedData = { data, ttl: endDate }\n vbase.saveJSON<StaleRevalidateData<T>>(bucket, filePath, revalidatedData).catch()\n return data\n}\n\nconst normalizedJSONFile = (filePath: string) => createHash('md5').update(filePath).digest('hex') + '.json'\n```" } ]
code_search-engine-example_e08f92d5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/utils/attachments.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { all, propEq } from 'ramda'\n\nexport const CHOICE_TYPES = {\n MULTIPLE: 'MULTIPLE',\n SINGLE: 'SINGLE',\n TOGGLE: 'TOGGLE',\n}\n\nconst isParentOptionSingleChoice = ({ composition }: AssemblyOption) => {\n if (!composition) {\n return false\n }\n const { minQuantity, maxQuantity } = composition\n return minQuantity === 1 && maxQuantity === 1\n}\n\nconst isParentOptionToggleChoice = ({ composition }: AssemblyOption) => {\n if (!composition) {\n return false\n }\n const { items } = composition\n return all(propEq('maxQuantity', 1))(items)\n}\n\nexport const getItemChoiceType = (childAssemblyData?: AssemblyOption) => {\n if (!childAssemblyData) {\n return CHOICE_TYPES.MULTIPLE\n }\n const isSingle = isParentOptionSingleChoice(childAssemblyData!)\n if (isSingle) {\n return CHOICE_TYPES.SINGLE\n }\n const isToggle = isParentOptionToggleChoice(childAssemblyData)\n if (isToggle) {\n return CHOICE_TYPES.TOGGLE\n }\n\n return CHOICE_TYPES.MULTIPLE\n}\n\n```" } ]
code_search-engine-example_2d19dc6d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/utils/cookie.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { parse } from 'cookie'\nimport { keys } from 'ramda'\n\nconst isUserLoggedIn = (ctx: Context) => {\n const { vtex: { account } } = ctx\n return !!ctx.cookies.get(`VtexIdclientAutCookie_${account}`)\n}\n\nconst parseCookie = (cookie: string) => {\n const parsed = parse(cookie)\n const cookieName = keys(parsed)[0]\n const cookieValue = parsed[cookieName]\n\n const extraOptions = {\n path: parsed.path,\n domain: parsed.domain,\n expires: parsed.expires ? new Date(parsed.expires) : undefined,\n }\n return {\n name: cookieName,\n value: cookieValue,\n options: extraOptions,\n }\n}\n\n/** Checkout cookie methods */\nconst CHECKOUT_COOKIE = 'checkout.vtex.com'\n\nconst checkoutCookieFormat = (orderFormId: string) => `${CHECKOUT_COOKIE}=__ofid=${orderFormId};`\n\nconst getOrderFormIdFromCookie = (cookies: Context['cookies']) => {\n const cookie = cookies.get(CHECKOUT_COOKIE)\n return cookie && cookie.split('=')[1]\n}\n\nexport { isUserLoggedIn, CHECKOUT_COOKIE, checkoutCookieFormat, getOrderFormIdFromCookie, parseCookie }\n\n```" } ]
code_search-engine-example_aac13735
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/utils/CategoryTreeSegmentsFinder.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { searchSlugify } from './slug'\nimport { VBase } from '@vtex/api'\nimport { Search } from '../clients/search'\nimport { CATEGORY_TREE_CHILDREN_BUCKET, CATEGORY_TREE_ROOT_BUCKET, CATEGORY_TREE_ROOT_PATH } from '../resolvers/search/constants'\nimport { staleFromVBaseWhileRevalidate } from './vbase'\ninterface Clients{\n vbase: VBase\n search: Search\n}\n\ninterface LazyCategoryTreeNode{\n id: number\n name: string\n hasChildren: boolean\n}\n\nexport interface CategoryIdNamePair{\n id: string\n name: string\n}\n\nexport class CategoryTreeSegmentsFinder {\n \n private clients: Clients\n private segments: string[]\n protected categoryTreeRoot: Record<string, LazyCategoryTreeNode>\n\n public constructor(clients: Clients, segments: string[]){\n this.clients = clients\n this.segments = segments\n this.categoryTreeRoot = {}\n }\n\n public find = async () => {\n const { segments } = this\n const result: (CategoryIdNamePair|null)[] = []\n await this.initCategoryTreeRoot()\n\n const rootCategorySegment = this.findRootCategorySegment()\n if(!rootCategorySegment){\n return []\n }\n \n const {category, index} = rootCategorySegment\n \n result[index] = {id: category.id.toString(), name: category.name}\n const segmentsTail = segments.slice(index+1)\n const categorySegmentsFromChildren = await this.findCategoriesFromChildren(category.id, segmentsTail)\n return result.concat(categorySegmentsFromChildren)\n }\n\n /**\n * Fetches a category children from vbase or search\n * clients: {vbase: VBase, search: Search}\n */\n protected lazyFetchChildren = async (id: number) => {\n const { search } = this.clients\n return await this.staleWhileRevalidate<Record<string, string>>(CATEGORY_TREE_CHILDREN_BUCKET, id.toString(), this.fetchChildrenFromSearch, { search, id })\n }\n\n protected staleWhileRevalidate = async <T>(bucket: string, path: string,validateFunction: (params?: any) => Promise<T>, params?: any) => {\n return await staleFromVBaseWhileRevalidate<T>(this.clients.vbase, bucket, path, validateFunction, params)\n }\n\n protected getCategoryTreeRoot = async () => {\n const categoryTree = await this.clients.search.categories(0)\n return categoryTree.reduce((acc, categoryTreeNode) => {\n const categorySlug = searchSlugify(categoryTreeNode.name)\n const lazyCategoryTreeNode = {\n id: categoryTreeNode.id,\n name: categoryTreeNode.name,\n hasChildren: categoryTreeNode.hasChildren,\n }\n acc[categorySlug] = lazyCategoryTreeNode\n return acc\n }, {} as Record<string, LazyCategoryTreeNode>)\n }\n\n private initCategoryTreeRoot = async () => {\n this.categoryTreeRoot = await this.staleWhileRevalidate<Record<string, LazyCategoryTreeNode>>(\n CATEGORY_TREE_ROOT_BUCKET, CATEGORY_TREE_ROOT_PATH, this.getCategoryTreeRoot)\n }\n \n // Returns {id: categoryId, name: categorySlug }\n private findCategoriesFromChildren = async (categoryId: number, segments: string[]) => {\n const result: (CategoryIdNamePair|null)[] = []\n for(const segment of segments){\n const children = await this.getChildren(categoryId)\n const childCategoryId = children[segment]\n if(childCategoryId){\n categoryId = Number(childCategoryId)\n result.push({ id: childCategoryId, name: segment })\n }else{\n result.push(null)\n }\n }\n return result\n }\n \n private findRootCategorySegment = () => {\n const { segments, categoryTreeRoot } = this\n const segmentIndex = segments.findIndex(segment => !!categoryTreeRoot[segment])\n return segmentIndex !== -1? {index: segmentIndex, category: categoryTreeRoot[segments[segmentIndex]]}: null\n }\n\n private getChildren = async (id: number) => {\n return await this.lazyFetchChildren(id)\n }\n \n // Returns { categorySlug: categoryId }\n private fetchChildrenFromSearch = async (params: { search: Search, id: number }): Promise<Record<string, string>> => {\n const {search, id} = params\n const categoryChildren = await search.getCategoryChildren(id)\n const categoryChildrenBySlug = Object.keys(categoryChildren).reduce((acc, categoryChildId: string) => {\n const categoryChildName = categoryChildren[categoryChildId]\n const categoryChildSlug = searchSlugify(categoryChildName)\n acc[categoryChildSlug] = categoryChildId\n return acc\n }, {} as Record<string, string>)\n return categoryChildrenBySlug\n }\n}\n```" } ]
code_search-engine-example_30e8f052
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/utils/object.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n adjust,\n curry,\n fromPairs,\n map,\n mergeAll,\n pipe,\n toPairs,\n zipObj,\n} from 'ramda'\n\n/**\n * Creates a new object with the own properties of the provided object, but the\n * keys renamed according to logic of renaming function.\n *\n * Keep in mind that in the case of keys conflict is behaviour undefined and\n * the result may vary between various JS engines!\n *\n * @func renameKeysWith\n * @category Object\n * @param {Function} func Function that renames the keys\n * @param {!Object} object Provided object\n * @return {!Object} New object with renamed keys\n * @see {@link https://github.com/ramda/ramda/wiki/Cookbook#rename-keys-of-an-object-by-a-function|Ramda Cookbook}\n * @example\n *\n * renameKeysWith(concat('a'), { A: 1, B: 2, C: 3 }) //=> { aA: 1, aB: 2, aC: 3 }\n */\ntype Tuple = [string, any]\nconst renameKeysWith = curry((func: any, object: any) =>\n pipe<any, Tuple[], any, any>(\n toPairs,\n map(adjust(0, func)),\n fromPairs\n )(object)\n)\n\n/*\n * Convert a list of fields like [ {key: 'propertyName', value: 'String'}, ... ]\n * to a JSON format.\n */\nconst parseFieldsToJson = (fields: any) =>\n mergeAll(fields.map((field: any) => zipObj([field.key], [field.value])))\n\nexport { renameKeysWith, parseFieldsToJson }\n\n```" } ]
code_search-engine-example_19ed7830
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/utils/index.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AxiosError } from 'axios'\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\n\nexport * from './object'\nexport * from './cookie'\n\nexport function generateRandomName() {\n return (1 + Math.random()).toString(36).substring(2)\n}\n\nexport function getFileExtension(fileName: string) {\n return fileName.match(/\\.[0-9a-z]+$/i)\n ? (fileName.match(/\\.[0-9a-z]+$/i) as any[])[0]\n : undefined\n}\n\nexport function statusToError(e: any) {\n if (!e.response) {\n throw e\n }\n\n const { response } = e as AxiosError\n const { status } = response!\n\n if (status === 401) {\n throw new AuthenticationError(e)\n }\n if (status === 403) {\n throw new ForbiddenError(e)\n }\n if (status === 400) {\n throw new UserInputError(e)\n }\n\n throw e\n}\n\n```" } ]
code_search-engine-example_5c063cf9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/utils/categoryTreeSearch.test.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as TypeMoq from 'typemoq'\nimport { CategoryTreeSegmentsFinder } from \"./CategoryTreeSegmentsFinder\"\nimport { VBase, IOContext } from \"@vtex/api\"\nimport { Search } from \"../clients/search\"\n\n/* CategoryTree \n * c0 \n * / \\ \n * c1 c2 \n * / \\ \n * c3 c4\n * \\\n * c5\n */\n\nconst context = TypeMoq.Mock.ofType<IOContext>()\nconst vbaseMock = TypeMoq.Mock.ofInstance(VBase)\nconst searchMock = TypeMoq.Mock.ofInstance(Search)\n\nconst c5 = {'c5': '5'}\nconst c4 = {'c4': '4'}\nconst c3 = {'c3': '3'}\nconst c2 = {'c2': '2'}\nconst c1 = { 'c1': '1'}\nconst c0 = { 'c0': '0' }\nconst root = {'c0': {id: 0, name: 'c0', hasChildren: true}}\n\nconst childrenTree = {\n \"0\": {...c1, ...c2},\n \"1\": {...c3, ...c4},\n \"2\": {},\n \"3\": {},\n \"4\": {...c5},\n \"5\": {}\n} as any\n\nconst clients = {vbase: new vbaseMock.object(context.object), search: new searchMock.object(context.object) }\n\nconst toPair = (categories: any[]) => \n categories.map(c => {\n const [key, value] = c && Object.entries(c)[0] || []\n return key? { id: value, name: key }: null\n })\n\ndescribe('Category Tree Search tests', () => {\n const finder = class CategoryTreeSegmentsFinderMock extends CategoryTreeSegmentsFinder {\n public constructor(segments: string[]){\n super(clients, segments)\n this.categoryTreeRoot = root\n }\n\n protected lazyFetchChildren = async (id: number) => {\n const children = childrenTree[id.toString()]\n return children\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected staleWhileRevalidate = async <T>(_: string, __: string, func: (params?: any) => Promise<T>, params?: any) => {\n return func(params)\n }\n\n protected getCategoryTreeRoot = () => {\n return this.categoryTreeRoot as any\n }\n }\n test('It should find a complete tree of categories', async () => {\n const segments = 'c0/c1/c4'.split('/')\n const treeFinder = new finder(segments)\n const result = await treeFinder.find()\n expect(result).toStrictEqual(toPair([c0, c1, c4]))\n })\n\n test('It should find the maximum categories possible ', async () => {\n const segments = 'c0/c1/c2'.split('/')\n const treeFinder = new finder(segments)\n const result = await treeFinder.find()\n expect(result).toStrictEqual(toPair([c0, c1, null]))\n })\n\n test('It should not find when doesnt exist', async () => {\n const segments = 'x/c1/c4'.split('/')\n const treeFinder = new finder(segments)\n const result = await treeFinder.find()\n expect(result).toStrictEqual([])\n })\n})\n```" } ]
code_search-engine-example_68251609
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/index.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { fieldResolvers as benefitsFieldResolvers } from './benefits'\nimport {\n fieldResolvers as searchFieldResolvers,\n queries as searchQueries,\n} from './search'\n\nimport { queries as statsQueries } from './stats'\n\nexport const resolvers = {\n ...searchFieldResolvers,\n ...benefitsFieldResolvers,\n Query: {\n ...searchQueries,\n ...statsQueries\n },\n}\n\n```" } ]
code_search-engine-example_df6fa243
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/commons/models/VtexSeller.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Installment {\n Value: number\n InterestRate: number\n TotalValuePlusInterestRate: number\n NumberOfInstallments: number\n Name: string\n}\n\ninterface CommertialOffer {\n AvailableQuantity: number\n discountHighlights: any[]\n teasers: any[]\n Installments: Installment[]\n Price: number\n ListPrice: number\n PriceWithoutDiscount: number\n}\n\nclass VtexSeller {\n public sellerId: string\n public sellerName: string\n public commertialOffer: CommertialOffer\n\n public constructor(\n sellerId: string,\n price: number,\n oldPrice: number,\n installment: { value: number; count: number }\n ) {\n this.sellerId = sellerId\n this.sellerName = ''\n\n this.commertialOffer = {\n AvailableQuantity: 10000,\n discountHighlights: [],\n teasers: [],\n Installments: installment\n ? [\n {\n Value: installment.value,\n InterestRate: 0,\n TotalValuePlusInterestRate: price,\n NumberOfInstallments: installment.count,\n Name: '',\n },\n ]\n : [],\n Price: price,\n ListPrice: oldPrice,\n PriceWithoutDiscount: price,\n }\n }\n}\n\nexport default VtexSeller\n\n```" } ]
code_search-engine-example_22668c26
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/typings/@gocommerce/utils.d.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '@gocommerce/utils' {\n const Functions: any\n}\n\n```" } ]
code_search-engine-example_1891fcdf
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/category.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { compose, last, prop, split } from 'ramda'\n\nimport { getCategoryInfo } from './utils'\n\nconst lastSegment = compose<string, string[], string>(\n last,\n split('/')\n)\n\nfunction cleanUrl(url: string) {\n return url.replace(/https:\\/\\/[A-z0-9]+\\.vtexcommercestable\\.com\\.br/, '')\n}\n\n/** This type has to be created because the Catlog API to get category by ID does not return the url or children for now.\n * These fields only come if you get the category from the categroy tree api.\n */\n\ntype SafeCategory = CategoryByIdResponse | CategoryTreeResponse\n\nexport const resolvers = {\n Category: {\n cacheId: prop('id'),\n\n href: async ({ url }: SafeCategory) => {\n return cleanUrl(url)\n },\n\n metaTagDescription: prop('MetaTagDescription'),\n\n titleTag: prop('Title'),\n\n slug: async ({ url }: SafeCategory) => {\n return url ? lastSegment(url) : null\n },\n\n children: async (\n { id, children }: SafeCategory,\n _: any,\n { clients: { search } }: Context\n ) => {\n if (children == null) {\n const category = await getCategoryInfo(search, id, 5)\n children = category.children\n }\n return children\n },\n },\n}\n\n```" } ]
code_search-engine-example_5ebd5277
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/searchBreadcrumb.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Functions } from '@gocommerce/utils'\nimport { equals, includes, toLower } from 'ramda'\n\nimport { getSpecificationFilterName } from './modules/metadata'\nimport { findCategoryInTree, getBrandFromSlug } from './utils'\n\ninterface BreadcrumbParams {\n queryUnit: string\n mapUnit: string\n index: number\n queryArray: string[]\n mapArray: string[]\n categories: CategoryTreeResponse[]\n categoriesSearched: string[]\n products: SearchProduct[]\n}\n\nconst findClusterNameFromId = (\n products: SearchProduct[],\n clusterId: string\n) => {\n const productWithCluster = products.find(\n ({ productClusters }) => !!productClusters[clusterId]\n )\n return productWithCluster && productWithCluster.productClusters[clusterId]\n}\n\nconst findSellerFromSellerId = (\n products: SearchProduct[],\n sellerId: string\n) => {\n for (const product of products) {\n for (const item of product.items) {\n const seller = item.sellers.find(sel => sel.sellerId === sellerId)\n if (seller) {\n return seller.sellerName\n }\n }\n }\n return null\n}\n\nconst sliceAndJoin = (array: string[], max: number, joinChar: string) =>\n array.slice(0, max).join(joinChar)\n\nconst isCategoryMap = equals('c')\nconst isBrandMap = equals('b')\nconst isProductClusterMap = equals('productClusterIds')\nconst isSellerMap = equals('sellerIds')\nconst isSpecificationFilter = includes('specificationFilter')\n\nconst getCategoryInfo = (\n { categoriesSearched, queryUnit, categories }: BreadcrumbParams,\n isVtex: boolean,\n ctx: Context\n) => {\n const queryPosition = categoriesSearched.findIndex(cat => cat === queryUnit)\n if (!isVtex) {\n return findCategoryInTree(\n categories,\n categoriesSearched.slice(0, queryPosition + 1)\n )\n }\n return ctx.clients.search\n .pageType(categoriesSearched.slice(0, queryPosition + 1).join('/'))\n .catch(() => null)\n}\n\nconst getBrandInfo = async (\n { queryUnit }: BreadcrumbParams,\n isVtex: boolean,\n { clients: { search } }: Context\n) => {\n if (!isVtex) {\n return getBrandFromSlug(toLower(queryUnit), search)\n }\n return search.pageType(queryUnit).catch(() => null)\n}\n\nexport const resolvers = {\n SearchBreadcrumb: {\n name: async (obj: BreadcrumbParams, _: any, ctx: Context) => {\n const {\n vtex: { account },\n } = ctx\n const { queryUnit, mapUnit, index, queryArray, products } = obj\n const defaultName = queryArray[index]\n const isVtex = !Functions.isGoCommerceAcc(account)\n if (isProductClusterMap(mapUnit)) {\n const clusterName = findClusterNameFromId(products, queryUnit)\n if (clusterName) {\n return clusterName\n }\n }\n if (isCategoryMap(mapUnit)) {\n const categoryData = await getCategoryInfo(obj, isVtex, ctx)\n if (categoryData) {\n return categoryData.name\n }\n }\n if (isSellerMap(mapUnit)) {\n const sellerName = findSellerFromSellerId(products, queryUnit)\n if (sellerName) {\n return sellerName\n }\n }\n if (isBrandMap(mapUnit)) {\n const brandData = await getBrandInfo(obj, isVtex, ctx)\n return brandData ? brandData.name : defaultName\n }\n if (isSpecificationFilter(mapUnit)) {\n return getSpecificationFilterName(queryUnit)\n }\n return defaultName && decodeURI(defaultName)\n },\n href: ({\n index,\n queryArray,\n mapArray,\n mapUnit,\n queryUnit,\n }: BreadcrumbParams) => {\n if (index === 0 && (isCategoryMap(mapUnit) || isBrandMap(mapUnit))) {\n return `/${queryUnit}`\n }\n if (mapArray.every(isCategoryMap)) {\n return `/${sliceAndJoin(queryArray, index + 1, '/')}`\n }\n return `/${sliceAndJoin(queryArray, index + 1, '/')}?map=${sliceAndJoin(\n mapArray,\n index + 1,\n ','\n )}`\n },\n },\n}\n\n```" } ]
code_search-engine-example_507cc2a4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/assemblyOption.test.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { resolvers } from './assemblyOption'\n\ntest('should return a TEXT type', async () => {\n const inputValues: InputValues = {\n 'Line 1': {\n maximumNumberOfCharacters: 20,\n domain: []\n }\n }\n\n const result = await resolvers.AssemblyOption.inputValues(\n { inputValues } as AssemblyOption\n )\n\n expect(result).toHaveLength(1)\n expect(result[0].label).toBe('Line 1')\n expect(result[0].type).toBe('TEXT')\n expect(result[0].maxLength).toBe(20)\n expect(result[0].domain).not.toBeDefined()\n expect(result[0].defaultValue).toBe('')\n})\n\ntest('should return an OPTIONS type', async () => {\n const inputValues: InputValues = {\n 'Line 1': {\n maximumNumberOfCharacters: 10,\n domain: ['One option']\n },\n 'Line 2': {\n maximumNumberOfCharacters: 7,\n domain: ['Two', 'Options']\n },\n }\n\n const result = await resolvers.AssemblyOption.inputValues(\n { inputValues } as AssemblyOption\n )\n\n expect(result).toHaveLength(2)\n\n const [line1, line2] = result\n expect(line1.label).toBe('Line 1')\n expect(line1.type).toBe('OPTIONS')\n expect(line1.maxLength).toBe(undefined)\n expect(line1.domain).toHaveLength(1)\n expect(line1.domain![0]).toBe('One option')\n expect(line1.defaultValue).toBe('One option')\n\n expect(line2.label).toBe('Line 2')\n expect(line2.type).toBe('OPTIONS')\n expect(line2.maxLength).toBe(undefined)\n expect(line2.domain).toHaveLength(2)\n expect(line2.defaultValue).toBe('Two')\n})\n\ntest('should return a BOOLEAN type', async () => {\n const inputValues: InputValues = {\n 'Use thing A': {\n maximumNumberOfCharacters: 5,\n domain: ['true', 'false']\n },\n 'Use thing B': {\n maximumNumberOfCharacters: 5,\n domain: ['false', 'true']\n },\n }\n\n const result = await resolvers.AssemblyOption.inputValues(\n { inputValues } as AssemblyOption\n )\n\n expect(result).toHaveLength(2)\n\n const [thingA, thingB] = result\n expect(thingA.label).toBe('Use thing A')\n expect(thingA.type).toBe('BOOLEAN')\n expect(thingA.maxLength).toBe(undefined)\n expect(thingA.domain).not.toBeDefined()\n expect(thingA.defaultValue).toBe(true)\n\n expect(thingB.label).toBe('Use thing B')\n expect(thingB.type).toBe('BOOLEAN')\n expect(thingB.maxLength).toBe(undefined)\n expect(thingB.domain).not.toBeDefined()\n expect(thingB.defaultValue).toBe(false)\n})\n\n```" } ]
code_search-engine-example_042fa561
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/brand.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop } from 'ramda'\n\nimport { searchSlugify } from '../../utils/slug'\n\nexport const resolvers = {\n Brand: {\n\n titleTag: prop('title'),\n\n active: prop('isActive'),\n\n cacheId: (brand: Brand) => searchSlugify(brand.name),\n\n slug: (brand: Brand) => searchSlugify(brand.name),\n },\n}\n\n```" } ]
code_search-engine-example_99f2f99a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/itemMetadataUnit.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop } from 'ramda'\n\nexport const resolvers = {\n ItemMetadataUnit: {\n imageUrl: prop('MainImage'),\n skuName: prop('Name'),\n name: prop('NameComplete'),\n productId: prop('ProductId'),\n },\n}\n\n```" } ]
code_search-engine-example_04ed18ce
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/autocomplete.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { path, split } from 'ramda'\n\n/**\n * It will extract the slug from the HREF in the item\n * passed as parameter.\n *\n * That is needed once the API provide only the old link\n * (from CMS portal) to access the product page, nothing\n * more.\n *\n * HREF provided:\n * https://portal.vtexcommercestable.com.br/:slug/p\n *\n * @param item The item to extract the information\n */\nconst extractSlug = (item: SearchAutocompleteUnit) => {\n const href = split('/', item.href)\n return item.criteria ? `${href[3]}/${href[4]}` : href[3]\n}\n\nexport const resolvers = {\n Items: {\n slug: (root: SearchAutocompleteUnit) => extractSlug(root),\n\n productId: ({ items }: SearchAutocompleteUnit) =>\n items ? path([0, 'productId'], items) : null,\n },\n}\n\n```" } ]
code_search-engine-example_70fa2df7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/productSearch.test.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { queries } from './index'\nimport { mockContext } from '../../__mocks__/helpers'\n\ndescribe('tests related to the searchMetadata query', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n })\n test('get search metadata from pageType for category', async () => {\n const args = { query: 'Department/Category', map: 'c,c' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe('department/category-title')\n expect(result.metaTagDescription).toBe(\n 'department/category-metaTagDescription'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n })\n\n test('get search metadata from pageType for brand', async () => {\n const args = { query: 'Brand', map: 'b' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe('Brand-title')\n expect(result.metaTagDescription).toBe('Brand-metaTagDescription')\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n })\n\n test('get search metadata for ft search', async () => {\n const args = { query: 'Shoes', map: 'ft' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe('Shoes')\n expect(result.metaTagDescription).toBe(null)\n expect(mockContext.clients.search.pageType).toBeCalledTimes(0)\n })\n\n test('get search metadata for specification filter search', async () => {\n const args = { query: 'Large', map: 'specificationFilter_10' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe('Large')\n expect(result.metaTagDescription).toBe(null)\n expect(mockContext.clients.search.pageType).toBeCalledTimes(0)\n })\n\n test('get search metadata from pageType for category with brand', async () => {\n const args = { query: 'Department/Category/Brand', map: 'c,c,b' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe('brand - department/category-title')\n expect(result.metaTagDescription).toBe(\n 'department/category-metaTagDescription'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(2)\n })\n\n test('get search metadata from pageType for brand with category', async () => {\n const args = { query: 'Brand/Department/Category', map: 'b,c,c' }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe('department/category - Brand-title')\n expect(result.metaTagDescription).toBe('Brand-metaTagDescription')\n expect(mockContext.clients.search.pageType).toBeCalledTimes(2)\n })\n\n test('get search metadata from pageType for category with brand & specification filter', async () => {\n const args = {\n query: 'Department/Category/Brand/Large',\n map: 'c,c,b,specificationFilter_15',\n }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe('Large - brand - department/category-title')\n expect(result.metaTagDescription).toBe(\n 'department/category-metaTagDescription'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(2)\n })\n\n test('get search metadata from pageType for category with brand in the middle', async () => {\n const args = {\n query: 'Department/Category/Brand/SubCategory',\n map: 'c,c,b,c',\n }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe(\n 'brand - department/category/subcategory-title'\n )\n expect(result.metaTagDescription).toBe(\n 'department/category/subcategory-metaTagDescription'\n )\n expect(mockContext.clients.search.pageType).toBeCalledTimes(2)\n })\n\n test('get search metadata for search ft with category', async () => {\n const args = {\n query: 'Shoes/Department/Category',\n map: 'ft,c,c',\n }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe('department/category - Shoes')\n expect(result.metaTagDescription).toBe(null)\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n })\n\n test('get search metadata for search ft with brand', async () => {\n const args = {\n query: 'Shoes/Brand',\n map: 'ft,b',\n }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe('brand - Shoes')\n expect(result.metaTagDescription).toBe(null)\n expect(mockContext.clients.search.pageType).toBeCalledTimes(1)\n })\n\n test('get search metadata for search ft with specification filter', async () => {\n const args = {\n query: 'Shoes/Large',\n map: 'ft,specificationFilter_10',\n }\n\n const result = await queries.searchMetadata({}, args, mockContext as any)\n expect(result.titleTag).toBe('Large - Shoes')\n expect(result.metaTagDescription).toBe(null)\n expect(mockContext.clients.search.pageType).toBeCalledTimes(0)\n })\n})\n\n```" } ]
code_search-engine-example_8acf302e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/index.test.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { queries } from './index'\nimport { mockContext } from '../../__mocks__/helpers'\nimport { getProduct, getItem } from '../../__mocks__/product'\n\nbeforeEach(() => {\n jest.clearAllMocks()\n})\n\ndescribe('product recommendations query tests', () => {\n test('test if productRecommendations products have correct custom cacheId', async () => {\n const product1 = getProduct()\n const product2 = getProduct()\n\n const item1 = getItem()\n const item2 = getItem('2')\n\n product1.items = [item1 as any]\n product2.items = [item2 as any]\n mockContext.clients.search.crossSelling.mockImplementation(() => [\n product1,\n product2,\n ])\n const results = await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'similars' as any },\n mockContext as any\n )\n expect(results.every(p => Boolean(p.cacheId))).toBeTruthy()\n expect(results[0].cacheId).toBe('classic-shoes-1')\n expect(results[1].cacheId).toBe('classic-shoes-2')\n })\n\n test('ensure correct types call the correct APIs', async () => {\n mockContext.clients.search.crossSelling.mockImplementation(() => [])\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'similars' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[0][1]).toBe(\n 'similars'\n )\n\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'view' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[1][1]).toBe(\n 'whosawalsosaw'\n )\n\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'buy' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[2][1]).toBe(\n 'whoboughtalsobought'\n )\n\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'viewAndBought' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[3][1]).toBe(\n 'whosawalsobought'\n )\n\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'suggestions' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[4][1]).toBe(\n 'suggestions'\n )\n\n await queries.productRecommendations(\n {},\n { identifier: { field: 'id', value: '1' }, type: 'accessories' as any },\n mockContext as any\n )\n expect(mockContext.clients.search.crossSelling.mock.calls[5][1]).toBe(\n 'accessories'\n )\n })\n})\n\n```" } ]
code_search-engine-example_35c2eb73
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/product.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { formatTranslatableStringV2 } from '@vtex/api'\nimport { compose, last, map, omit, pathOr, propOr, split } from 'ramda'\n\nimport { getBenefits } from '../benefits'\nimport { buildCategoryMap } from './utils'\n\nconst objToNameValue = (\n keyName: string,\n valueName: string,\n record: Record<string, any> | null | undefined\n) => {\n if (!record) {\n return []\n }\n return Object.keys(record).reduce(\n (acc, key: any) => {\n const value = record[key]\n if (typeof value === 'string') {\n acc.push({ [keyName]: key, [valueName]: value })\n }\n return acc\n },\n [] as Record<string, string>[]\n )\n}\n\ntype SearchProductWithCache = SearchProduct & { cacheId?: string }\nenum ItemsFilterEnum {\n ALL = 'ALL',\n FIRST_AVAILABLE = 'FIRST_AVAILABLE',\n ALL_AVAILABLE = 'ALL_AVAILABLE',\n}\ninterface ItemArg {\n filter?: ItemsFilterEnum\n}\n\nconst isSellerAvailable = (seller: Seller) =>\n pathOr(0, ['commertialOffer', 'AvailableQuantity'], seller) > 0\n\nconst isAvailable = (item: SearchItem): boolean => {\n return item.sellers.find(isSellerAvailable) !== undefined\n}\n\nconst knownNotPG = [\n 'allSpecifications',\n 'brand',\n 'categoriesIds',\n 'categoryId',\n 'clusterHighlights',\n 'productClusters',\n 'items',\n 'productId',\n 'link',\n 'linkText',\n 'productReference',\n]\n\nconst removeTrailingSlashes = (str: string) =>\n str.endsWith('/') ? str.slice(0, str.length - 1) : str\n\nconst removeStartingSlashes = (str: string) =>\n str.startsWith('/') ? str.slice(1) : str\n\nconst getLastCategory = compose<string, string, string[], string>(\n last,\n split('/'),\n removeTrailingSlashes\n)\n\nconst treeStringToArray = compose(\n split('/'),\n removeTrailingSlashes,\n removeStartingSlashes\n)\n\nconst findMainTree = (categoriesIds: string[], prodCategoryId: string) => {\n const mainTree = categoriesIds.find(\n treeIdString => getLastCategory(treeIdString) === prodCategoryId\n )\n if (mainTree) {\n return treeStringToArray(mainTree)\n }\n\n // If we are here, did not find the specified main category ID in given strings. It is probably a bug.\n // We will return the biggest tree we find\n\n const trees = categoriesIds.map(treeStringToArray)\n\n return trees.reduce(\n (acc, currTree) => (currTree.length > acc.length ? currTree : acc),\n []\n )\n}\n\nconst productCategoriesToCategoryTree = async (\n { categories, categoriesIds, categoryId: prodCategoryId }: SearchProduct,\n _: any,\n { clients: { search }, vtex: { platform } }: Context\n) => {\n if (!categories || !categoriesIds) {\n return []\n }\n\n const mainTreeIds = findMainTree(categoriesIds, prodCategoryId)\n\n if (platform === 'vtex') {\n return mainTreeIds.map(categoryId => search.category(Number(categoryId)))\n }\n const categoriesTree = await search.categories(mainTreeIds.length)\n const categoryMap = buildCategoryMap(categoriesTree)\n const mappedCategories = mainTreeIds\n .map(id => categoryMap[id])\n .filter(Boolean)\n\n return mappedCategories.length ? mappedCategories : null\n}\n\nexport const resolvers = {\n Product: {\n benefits: ({ productId }: SearchProduct, _: any, ctx: Context) =>\n getBenefits(productId, ctx),\n\n categoryTree: productCategoriesToCategoryTree,\n\n cacheId: ({ linkText, cacheId }: SearchProductWithCache) =>\n cacheId || linkText,\n\n clusterHighlights: ({ clusterHighlights = {} }: SearchProduct) =>\n objToNameValue('id', 'name', clusterHighlights),\n\n jsonSpecifications: (product: SearchProduct) => {\n const { Specifications = [] } = product\n const specificationsMap = Specifications.reduce(\n (acc: Record<string, string>, key: string) => {\n acc[key] = (product as any)[key]\n return acc\n },\n {}\n )\n return JSON.stringify(specificationsMap)\n },\n\n productClusters: ({ productClusters = {} }: SearchProduct) =>\n objToNameValue('id', 'name', productClusters),\n\n properties: (product: SearchProduct) =>\n map(\n (name: string) => ({ name, values: (product as any)[name] }),\n product.allSpecifications || []\n ),\n\n propertyGroups: (product: SearchProduct) => {\n const { allSpecifications = [] } = product\n const notPG = knownNotPG.concat(allSpecifications)\n return objToNameValue('name', 'values', omit(notPG, product))\n },\n\n recommendations: (product: SearchProduct) => product,\n\n description: ({ productId, description }: SearchProduct) => formatTranslatableStringV2({\n content: description,\n context: productId,\n }),\n\n metaTagDescription: ({ productId, metaTagDescription }: SearchProduct) => formatTranslatableStringV2({\n content: metaTagDescription,\n context: productId,\n }),\n\n titleTag: ({ productId, productTitle }: SearchProduct) => formatTranslatableStringV2({\n content: productTitle,\n context: productId,\n }),\n\n productName: ({ productId, productName }: SearchProduct) => formatTranslatableStringV2({\n content: productName,\n context: productId,\n }),\n\n linkText: async ({ productId, linkText }: SearchProduct, _: unknown, ctx: Context) => {\n const { clients: { messagesGraphQL }, vtex: { binding, tenant } } = ctx\n\n if (!binding || !tenant || binding.locale === tenant.locale) {\n return linkText\n }\n\n const messages = [{\n context: productId,\n content: linkText\n }]\n\n const translations = await messagesGraphQL.translate({\n to: binding.locale,\n indexedByFrom: [{\n from: tenant.locale,\n messages\n }]\n })\n\n return translations[0]\n },\n\n specificationGroups: (product: SearchProduct) => {\n const allSpecificationsGroups = propOr<[], SearchProduct, string[]>(\n [],\n 'allSpecificationsGroups',\n product\n ).concat(['allSpecifications'])\n const specificationGroups = allSpecificationsGroups.map(\n (groupName: string) => ({\n name: groupName,\n specifications: ((product as any)[groupName] || []).map(\n (name: string) => ({\n name,\n values: (product as any)[name] || [],\n })\n ),\n })\n )\n return specificationGroups || []\n },\n items: ({ items: searchItems }: SearchProduct, { filter }: ItemArg) => {\n if (filter === ItemsFilterEnum.ALL) {\n return searchItems\n }\n if (filter === ItemsFilterEnum.FIRST_AVAILABLE) {\n const firstAvailable = searchItems.find(isAvailable)\n return firstAvailable ? [firstAvailable] : [searchItems[0]]\n }\n if (filter === ItemsFilterEnum.ALL_AVAILABLE) {\n const onlyAvailable = searchItems.filter(isAvailable)\n return onlyAvailable.length > 0 ? onlyAvailable : [searchItems[0]]\n }\n return searchItems\n },\n priceRange: ({ items: searchItems }: SearchProduct) => {\n const offers = searchItems.reduce<CommertialOffer[]>(\n (acc, currentItem) => {\n for (const seller of currentItem.sellers) {\n if (isSellerAvailable(seller)) {\n acc.push(seller.commertialOffer)\n }\n }\n return acc\n },\n []\n )\n\n return { offers }\n },\n },\n OnlyProduct: {\n categoryTree: productCategoriesToCategoryTree,\n },\n}\n\n```" } ]
code_search-engine-example_7f402eb7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/discount.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop } from 'ramda'\n\nexport const resolvers = {\n Discount: {\n name: prop('<Name>k__BackingField'),\n },\n Teaser: {\n name: prop('<Name>k__BackingField'),\n conditions: prop('<Conditions>k__BackingField'),\n effects: prop('<Effects>k__BackingField'),\n },\n TeaserCondition: {\n minimumQuantity: prop('<MinimumQuantity>k__BackingField'),\n parameters: prop('<Parameters>k__BackingField'),\n },\n TeaserEffects: {\n parameters: prop('<Parameters>k__BackingField'),\n },\n TeaserValue: {\n name: prop('<Name>k__BackingField'),\n value: prop('<Value>k__BackingField'),\n }\n}\n\n```" } ]
code_search-engine-example_a8151fb1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/newURLs.test.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport * as TypeMoq from 'typemoq'\nimport { VBase, IOContext } from \"@vtex/api\"\nimport { Search } from '../../clients/search'\nimport { mountCompatibilityQuery } from './newURLs'\nimport { getCompatibilityArgs } from '.'\nimport { Clients } from '../../clients'\n\n\nconst contextMock = TypeMoq.Mock.ofType<IOContext>()\nconst categoryTreeResponseMock = TypeMoq.Mock.ofType<CategoryTreeResponse>()\nconst facetsMock = TypeMoq.Mock.ofType<SearchFacets>()\nconst vbaseTypeMock = TypeMoq.Mock.ofInstance(VBase)\nconst state = TypeMoq.Mock.ofType<State>()\nconst customContext = TypeMoq.Mock.ofType<CustomContext>()\n\ndescribe('Search new URLs dicovery', () => {\n let context: any\n\n class VBaseMock extends vbaseTypeMock.object {\n private jsonData: any\n\n public constructor() {\n super(contextMock.object)\n this.jsonData = {}\n }\n\n public getJSON = async <T>(bucket: string, file: string, nullOrUndefined?: boolean | undefined): Promise<T> => {\n if (!this.jsonData[bucket]) {\n return (nullOrUndefined ? null : {}) as T\n }\n return Promise.resolve(this.jsonData[bucket][file] as T)\n }\n\n public saveJSON = async <T>(bucket: string, file: string, data: T): Promise<void> => {\n if (!this.jsonData[bucket]) {\n this.jsonData[bucket] = {}\n }\n this.jsonData[bucket][file] = data\n }\n }\n\n const search = class SearchMock extends Search {\n private categoriesResponse: CategoryTreeResponse[]\n private categoryChildrenResponse: Record<number, Record<string, string>>\n private facetsResponse: SearchFacets\n\n public constructor(categories: CategoryTreeResponse[], categoryChildren: Record<number, Record<string, string>>, facets: SearchFacets){\n super(contextMock.object)\n this.categoriesResponse = categories\n this.categoryChildrenResponse = categoryChildren\n this.facetsResponse = facets\n }\n \n public categories = async (_: number) => {\n return Promise.resolve(this.categoriesResponse)\n }\n\n public getCategoryChildren = (id: number) => {\n return Promise.resolve(this.categoryChildrenResponse[id])\n }\n\n public facets = (_?: string) => {\n return Promise.resolve(this.facetsResponse)\n }\n }\n\n beforeEach(() => {\n // tslint:disable-next-line: max-classes-per-file\n const ClientsImpl = class ClientsMock extends Clients {\n public get vbase() {\n return this.getOrSet('vbase', VBaseMock)\n }\n }\n\n context = {\n clients: new ClientsImpl({}, contextMock.object),\n ...contextMock.object,\n ...customContext.object,\n state: {\n ...state.object,\n },\n }\n })\n\n it('Should transform /category in /category?map=c', async () => {\n const args = {\n query: 'category',\n map: ''\n }\n\n const categoryTree: CategoryTreeResponse[] = [\n {\n ...categoryTreeResponseMock.object,\n id: 1,\n name: 'category',\n hasChildren: false,\n }\n ]\n\n const facets = {\n SpecificationFilters: {},\n ...facetsMock.object\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, {}, facets)\n const result = await mountCompatibilityQuery({vbase: vbaseMock, search: searchMock, args})\n expect(result).toStrictEqual({query: 'category', map: 'c'})\n })\n\n it('Should transform /department/category/subcategory in /department/category/subcategory?map=c,c,c', async () => {\n const args = {\n query: 'department/category/subcategory',\n map: ''\n }\n\n const categoryTree: CategoryTreeResponse[] = [\n {\n ...categoryTreeResponseMock.object,\n id: 1,\n name: 'department',\n hasChildren: true,\n }\n ]\n\n const categoryChildren = {\n 1: {'2': 'category'},\n 2: {'3': 'subcategory'}\n }\n\n const facets = {\n SpecificationFilters: {},\n ...facetsMock.object\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets)\n const result = await mountCompatibilityQuery({vbase: vbaseMock, search: searchMock, args})\n expect(result).toStrictEqual({query: 'department/category/subcategory', map: 'c,c,c'})\n })\n\n it('Should transform /category/brand?map=b in /category?map=c,b', async () => {\n const args = {\n query: 'category/brand',\n map: 'b'\n }\n\n const categoryTree: CategoryTreeResponse[] = [\n {\n ...categoryTreeResponseMock.object,\n id: 1,\n name: 'category',\n hasChildren: false,\n }\n ]\n\n const categoryChildren = { 1: {} }\n\n const facets = {\n SpecificationFilters: {},\n ...facetsMock.object\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets)\n const result = await mountCompatibilityQuery({vbase: vbaseMock, search: searchMock, args})\n expect(result).toStrictEqual({query: 'category/brand', map: 'c,b'})\n })\n\n it('Should transform /collection?map=productClusterIds in /collection?map=productClusterIds', async () => {\n const args = {\n query: 'collection',\n map: 'productClusterIds'\n }\n\n const categoryTree: CategoryTreeResponse[] = []\n\n const categoryChildren = {}\n\n const facets = {\n SpecificationFilters: {},\n ...facetsMock.object\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets)\n const result = await mountCompatibilityQuery({vbase: vbaseMock, search: searchMock, args})\n expect(result).toStrictEqual({query: 'collection', map: 'productClusterIds'})\n })\n\n it('Should transform /filterxpto?map=specificationFilter_0 in /filterxpto?map=specificationFilter_0', async () => {\n const args = {\n query: 'filterxpto',\n map: 'specificationFilter_0'\n }\n\n const categoryTree: CategoryTreeResponse[] = []\n\n const categoryChildren = {}\n\n const facets = {\n SpecificationFilters: {},\n ...facetsMock.object\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets)\n const result = await mountCompatibilityQuery({vbase: vbaseMock, search: searchMock, args})\n expect(result).toStrictEqual({query: 'filterxpto', map: 'specificationFilter_0'})\n })\n\n it('Should transform /department/style_1/color_2/size_3 in /department/1/2/3?map=c,specificationFilter_1,specificationFilter_2,specificationFilter_3', async () => {\n const args = {\n query: 'department/style_1/color_2/size_3',\n map: ''\n }\n\n const categoryTree: CategoryTreeResponse[] = [\n {\n ...categoryTreeResponseMock.object,\n id: 1,\n name: 'department',\n hasChildren: false,\n }\n ]\n\n const categoryChildren = { 1: {} }\n\n const facets = {\n SpecificationFilters: {\n style: [\n {\n Name: \"1\",\n Map: \"specificationFilter_1\",\n Value: \"1\"\n },\n ],\n color: [\n {\n Name: \"2\",\n Map: \"specificationFilter_2\",\n Value: \"2\"\n },\n ],\n size: [\n {\n Name: \"3\",\n Map: \"specificationFilter_3\",\n Value: \"3\"\n },\n ]\n },\n ...facetsMock.object\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets)\n const result = await mountCompatibilityQuery({vbase: vbaseMock, search: searchMock, args})\n expect(result).toStrictEqual({query: 'department/1/2/3', map: 'c,specificationFilter_1,specificationFilter_2,specificationFilter_3'})\n })\n \n it('Should transform /department/style_1/brand?map=b in /department/style_1/brand?map=c,specificationFilter_1,b', async () => {\n const args = {\n query: 'department/style_1/brand',\n map: 'b'\n }\n\n const categoryTree: CategoryTreeResponse[] = [\n {\n ...categoryTreeResponseMock.object,\n id: 1,\n name: 'department',\n hasChildren: false,\n }\n ]\n\n const categoryChildren = { 1: {} }\n\n const facets = {\n SpecificationFilters: {\n style: [\n {\n Name: \"1\",\n Map: \"specificationFilter_1\",\n Value: \"1\"\n },\n ],\n },\n ...facetsMock.object\n }\n\n const vbaseMock = new VBaseMock()\n const searchMock = new search(categoryTree, categoryChildren, facets)\n const result = await mountCompatibilityQuery({vbase: vbaseMock, search: searchMock, args})\n expect(result).toStrictEqual({query: 'department/1/brand', map: 'c,specificationFilter_1,b'})\n })\n\n it('Should not transform urls in the format query?map=c', async () => {\n \n const argsList = [\n {\n map: 'c',\n query: 'category'\n },\n {\n map: 'specificationFilter_1',\n query: 'filtertest'\n },\n {\n map: 'c,specificationFilter_1',\n query: 'category/filtertest'\n },\n {\n map: 'specificationFilter_1,c,b',\n query: 'filtertest/category/brand'\n }\n ]\n\n for(const args of argsList){\n const result = await getCompatibilityArgs(context, args)\n expect(result).toStrictEqual(args)\n }\n })\n})\n```" } ]
code_search-engine-example_c1cecd03
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/utils.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport crypto from 'crypto'\nimport { compose, last, split, toLower, zip } from 'ramda'\nimport { Functions } from '@gocommerce/utils'\n\nimport { searchSlugify, Slugify } from '../../utils/slug'\n\nexport enum SearchCrossSellingTypes {\n whoboughtalsobought = 'whoboughtalsobought',\n similars = 'similars',\n whosawalsosaw = 'whosawalsosaw',\n whosawalsobought = 'whosawalsobought',\n accessories = 'accessories',\n suggestions = 'suggestions',\n}\n\nconst pageTypeMapping: Record<string, string> = {\n Brand: 'brand',\n Department: 'department',\n Category: 'category',\n SubCategory: 'subcategory',\n NotFound: 'search',\n FullText: 'search',\n Search: 'search',\n}\n\nconst lastSegment = compose<string, string[], string>(\n last,\n split('/')\n)\n\nexport const zipQueryAndMap = (query?: string | null, map?: string | null) => {\n const cleanQuery = query || ''\n const cleanMap = map || ''\n return zip(\n cleanQuery\n .toLowerCase()\n .split('/')\n .map(decodeURIComponent),\n cleanMap.split(',')\n )\n}\n\nexport function hashMD5(text: string) {\n const hash = crypto.createHash('md5')\n return hash.update(text).digest('hex')\n}\n\nexport function findCategoryInTree(\n tree: CategoryTreeResponse[],\n values: string[],\n index = 0\n): CategoryTreeResponse | null {\n for (const node of tree) {\n const slug = lastSegment(node.url)\n if (slug.toUpperCase() === values[index].toUpperCase()) {\n if (index === values.length - 1) {\n return node\n }\n return findCategoryInTree(node.children, values, index + 1)\n }\n }\n return null\n}\n\nexport const getBrandFromSlug = async (\n brandSlug: string,\n search: Context['clients']['search']\n) => {\n const brands = await search.brands()\n return brands.find(\n brand =>\n brand.isActive &&\n (toLower(searchSlugify(brand.name)) === brandSlug ||\n toLower(Slugify(brand.name)) === brandSlug)\n )\n}\n\ntype CategoryMap = Record<string, CategoryTreeResponse>\n\n/**\n * We are doing this because the `get category` API is not returning the values\n * for slug and href. So we get the whole category tree and get that info from\n * there instead until the Search team fixes this issue with the category API.\n */\nexport async function getCategoryInfo(\n search: Context['clients']['search'],\n id: number,\n levels: number\n) {\n const categories = await search.categories(levels)\n const mapCategories = categories.reduce(appendToMap, {}) as CategoryMap\n\n const category = mapCategories[id] || { url: '' }\n\n return category\n}\n\nexport function buildCategoryMap(categoryTree: CategoryTreeResponse[]) {\n return categoryTree.reduce(appendToMap, {}) as CategoryMap\n}\n\n/**\n * That's a recursive function to fill an object like { [categoryId]: Category }\n * It will go down the category.children appending its children and so on.\n */\nfunction appendToMap(\n mapCategories: CategoryMap,\n category: CategoryTreeResponse\n) {\n mapCategories[category.id] = category\n\n mapCategories = category.children.reduce(appendToMap, mapCategories)\n\n return mapCategories\n}\n\nexport function translatePageType(searchPageType: string): string {\n return pageTypeMapping[searchPageType] || 'search'\n}\n\nexport const searchEncodeURI = (account: string) => (str: string) => {\n if (!Functions.isGoCommerceAcc(account)) {\n return str.replace(/[%\"'.()]/g, (c: string) => {\n switch (c) {\n case '%':\n return '@perc@'\n case '\"':\n return '@quo@'\n case \"'\":\n return '@squo@'\n case '.':\n return '@dot@'\n case '(':\n return '@lpar@'\n case ')':\n return '@rpar@'\n default: {\n return c\n }\n }\n })\n }\n return str\n}\n\nexport const getMapAndPriceRangeFromSelectedFacets = (\n selectedFacets: SelectedFacet[]\n) => {\n const priceRangeIndex = selectedFacets.findIndex(\n facet => facet.key === 'priceRange'\n )\n const priceRange =\n priceRangeIndex > -1\n ? selectedFacets.splice(priceRangeIndex, 1)[0].value\n : undefined\n\n const map = selectedFacets.map(facet => facet.key).join(',')\n\n return [map, priceRange]\n}\n\n```" } ]
code_search-engine-example_03761e8d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/recommendation.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { SearchCrossSellingTypes } from './utils'\n\nexport const resolvers = {\n Recommendation: {\n buy: (\n { productId }: SearchProduct,\n _: any,\n { clients: { search } }: Context\n ) =>\n search.crossSelling(\n productId,\n SearchCrossSellingTypes.whoboughtalsobought\n ),\n\n similars: (\n { productId }: SearchProduct,\n _: any,\n { clients: { search } }: Context\n ) => search.crossSelling(productId, SearchCrossSellingTypes.similars),\n\n view: (\n { productId }: SearchProduct,\n _: any,\n { clients: { search } }: Context\n ) =>\n search.crossSelling(productId, SearchCrossSellingTypes.whosawalsosaw),\n },\n}\n\n```" } ]
code_search-engine-example_8d8faaad
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/itemMetadata.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Segment } from '@vtex/api'\nimport camelCase from 'camelcase'\nimport { both, pickBy } from 'ramda'\nimport { renameKeysWith } from '../../utils'\n\nconst isTruthy = (val?: string) => !!val\nconst isUtm = (_: any, key: string | number) => String(key).startsWith('utm')\nconst isValidUtm = both(isUtm, isTruthy)\n\ninterface Parent {\n items: SearchMetadataItem[]\n}\n\ninterface SimulationPayload {\n countryCode: string\n marketingData: Record<string, string>\n}\n\nconst getSimulationPayload = async (\n segment: Segment\n): Promise<SimulationPayload> => {\n const segmentData = await segment.getSegment()\n\n let marketingData: Record<string, string> = {}\n try {\n marketingData = renameKeysWith(\n camelCase,\n pickBy(isValidUtm, segmentData)\n ) as Record<string, string>\n } catch (e) {\n // TODO: Log to Splunk\n console.error(e)\n }\n\n return {\n countryCode: segmentData.countryCode,\n marketingData,\n }\n}\n\ntype PriceTableMap = Record<\n string,\n {\n compositionItem: CompositionItem\n simulationPayload: SimulationPayload\n items: SearchMetadataItem[]\n parent: SearchMetadataItem\n assemblyOption: AssemblyOption\n }[]\n>\n\nexport const resolvers = {\n ItemMetadata: {\n priceTable: async (\n { items }: Parent,\n _: any,\n { clients: { segment } }: Context\n ) => {\n const simulationPayload = await getSimulationPayload(segment)\n\n const itemsWithAssembly = items.filter(\n item => item.assemblyOptions.length > 0\n )\n\n const priceTableMap: PriceTableMap = itemsWithAssembly.reduce<PriceTableMap>((acc, item) => {\n for (const assemblyOption of item.assemblyOptions) {\n if (!assemblyOption.composition || !assemblyOption.composition.items) {\n continue\n }\n\n for (const compItem of assemblyOption.composition.items) {\n const currentArray = acc[compItem.priceTable] || []\n currentArray.push({\n compositionItem: compItem,\n simulationPayload,\n items: itemsWithAssembly,\n parent: item,\n assemblyOption,\n })\n acc[compItem.priceTable] = currentArray\n }\n }\n\n return acc\n }, {})\n\n return Object.entries(priceTableMap).map(\n ([priceTableName, priceTableValues]) => ({\n type: priceTableName,\n values: priceTableValues,\n })\n )\n },\n },\n}\n\n```" } ]
code_search-engine-example_58ba2ffb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/constants.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const SEARCH_URLS_BUCKET = 'newSearchURLs'\nexport const CATEGORY_TREE_ROOT_BUCKET = 'categoryTree'\nexport const CATEGORY_TREE_CHILDREN_BUCKET = 'categoryTreeChildren'\nexport const CATEGORY_TREE_ROOT_PATH = 'categoryTree.json'\nexport const FACETS_BUCKET = 'facets'\nexport const SPEC_FILTER = 'specificationFilter'\nexport const MAP_QUERY_KEY = 'map'\nexport const MAP_VALUES_SEP = ','\nexport const PATH_SEPARATOR = '/'\nexport const SPACE_REPLACER = '-'\nexport const FILTER_TITLE_SEP = '_'\nexport const CATEGORY_SEGMENT = 'c'\nexport const FULL_TEXT_SEGMENT = 'ft'\n```" } ]
code_search-engine-example_6bb3428f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/newURLs.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Search } from '../../clients/search'\nimport { VBase } from '@vtex/api'\nimport {\n SEARCH_URLS_BUCKET,\n CATEGORY_SEGMENT,\n FACETS_BUCKET,\n FULL_TEXT_SEGMENT,\n} from './constants'\nimport { CategoryTreeSegmentsFinder, CategoryIdNamePair } from '../../utils/CategoryTreeSegmentsFinder'\nimport { staleFromVBaseWhileRevalidate } from '../../utils/vbase'\nimport { searchSlugify } from '../../utils/slug'\nimport { PATH_SEPARATOR, MAP_SEPARATOR } from '../stats/constants'\n\nexport const hasFacetsBadArgs = ({ query, map }: QueryArgs) => !query || !map\n\nexport const toCompatibilityArgs = async (vbase:VBase, search: Search, args: QueryArgs): Promise<QueryArgs|undefined> => {\n const {query} = args\n if(!query){\n return\n }\n const { query: compatibilityQuery, map: compatibilityMap } = await staleFromVBaseWhileRevalidate(\n vbase, SEARCH_URLS_BUCKET, query, mountCompatibilityQuery, {vbase, search, args} )\n return { query: compatibilityQuery, map: compatibilityMap }\n}\n\nexport const mountCompatibilityQuery = async (params: {vbase: VBase, search: Search, args: any}) => {\n const {vbase, search, args} = params\n const { query, map } = args\n const querySegments = query.startsWith(PATH_SEPARATOR)? query.split(PATH_SEPARATOR).slice(1): query.split(PATH_SEPARATOR)\n\n const categoryTreeFinder = new CategoryTreeSegmentsFinder({vbase, search}, querySegments)\n const categories = await categoryTreeFinder.find()\n const facetsQuery = getFacetsQueryFromCategories(categories)\n \n const fieldsLookup = facetsQuery? await getCategoryFilters(vbase, search, facetsQuery): {}\n const mapSegments = fillCategoriesMapSegments(categories, map)\n\n const compatMapSegments = []\n const compatQuerySegments = []\n\n for(let segmentIndex = 0; segmentIndex < querySegments.length; segmentIndex++ ) {\n const querySegment = querySegments[segmentIndex]\n \n const [fieldName, fieldValue] = querySegment.split('_')\n const compatMapSegmentField = fieldsLookup[fieldName]\n \n const mapSegment = compatMapSegmentField || mapSegments.shift() || FULL_TEXT_SEGMENT\n compatMapSegments.push(mapSegment)\n compatQuerySegments.push(fieldValue || querySegment)\n }\n\n const compatibilityQuery = compatQuerySegments.join('/')\n const compatibilityMap = compatMapSegments.join(',')\n return { query: compatibilityQuery, map: compatibilityMap}\n}\n\nconst normalizeName = (name: string): string => searchSlugify(name)\n\nconst fillCategoriesMapSegments = (categories: (CategoryIdNamePair|null)[], map: string): (string|undefined)[] => {\n const mapSegments = map.split(MAP_SEPARATOR).filter(segment=> segment !== CATEGORY_SEGMENT)\n const segmentsFound = []\n\n for( const category of categories){\n if(!category){\n segmentsFound.push(mapSegments.shift())\n }else{\n segmentsFound.push(CATEGORY_SEGMENT)\n }\n }\n return [...segmentsFound, ...mapSegments]\n}\n\nconst getFacetsQueryFromCategories = (categories: (CategoryIdNamePair|null)[]) => {\n const queryArgs = categories.reduce((acc: QueryArgs, category) => {\n if(category){\n acc.query = acc.query? acc.query + PATH_SEPARATOR + category.name.toLocaleLowerCase(): category.name.toLocaleLowerCase()\n acc.map = acc.map? acc.map + MAP_SEPARATOR + CATEGORY_SEGMENT: CATEGORY_SEGMENT\n }\n return acc\n }, {query: '', map: ''} as QueryArgs)\n return !hasFacetsBadArgs(queryArgs)? `${queryArgs.query}?map=${queryArgs.map}`: null\n}\n\nconst getCategoryFilters = async (vbase: VBase, search: Search, query: string) => {\n const facets = await staleFromVBaseWhileRevalidate<SearchFacets>(\n vbase, FACETS_BUCKET, query, search.facets, query)\n return normalizedFiltersFromFacets(facets)\n}\n\nconst normalizedFiltersFromFacets = async (facets: SearchFacets) => {\n const specificationFilters = facets['SpecificationFilters']\n return Object.keys(specificationFilters).reduce((acc, filterKey) => {\n const facets = specificationFilters[filterKey]\n const normalizedFilterName = normalizeName(filterKey)\n acc[normalizedFilterName] = facets[0].Map\n return acc\n }, {} as Record<string, string>)\n}\n\n```" } ]
code_search-engine-example_d475ccd2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/itemMetadataPriceTableItem.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { isEmpty, path } from 'ramda'\nimport { getItemChoiceType, CHOICE_TYPES } from '../../utils/attachments'\n\ninterface Params {\n compositionItem: CompositionItem\n simulationPayload: {\n marketingData: Record<string, string>\n countryCode: string\n }\n items: SearchMetadataItem[]\n parent: SearchMetadataItem\n assemblyOption: AssemblyOption\n}\n\n// Generate a valid simulation list with this child, considering its a single item type\nconst getSimulationPayloadItemsForSingleFromTree = (\n parent: SearchMetadataItem,\n childId: string,\n seller: string,\n parentAssemblyBinding: string\n) => {\n return [\n { id: parent.id, quantity: 1, seller: parent.seller },\n {\n id: childId,\n seller,\n quantity: 1,\n parentItemIndex: 0,\n parentAssemblyBinding,\n },\n ]\n}\n\n// Generate a valid simulation list with this child, considering its a TOGGLE item type\nconst getSimulationPayloadItemsForToggleFromTree = (\n parent: SearchMetadataItem,\n childId: string,\n seller: string,\n assemblyOption: AssemblyOption,\n parentBasicTree: PayloadItem[]\n) => {\n const parentPayloadItem = {\n id: parent.id,\n quantity: 1,\n seller: parent.seller,\n }\n const basicChildItem = {\n id: childId,\n seller,\n quantity: 1,\n parentItemIndex: 0,\n parentAssemblyBinding: assemblyOption.id,\n }\n const siblings = parentBasicTree.filter(\n ({ parentAssemblyBinding }) => parentAssemblyBinding === assemblyOption.id\n )\n const siblingCount = siblings.length\n // See if we can add this item, considering the group max quantity\n if (siblingCount < assemblyOption.composition!.maxQuantity) {\n return [parentPayloadItem, basicChildItem]\n }\n\n // If there are siblings on the basic tree, remove it and add this child\n const brotherToBeRemoved = siblings.find(item => {\n const brotherComposition = assemblyOption.composition!.items.find(\n comp => comp.id === item.id\n )\n return brotherComposition!.minQuantity === 0\n })\n if (!brotherToBeRemoved) {\n return []\n }\n const withoutBrother = parentBasicTree.filter(\n ({ id, parentAssemblyBinding }) =>\n id !== brotherToBeRemoved.id &&\n parentAssemblyBinding !== brotherToBeRemoved.parentAssemblyBinding\n )\n return [parentPayloadItem, ...withoutBrother, basicChildItem]\n}\n\n// Generate a valid simulation list with this child, considering its a MULTIPLE item type\nconst getSimulationPayloadItemsForMultipleFromTree = (\n parent: SearchMetadataItem,\n assemblyOption: AssemblyOption,\n parentBasicTree: PayloadItem[],\n childCompositionItem: CompositionItem\n) => {\n const parentPayloadItem = {\n id: parent.id,\n quantity: 1,\n seller: parent.seller,\n }\n\n const basicItemQuantity = childCompositionItem.minQuantity || 1\n const familyMinimum = assemblyOption.composition!.minQuantity\n const basicChildItem = {\n id: childCompositionItem.id,\n seller: childCompositionItem.seller,\n quantity: basicItemQuantity,\n parentItemIndex: 0,\n parentAssemblyBinding: assemblyOption.id,\n }\n\n // Corner case that can be easily solved: when a single child can fill alone the whole group\n if (childCompositionItem.maxQuantity >= familyMinimum) {\n return [\n parentPayloadItem,\n { ...basicChildItem, quantity: familyMinimum || basicItemQuantity },\n ]\n }\n\n const siblings = parentBasicTree.filter(\n ({ parentAssemblyBinding, parentItemIndex }) =>\n parentAssemblyBinding === assemblyOption.id && parentItemIndex === 0\n )\n\n const siblingCount = siblings.reduce((sum, sib) => sum + sib.quantity, 0)\n const siblingsAllowed = assemblyOption.composition!.maxQuantity - siblingCount\n if (basicItemQuantity <= siblingsAllowed) {\n return [parentPayloadItem, ...siblings, basicChildItem]\n }\n\n let currentSiblingCount = siblingCount\n // We will iterate through the childs siblings and remove the minimum we should\n for (const brother of siblings) {\n const brotherComposition = assemblyOption.composition!.items.find(\n comp => comp.id === brother.id\n )\n const oldBrotherQuantity = brother.quantity\n brother.quantity = brotherComposition!.minQuantity\n currentSiblingCount -= oldBrotherQuantity - brotherComposition!.minQuantity\n const currentSiblingsAllowed =\n assemblyOption.composition!.maxQuantity - currentSiblingCount\n if (currentSiblingsAllowed >= basicItemQuantity) {\n // We can now break because we can add out chuld item safely\n break\n }\n }\n\n const nonEmptySiblings = siblings.filter(({ quantity }) => quantity > 0)\n return [parentPayloadItem, ...nonEmptySiblings, basicChildItem]\n}\n\nconst simulateAndGetPrice = async (\n payload: SimulationPayload,\n checkout: Context['clients']['checkout'],\n itemId: string,\n assemblyId: string\n) => {\n const simulation = await checkout.simulation(payload)\n const childInTree = simulation.items.find(\n item => itemId === item.id && assemblyId === item.parentAssemblyBinding\n )\n return childInTree ? childInTree.sellingPrice : 0\n}\n\nconst getSimulationPayloadItems = (\n assemblyOption: AssemblyOption,\n compositionItem: CompositionItem,\n parent: SearchMetadataItem,\n fatherBasicTree: PayloadItem[]\n) => {\n const assemblyType = getItemChoiceType(assemblyOption)\n\n if (assemblyType === CHOICE_TYPES.SINGLE) {\n return getSimulationPayloadItemsForSingleFromTree(\n parent,\n compositionItem.id,\n compositionItem.seller,\n assemblyOption.id\n )\n }\n if (assemblyType === CHOICE_TYPES.TOGGLE) {\n return getSimulationPayloadItemsForToggleFromTree(\n parent,\n compositionItem.id,\n compositionItem.seller,\n assemblyOption,\n fatherBasicTree\n )\n }\n return getSimulationPayloadItemsForMultipleFromTree(\n parent,\n assemblyOption,\n fatherBasicTree,\n compositionItem\n )\n}\n\nexport const resolvers = {\n PriceTableItem: {\n assemblyId: path(['assemblyOption', 'id']),\n id: path(['compositionItem', 'id']),\n price: async (\n { parent, simulationPayload, assemblyOption, compositionItem }: Params,\n _: any,\n { clients: { checkout } }: Context\n ) => {\n const { id, priceTable } = compositionItem\n const { marketingData, countryCode } = simulationPayload\n const payload = {\n country: countryCode,\n isCheckedIn: false,\n priceTables: [priceTable],\n ...(isEmpty(marketingData) ? {} : { marketingData }),\n }\n\n const parentBasicTree = [\n { id: parent.id, seller: parent.seller, quantity: 1 },\n ] as PayloadItem[]\n\n for (const fatherAssemblyOption of parent.assemblyOptions) {\n const assemblyId = fatherAssemblyOption.id\n if (!fatherAssemblyOption.composition) {\n continue\n }\n const groupMinimum = fatherAssemblyOption.composition!.minQuantity\n const itemsInitialsSum = fatherAssemblyOption.composition!.items.reduce(\n (sum, item) => sum + item.initialQuantity,\n 0\n )\n // The basic tree will not contain children of this group\n if (groupMinimum !== itemsInitialsSum) {\n continue\n }\n for (const compItem of fatherAssemblyOption.composition!.items) {\n if (compItem.initialQuantity > 0) {\n parentBasicTree.push({\n id: compItem.id,\n quantity: compItem.initialQuantity,\n seller: compItem.seller,\n parentItemIndex: 0,\n parentAssemblyBinding: assemblyId,\n })\n }\n }\n }\n\n const itemInTree = parentBasicTree.find(\n item =>\n id === item.id && assemblyOption.id === item.parentAssemblyBinding\n )\n // If item is already in tree, just simulate and return the price\n if (itemInTree) {\n return simulateAndGetPrice(\n { ...payload, items: parentBasicTree },\n checkout,\n id,\n assemblyOption.id\n )\n }\n\n // If not in tree, include it, then simulate and get price\n const newSimulationPayloadItems = getSimulationPayloadItems(\n assemblyOption,\n compositionItem,\n parent,\n parentBasicTree\n )\n return simulateAndGetPrice(\n { ...payload, items: newSimulationPayloadItems },\n checkout,\n id,\n assemblyOption.id\n )\n },\n },\n}\n\n```" } ]
code_search-engine-example_669f404f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/index.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { NotFoundError, UserInputError, createMessagesLoader } from '@vtex/api'\nimport { head, isEmpty, isNil, test, pathOr } from 'ramda'\n\nimport { resolvers as assemblyOptionResolvers } from './assemblyOption'\nimport { resolvers as autocompleteResolvers } from './autocomplete'\nimport { resolvers as brandResolvers } from './brand'\nimport { resolvers as categoryResolvers } from './category'\nimport { resolvers as discountResolvers } from './discount'\nimport { resolvers as itemMetadataResolvers } from './itemMetadata'\nimport { resolvers as itemMetadataPriceTableItemResolvers } from './itemMetadataPriceTableItem'\nimport { resolvers as itemMetadataUnitResolvers } from './itemMetadataUnit'\nimport { resolvers as offerResolvers } from './offer'\nimport { resolvers as productResolvers } from './product'\nimport { resolvers as recommendationResolvers } from './recommendation'\nimport { resolvers as skuResolvers } from './sku'\nimport { resolvers as productPriceRangeResolvers } from './productPriceRange'\nimport { getSearchMetaData } from './modules/metadata'\nimport {\n SearchCrossSellingTypes,\n getMapAndPriceRangeFromSelectedFacets,\n} from './utils'\nimport { toCompatibilityArgs } from './newURLs'\nimport { PATH_SEPARATOR, MAP_VALUES_SEP } from './constants'\nimport {\n biggyAttributesToVtexFilters,\n buildAttributePath,\n convertOrderBy,\n buildBreadcrumb,\n} from '../../commons/compatibility-layer'\nimport { productsCatalog, productsBiggy } from '../../commons/products'\n\ninterface ProductIndentifier {\n field: 'id' | 'slug' | 'ean' | 'reference' | 'sku'\n value: string\n}\n\ninterface ProductArgs {\n slug?: string\n identifier?: ProductIndentifier\n}\n\nenum CrossSellingInput {\n view = 'view',\n buy = 'buy',\n similars = 'similars',\n viewAndBought = 'viewAndBought',\n suggestions = 'suggestions',\n accessories = 'accessories',\n}\n\ninterface ProductRecommendationArg {\n identifier?: ProductIndentifier\n type?: CrossSellingInput\n}\n\ninterface ProductsByIdentifierArgs {\n field: 'id' | 'ean' | 'reference' | 'sku'\n values: string[]\n}\n\nconst inputToSearchCrossSelling = {\n [CrossSellingInput.buy]: SearchCrossSellingTypes.whoboughtalsobought,\n [CrossSellingInput.view]: SearchCrossSellingTypes.whosawalsosaw,\n [CrossSellingInput.similars]: SearchCrossSellingTypes.similars,\n [CrossSellingInput.viewAndBought]: SearchCrossSellingTypes.whosawalsobought,\n [CrossSellingInput.accessories]: SearchCrossSellingTypes.accessories,\n [CrossSellingInput.suggestions]: SearchCrossSellingTypes.suggestions,\n}\n\n/**\n * There is an URL pattern in VTEX where the number of mapSegments doesn't match the number of querySegments. This function deals with these cases.\n * Since this should not be a search concern, this function will be removed soon.\n *\n * @param {Context} ctx\n * @param {QueryArgs} args\n * @returns\n */\nconst getCompatibilityArgsFromSelectedFacets = async (\n ctx: Context,\n args: QueryArgs\n) => {\n const { selectedFacets, query } = args\n\n if (!selectedFacets || selectedFacets.length === 0 || !query) {\n return args\n }\n\n const [map, priceRange] = getMapAndPriceRangeFromSelectedFacets([\n ...selectedFacets,\n ])\n\n args.map = map\n\n if (isLegacySearchFormat({ query: args.query, map: args.map })) {\n return args\n }\n\n const compatibilityArgs = (await getCompatibilityArgs(ctx, args)) as QueryArgs\n\n const mapSegments = compatibilityArgs.map!.split(MAP_VALUES_SEP)\n const querySegments = compatibilityArgs.query!.split(PATH_SEPARATOR)\n\n args.selectedFacets = mapSegments.map((map, index) => {\n return {\n key: map,\n value: querySegments[index],\n }\n })\n\n if (priceRange) {\n args.selectedFacets.push({\n key: 'priceRange',\n value: priceRange,\n })\n }\n\n return args\n}\n\nconst translateToStoreDefaultLanguage = async (\n ctx: Context,\n term: string\n): Promise<string> => {\n const {\n clients,\n state,\n vtex: { locale: from, tenant },\n } = ctx\n const { locale: to } = tenant!\n\n if (!from || from === to) {\n return term\n }\n\n if (!state.messages) {\n state.messages = createMessagesLoader(clients, to)\n }\n\n return state.messages!.load({\n from,\n content: term,\n })\n}\n\nconst noop = () => {}\n\n// Does prefetching and warms up cache for up to the 10 first elements of a search, so if user clicks on product page\nconst searchFirstElements = (\n products: SearchProduct[],\n from: number | null = 0,\n search: Context['clients']['search']\n) => {\n if (from !== 0 || from == null) {\n // We do not want this for pages other than the first\n return\n }\n products\n .slice(0, Math.min(10, products.length))\n .forEach(product =>\n search.productById(product.productId, false).catch(noop)\n )\n}\n\nexport const fieldResolvers = {\n ...autocompleteResolvers,\n ...brandResolvers,\n ...categoryResolvers,\n ...itemMetadataResolvers,\n ...itemMetadataUnitResolvers,\n ...itemMetadataPriceTableItemResolvers,\n ...offerResolvers,\n ...discountResolvers,\n ...productResolvers,\n ...recommendationResolvers,\n ...skuResolvers,\n ...assemblyOptionResolvers,\n ...productPriceRangeResolvers,\n}\n\nexport const getCompatibilityArgs = async <T extends QueryArgs>(\n ctx: Context,\n args: T\n) => {\n const {\n clients: { vbase, search },\n } = ctx\n const compatArgs = isLegacySearchFormat(args)\n ? args\n : await toCompatibilityArgs(vbase, search, args)\n return compatArgs ? { ...args, ...compatArgs } : args\n}\n\n// Legacy search format is our search with path?map=c,c,specificationFilter\n// Where it has specificationFilters and all segments in path are mapped in `map` querystring\nconst isLegacySearchFormat = ({\n query,\n map,\n}: {\n query: string\n map?: string\n}) => {\n if (!map) {\n return false\n }\n return map.split(MAP_VALUES_SEP).length === query.split(PATH_SEPARATOR).length\n}\n\nconst isValidProductIdentifier = (identifier: ProductIndentifier | undefined) =>\n !!identifier && !isNil(identifier.value) && !isEmpty(identifier.value)\n\nexport const queries = {\n autocomplete: async (\n _: any,\n args: { maxRows: number; searchTerm?: string },\n ctx: Context\n ) => {\n const {\n clients: { search },\n } = ctx\n\n if (!args.searchTerm) {\n throw new UserInputError('No search term provided')\n }\n const translatedTerm = await translateToStoreDefaultLanguage(\n ctx,\n args.searchTerm\n )\n const { itemsReturned } = await search.autocomplete({\n maxRows: args.maxRows,\n searchTerm: translatedTerm,\n })\n return {\n cacheId: args.searchTerm,\n itemsReturned,\n }\n },\n facets: async (_: any, args: FacetsInput, ctx: any) => {\n args = (await getCompatibilityArgsFromSelectedFacets(\n ctx,\n args\n )) as FacetsInput\n\n let { fullText } = args\n\n if (fullText) {\n fullText = await translateToStoreDefaultLanguage(ctx, args.fullText!)\n }\n\n const { customSearchEngine } = ctx.clients\n const { segment } = ctx.vtex\n\n const biggyArgs = {\n attributePath: buildAttributePath(args.selectedFacets),\n query: args.fullText,\n tradePolicy: segment && segment.channel,\n }\n\n const result = await customSearchEngine.facets(biggyArgs)\n\n return {\n facets: result.attributes\n ? biggyAttributesToVtexFilters(result.attributes)\n : [],\n queryArgs: {\n query: args.query,\n selectedFacets: args.selectedFacets,\n },\n }\n },\n\n product: async (_: any, rawArgs: ProductArgs, ctx: Context) => {\n const {\n clients: { search },\n } = ctx\n\n const args =\n rawArgs && isValidProductIdentifier(rawArgs.identifier)\n ? rawArgs\n : { identifier: { field: 'slug', value: rawArgs.slug! } }\n\n if (!args.identifier) {\n throw new UserInputError('No product identifier provided')\n }\n\n const { field, value } = args.identifier\n let products = [] as SearchProduct[]\n\n switch (field) {\n case 'id':\n products = await search.productById(value)\n break\n case 'slug':\n products = await search.product(value)\n break\n case 'ean':\n products = await search.productByEan(value)\n break\n case 'reference':\n products = await search.productByReference(value)\n break\n case 'sku':\n products = await search.productBySku([value])\n break\n }\n\n if (products.length > 0) {\n return head(products)\n }\n\n throw new NotFoundError(\n `No product was found with requested ${field} ${JSON.stringify(args)}`\n )\n },\n\n products: async (_: any, args: SearchArgs, ctx: Context) => {\n const {\n clients: { search },\n } = ctx\n const queryTerm = args.query\n if (queryTerm == null || test(/[?&[\\]=]/, queryTerm)) {\n throw new UserInputError(\n `The query term contains invalid characters. query=${queryTerm}`\n )\n }\n\n if (args.to && args.to > 2500) {\n throw new UserInputError(\n `The maximum value allowed for the 'to' argument is 2500`\n )\n }\n const products = await search.products(args)\n searchFirstElements(products, args.from, ctx.clients.search)\n return products\n },\n\n productsByIdentifier: async (\n _: any,\n args: ProductsByIdentifierArgs,\n ctx: Context\n ) => {\n const {\n clients: { search },\n } = ctx\n\n let products = [] as SearchProduct[]\n const { field, values } = args\n\n switch (field) {\n case 'id':\n products = await search.productsById(values)\n break\n case 'ean':\n products = await search.productsByEan(values)\n break\n case 'reference':\n products = await search.productsByReference(values)\n break\n case 'sku':\n products = await search.productBySku(values)\n break\n }\n\n if (products.length > 0) {\n return products\n }\n\n throw new NotFoundError(`No products were found with requested ${field}`)\n },\n\n productSearch: async (_: any, args: ProductSearchInput, ctx: any) => {\n args = (await getCompatibilityArgsFromSelectedFacets(\n ctx,\n args\n )) as ProductSearchInput\n\n const { customSearchEngine } = ctx.clients\n const { segment } = ctx.vtex\n const { from, to, selectedFacets, fullText, fuzzy, operator } = args\n\n const count = to - from + 1\n const page = Math.round((to + 1) / count)\n\n const biggyArgs = {\n page,\n count,\n fuzzy,\n operator,\n attributePath: buildAttributePath(selectedFacets),\n query: fullText,\n tradePolicy: segment && segment.channel,\n sort: convertOrderBy(args.orderBy),\n }\n\n const result = await customSearchEngine.productSearch(biggyArgs)\n\n const productResolver = args.productOriginVtex\n ? productsCatalog\n : productsBiggy\n const convertedProducts = productResolver(result, ctx)\n\n return {\n products: convertedProducts,\n recordsFiltered: result.total,\n breadcrumb: buildBreadcrumb(selectedFacets),\n suggestion: result.suggestion,\n correction: result.correction,\n fuzzy: result.fuzzy,\n operator: result.operator,\n banners: result.banners,\n }\n },\n\n productRecommendations: async (\n _: any,\n { identifier, type }: ProductRecommendationArg,\n ctx: Context\n ) => {\n if (identifier == null || type == null) {\n throw new UserInputError('Wrong input provided')\n }\n const searchType = inputToSearchCrossSelling[type]\n let productId = identifier.value\n if (identifier.field !== 'id') {\n const product = await queries.product(_, { identifier }, ctx)\n productId = product!.productId\n }\n\n const products = await ctx.clients.search.crossSelling(\n productId,\n searchType\n )\n\n searchFirstElements(products, 0, ctx.clients.search)\n // We add a custom cacheId because these products are not exactly like the other products from search apis.\n // Each product is basically a SKU and you may have two products in response with same ID but each one representing a SKU.\n return products.map(product => {\n const skuId = pathOr('', ['items', '0', 'itemId'], product)\n return {\n ...product,\n cacheId: `${product.linkText}-${skuId}`,\n }\n })\n },\n\n searchMetadata: async (_: any, args: SearchMetadataArgs, ctx: Context) => {\n const queryTerm = args.query\n if (queryTerm == null || test(/[?&[\\]=]/, queryTerm)) {\n throw new UserInputError(\n `The query term contains invalid characters. query=${queryTerm}`\n )\n }\n\n if (args.selectedFacets) {\n const [map] = getMapAndPriceRangeFromSelectedFacets(args.selectedFacets)\n args.map = map\n }\n\n const query = await translateToStoreDefaultLanguage(ctx, args.query || '')\n const translatedArgs = {\n ...args,\n query,\n }\n const compatibilityArgs = await getCompatibilityArgs<SearchArgs>(\n ctx,\n translatedArgs as SearchArgs\n )\n return getSearchMetaData(_, compatibilityArgs, ctx)\n },\n topSearches: () => null,\n searchSuggestions: () => null,\n productSuggestions:() => null,\n}\n\n```" } ]
code_search-engine-example_cf9d746a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/assemblyOption.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const resolvers = {\n AssemblyOption: {\n inputValues: (\n { inputValues }: AssemblyOption,\n ): InputValue[] => {\n return Object.keys(inputValues).reduce<InputValue[]>((acc, label) => {\n const inputValue = inputValues[label]\n const type = defineInputValueType(inputValue)\n\n const maxLength = type === InputValueType.TEXT\n ? inputValue.maximumNumberOfCharacters : undefined\n\n const domain = type === InputValueType.OPTIONS\n ? inputValue.domain\n : undefined\n\n const defaultValue = type === InputValueType.OPTIONS\n ? inputValue.domain[0]\n : type === InputValueType.BOOLEAN\n ? stringToBoolean(inputValue.domain[0])\n : ''\n\n acc.push({\n label,\n type,\n maxLength,\n defaultValue,\n domain,\n })\n\n return acc\n }, [])\n }\n },\n}\n\nfunction defineInputValueType(inputValue: RawInputValue): InputValueType {\n const domain = inputValue.domain\n\n // If domain is something like ['true', 'false'] or ['false', 'true']\n if (\n domain && domain.length === 2 &&\n domain.indexOf('true') !== -1 && domain.indexOf('false') !== -1\n ) {\n return InputValueType.BOOLEAN\n }\n\n // If domain is something like ['Sans serif', 'Roman']\n if (domain && domain.length > 0) {\n return InputValueType.OPTIONS\n }\n\n return InputValueType.TEXT\n}\n\nfunction stringToBoolean(value: string) {\n return value === 'true'\n ? true\n : false\n}\n\n\ninterface InputValue {\n label: string\n maxLength?: number\n type: InputValueType\n defaultValue: string|boolean\n domain?: string[]\n}\n\nenum InputValueType {\n TEXT = 'TEXT',\n BOOLEAN = 'BOOLEAN',\n OPTIONS = 'OPTIONS',\n}\n```" } ]
code_search-engine-example_31db2a31
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/offer.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { propOr } from 'ramda'\n\nconst InstallmentsCriteria = {\n ALL: 'ALL',\n MAX: 'MAX',\n MIN: 'MIN',\n MAX_WITHOUT_INTEREST: 'MAX_WITHOUT_INTEREST',\n MAX_WITH_INTEREST: 'MAX_WITH_INTEREST',\n}\n\nconst gte = (a: number, b: number) => a > b\nconst lte = (a: number, b: number) => a < b\n\nexport const resolvers = {\n Offer: {\n Installments: (\n { Installments }: CommertialOffer,\n { criteria, rates }: { criteria?: string; rates?: boolean }\n ) => {\n if (criteria === InstallmentsCriteria.ALL || Installments.length === 0) {\n return Installments\n }\n\n /** TODO: Transforms arguments for backwards-compatibility. Should be cleaned up in the future */\n if (criteria === InstallmentsCriteria.MAX_WITH_INTEREST || criteria === InstallmentsCriteria.MAX_WITHOUT_INTEREST){\n rates = criteria === InstallmentsCriteria.MAX_WITHOUT_INTEREST\n criteria = InstallmentsCriteria.MAX\n }\n\n const filteredInstallments = !rates\n ? Installments\n : Installments.filter(({ InterestRate }) => !InterestRate)\n\n const compareFunc = criteria === InstallmentsCriteria.MAX ? gte : lte\n const value = filteredInstallments.reduce(\n (acc, currentValue) =>\n compareFunc(\n currentValue.NumberOfInstallments,\n acc.NumberOfInstallments\n )\n ? currentValue\n : acc,\n filteredInstallments[0]\n )\n return [value]\n },\n teasers: propOr([], 'Teasers'),\n giftSkuIds: propOr([], 'GiftSkuIds'),\n gifts: async ({ GiftSkuIds }: CommertialOffer, _: any, ctx: Context) => {\n if (GiftSkuIds.length === 0) {\n return []\n }\n\n const catalogGiftProducts = await ctx.clients.search.productBySku(GiftSkuIds).catch(() => null)\n\n if (!catalogGiftProducts || catalogGiftProducts.length === 0) {\n return []\n }\n\n const giftProducts = GiftSkuIds.map(skuId => {\n let giftSku = null\n let giftProduct = null\n\n for (const currGiftProduct of catalogGiftProducts) {\n const currGiftSku = currGiftProduct.items.find(item => item.itemId === skuId)\n if (currGiftSku) {\n giftSku = currGiftSku\n giftProduct = currGiftProduct\n break\n }\n }\n if (!giftProduct || !giftSku) {\n return null\n }\n const {\n productName,\n brand,\n linkText,\n description,\n } = giftProduct\n return {\n productName,\n brand,\n linkText,\n description,\n skuName: giftSku?.nameComplete ?? '',\n images: giftSku?.images.map(({ imageLabel, imageUrl, imageText }) => ({\n imageUrl,\n imageLabel,\n imageText,\n })) ?? [],\n }\n })\n const filteredGiftProducts = giftProducts.filter(Boolean)\n\n return filteredGiftProducts\n },\n discountHighlights: propOr([], 'DiscountHighLight'),\n spotPrice: (offer: CommertialOffer) => {\n const sellingPrice = offer.Price\n const spotPrice: number | undefined = offer.Installments.find(({NumberOfInstallments, Value}) => {\n return (NumberOfInstallments === 1 && Value < sellingPrice)\n })?.Value;\n return spotPrice || sellingPrice\n },\n taxPercentage: () => 0 // NOTE: We do not have offer.Tax info\n },\n}\n\n```" } ]
code_search-engine-example_43072aba
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/productPriceRange.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Root {\n offers: CommertialOffer[]\n}\n\nconst getMaxAndMinForAttribute = (\n offers: CommertialOffer[],\n attribute: 'Price' | 'ListPrice'\n) => {\n return offers.reduce(\n (acc, currentOffer) => {\n const highPrice =\n currentOffer[attribute] > acc.highPrice\n ? currentOffer[attribute]\n : acc.highPrice\n const lowPrice =\n currentOffer[attribute] < acc.lowPrice\n ? currentOffer[attribute]\n : acc.lowPrice\n return { highPrice, lowPrice }\n },\n { highPrice: 0, lowPrice: Infinity }\n )\n}\n\nexport const resolvers = {\n ProductPriceRange: {\n sellingPrice: ({ offers }: Root) => {\n return getMaxAndMinForAttribute(offers, 'Price')\n },\n listPrice: ({ offers }: Root) => {\n return getMaxAndMinForAttribute(offers, 'ListPrice')\n },\n },\n PriceRange: {\n lowPrice: ({ lowPrice }: any) => lowPrice !== Infinity ? lowPrice : null\n }\n}\n\n```" } ]
code_search-engine-example_440b2482
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/productPriceRange.test.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { resolvers } from './product'\nimport { resolvers as productPriceResolvers } from './productPriceRange'\nimport { mockContext } from '../../__mocks__/helpers'\nimport { productPriceRange } from '../../__mocks__/productPriceRange'\nimport { clone } from 'ramda'\n\ndescribe('tests related to ProductPriceRange type', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n mockContext.vtex.platform = 'vtex'\n })\n\n test('gets correct value for product with many skus and prices', () => {\n const { offers } = resolvers.Product.priceRange(\n productPriceRange as any\n ) as { offers: CommertialOffer[] }\n\n const sellingPrice = productPriceResolvers.ProductPriceRange.sellingPrice({\n offers,\n })\n expect(sellingPrice).toMatchObject({ highPrice: 100, lowPrice: 20 })\n\n const listPrice = productPriceResolvers.ProductPriceRange.listPrice({\n offers,\n })\n\n expect(listPrice).toMatchObject({ highPrice: 150, lowPrice: 30 })\n })\n test('works for products with many sellers', () => {\n const cloneProduct = clone(productPriceRange)\n cloneProduct.items[0].sellers.push({\n sellerId: '99',\n commertialOffer: {\n Price: 10,\n ListPrice: 160,\n AvailableQuantity: 10,\n },\n } as any)\n\n const { offers } = resolvers.Product.priceRange(cloneProduct as any) as {\n offers: CommertialOffer[]\n }\n const sellingPrice = productPriceResolvers.ProductPriceRange.sellingPrice({\n offers,\n })\n expect(sellingPrice).toMatchObject({ highPrice: 100, lowPrice: 10 })\n\n const listPrice = productPriceResolvers.ProductPriceRange.listPrice({\n offers,\n })\n\n expect(listPrice).toMatchObject({ highPrice: 160, lowPrice: 30 })\n })\n\n test('ignores sellers with no availability', () => {\n const cloneProduct = clone(productPriceRange)\n cloneProduct.items[0].sellers.push({\n sellerId: '99',\n commertialOffer: {\n Price: 10,\n ListPrice: 10,\n AvailableQuantity: 0,\n },\n } as any)\n\n const { offers } = resolvers.Product.priceRange(cloneProduct as any) as {\n offers: CommertialOffer[]\n }\n const sellingPrice = productPriceResolvers.ProductPriceRange.sellingPrice({\n offers,\n })\n expect(sellingPrice).toMatchObject({ highPrice: 100, lowPrice: 20 })\n\n const listPrice = productPriceResolvers.ProductPriceRange.listPrice({\n offers,\n })\n\n expect(listPrice).toMatchObject({ highPrice: 150, lowPrice: 30 })\n })\n})\n\n```" } ]
code_search-engine-example_f969f175
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/product.test.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { resolvers } from './product'\nimport { mockContext } from '../../__mocks__/helpers'\nimport { getProduct } from '../../__mocks__/product'\n\ndescribe('tests related to product resolver', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n mockContext.vtex.platform = 'vtex'\n })\n describe('categoryTree resolver', () => {\n test('ensure that VTEX account never calls the category tree search API', async () => {\n const searchProduct = getProduct()\n await resolvers.Product.categoryTree(\n searchProduct as any,\n {},\n mockContext as any\n )\n expect(mockContext.clients.search.category).toBeCalledTimes(2)\n expect(mockContext.clients.search.categories).toBeCalledTimes(0)\n })\n\n test('get correct main category tree for product with only one tree', async () => {\n const searchProduct = getProduct()\n await resolvers.Product.categoryTree(\n searchProduct as any,\n {},\n mockContext as any\n )\n expect(mockContext.clients.search.category).toBeCalledTimes(2)\n expect(mockContext.clients.search.category.mock.calls[0][0]).toBe(25)\n expect(mockContext.clients.search.category.mock.calls[1][0]).toBe(10)\n })\n\n test('get correct main category tree for product with more than one tree', async () => {\n const categoriesIds = [\n '/101/101003/101003009/',\n '/101/101003/',\n '/101/',\n '/101/101019/101019004/',\n '/101/101019/',\n '/103/103023/103023003/',\n '/103/103023/',\n '/103/',\n ]\n const searchProduct = getProduct({\n categoriesIds,\n categoryId: '101003009',\n })\n\n await resolvers.Product.categoryTree(\n searchProduct as any,\n {},\n mockContext as any\n )\n expect(mockContext.clients.search.category).toBeCalledTimes(3)\n expect(mockContext.clients.search.category.mock.calls[0][0]).toBe(101)\n expect(mockContext.clients.search.category.mock.calls[1][0]).toBe(101003)\n expect(mockContext.clients.search.category.mock.calls[2][0]).toBe(\n 101003009\n )\n })\n\n test('ensure that GC account calls the category tree API ', async () => {\n const searchProduct = getProduct()\n mockContext.vtex.platform = 'gocommerce'\n mockContext.clients.search.categories.mockImplementation(() => [\n {\n id: '10',\n name: 'a',\n url: 'a',\n children: [],\n },\n {\n id: '25',\n name: 'a',\n url: 'a',\n children: [],\n },\n ])\n const result = await resolvers.Product.categoryTree(\n searchProduct as any,\n {},\n mockContext as any\n )\n expect(mockContext.clients.search.category).toBeCalledTimes(0)\n expect(mockContext.clients.search.categories).toBeCalledTimes(1)\n expect(mockContext.clients.search.categories.mock.calls[0][0]).toBe(2) //ensure maximum level was correct\n expect(result!.length).toBe(2)\n })\n\n test('if categoryId does not match any id in categoriesIds, find biggest tree', async () => {\n const searchProduct = getProduct()\n searchProduct.categoryId = '1'\n searchProduct.categoriesIds = ['/2064927469/', '/2064927469/630877787/']\n await resolvers.Product.categoryTree(\n searchProduct as any,\n {},\n mockContext as any\n )\n expect(mockContext.clients.search.category).toBeCalledTimes(2)\n expect(mockContext.clients.search.category.mock.calls[0][0]).toBe(\n 2064927469\n )\n expect(mockContext.clients.search.category.mock.calls[1][0]).toBe(\n 630877787\n )\n })\n })\n\n test('if custom cacheId is given, it should be returned', async () => {\n const searchProduct = getProduct()\n const cacheAsSlug = await resolvers.Product.cacheId(searchProduct as any)\n expect(cacheAsSlug).toBe(searchProduct.linkText)\n\n searchProduct.cacheId = 'CUSTOM_CACHE'\n\n const customCache = await resolvers.Product.cacheId(searchProduct as any)\n expect(customCache).toBe('CUSTOM_CACHE')\n })\n\n test('productClusters should be properly formatted', () => {\n const product = getProduct()\n product.productClusters = {\n \"140\": 'Casual Footwear',\n \"195\": 'All products',\n \"201\": \"Third\"\n }\n const result = resolvers.Product.productClusters(product as any)\n expect(result).toMatchObject([\n { id: '140', name: 'Casual Footwear' },\n { id: '195', name: 'All products' },\n { id: '201', name: 'Third' }\n ])\n })\n\n test('productClusters should not break if value is null', () => {\n const product = getProduct()\n product.productClusters = null as any\n const result = resolvers.Product.productClusters(product as any)\n expect(result).toMatchObject([])\n })\n\n test('clusterHighlights should be properly formatted', () => {\n const product = getProduct()\n product.clusterHighlights = {\n \"140\": 'Casual Footwear',\n \"195\": 'All products',\n \"201\": \"Third\"\n }\n const result = resolvers.Product.clusterHighlights(product as any)\n expect(result).toMatchObject([\n { id: '140', name: 'Casual Footwear' },\n { id: '195', name: 'All products' },\n { id: '201', name: 'Third' }\n ])\n })\n\n test('clusterHighlights should not break if value is null', () => {\n const product = getProduct()\n product.clusterHighlights = null as any\n const result = resolvers.Product.clusterHighlights(product as any)\n expect(result).toMatchObject([])\n })\n\n test('clusterHighlights should be properly formatted', () => {\n const product = getProduct()\n product.clusterHighlights = {\n \"140\": 'Casual Footwear',\n \"195\": 'All products',\n \"201\": \"Third\"\n }\n const result = resolvers.Product.clusterHighlights(product as any)\n expect(result).toMatchObject([\n { id: '140', name: 'Casual Footwear' },\n { id: '195', name: 'All products' },\n { id: '201', name: 'Third' }\n ])\n })\n\n test('clusterHighlights should not break if value is null', () => {\n const product = getProduct()\n product.clusterHighlights = null as any\n const result = resolvers.Product.clusterHighlights(product as any)\n expect(result).toMatchObject([])\n })\n})\n\n```" } ]
code_search-engine-example_8b048e21
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/productSearch.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { path } from 'ramda'\nimport { IOResponse } from '@vtex/api'\nimport { Functions } from '@gocommerce/utils'\nimport { zipQueryAndMap } from './utils'\n\ninterface ProductSearchParent {\n productsRaw: IOResponse<SearchProduct[]>\n translatedArgs: SearchArgs\n searchMetaData: {\n titleTag: string | null\n metaTagDescription: string | null\n }\n}\n\nexport const resolvers = {\n ProductSearch: {\n titleTag: path(['searchMetaData', 'titleTag']),\n metaTagDescription: path(['searchMetaData', 'metaTagDescription']),\n recordsFiltered: ({ productsRaw }: ProductSearchParent) => {\n const {\n headers: { resources },\n } = productsRaw\n const quantity = resources.split('/')[1]\n return parseInt(quantity, 10)\n },\n products: path(['productsRaw', 'data']),\n breadcrumb: async (\n { translatedArgs, productsRaw: { data: products } }: ProductSearchParent,\n _: any,\n { vtex: { account }, clients: { search } }: Context\n ) => {\n const query = translatedArgs?.query || ''\n const map = translatedArgs?.map || ''\n const queryAndMap = zipQueryAndMap(\n translatedArgs?.query,\n translatedArgs?.map\n )\n const categoriesSearched = queryAndMap\n .filter(([_, m]) => m === 'c')\n .map(([q]) => q)\n const categoriesCount = map.split(',').filter(m => m === 'c').length\n const categories =\n !!categoriesCount && Functions.isGoCommerceAcc(account)\n ? await search.categories(categoriesCount)\n : []\n\n const queryArray = query.split('/')\n const mapArray = map.split(',')\n return queryAndMap.map(\n ([queryUnit, mapUnit]: [string, string], index: number) => ({\n queryUnit,\n mapUnit,\n index,\n queryArray,\n mapArray,\n categories,\n categoriesSearched,\n products,\n })\n )\n },\n },\n}\n\n```" } ]
code_search-engine-example_8c11982f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/sku.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { find, head, map, replace, slice } from 'ramda'\n\nexport const resolvers = {\n SKU: {\n attachments: ({ attachments = [] }: SearchItem) =>\n map(\n (attachment: any) => ({\n ...attachment,\n domainValues: JSON.parse(attachment.domainValues),\n }),\n attachments\n ),\n\n images: (\n { images = [] }: SearchItem,\n { quantity }: { quantity: number }\n ) =>\n map(\n image => ({\n cacheId: image.imageId,\n ...image,\n imageUrl: replace('http://', 'https://', image.imageUrl),\n }),\n quantity > 0 ? slice(0, quantity, images) : images\n ),\n\n kitItems: (\n { kitItems }: SearchItem,\n _: any,\n { clients: { search } }: Context\n ) =>\n !kitItems\n ? []\n : kitItems.map(async kitItem => {\n const products = await search.productBySku([kitItem.itemId])\n const { items: skus = [], ...product } = head(products) || {}\n const sku = find(({ itemId }) => itemId === kitItem.itemId, skus)\n return { ...kitItem, product, sku }\n }),\n\n variations: (sku: SearchItem) =>\n sku &&\n map(\n (name: string) => ({ name, values: (sku as any)[name] }),\n sku.variations || []\n ),\n\n videos: ({ Videos }: SearchItem) =>\n map(\n (video: string) => ({\n videoUrl: video,\n }),\n Videos\n ),\n },\n}\n\n```" } ]
code_search-engine-example_b548129a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/benefits/index.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { flatten, indexOf, path } from 'ramda'\n\nconst SKU_SEPARATOR = ','\nconst CATALOG = 'Catalog'\nconst DEFAULT_SELLER = '1'\nconst DEFAULT_QUANTITY = 1\n\nexport const fieldResolvers = {\n Benefit: {\n items: async (benefit: any, _: any, { clients: { search } }: Context) => {\n const { teaserType, conditions, effects } = benefit\n\n if (teaserType === CATALOG) {\n const {\n parameters: conditionsParameters,\n minimumQuantity = DEFAULT_QUANTITY,\n } = conditions\n\n const { parameters: effectsParameters } = effects\n\n const items = await Promise.all(\n conditionsParameters.map(\n async (conditionsParameter: any, index: any) => {\n const skuIds: string[] = conditionsParameter.value.split(\n SKU_SEPARATOR\n )\n const discount = effectsParameters[index].value\n const products = await search.productBySku(skuIds)\n\n return products.map((product: any) => {\n const benefitSKUIds: any = []\n\n product.items.map((item: any) => {\n if (indexOf(item.itemId, skuIds) > -1) {\n benefitSKUIds.push(item.itemId)\n }\n })\n\n return {\n benefitProduct: product,\n benefitSKUIds,\n discount,\n minQuantity: minimumQuantity,\n }\n })\n }\n )\n )\n return flatten(items)\n }\n return\n },\n },\n}\n\nexport const getBenefits = async (\n itemId: string,\n { clients: { checkout } }: Context\n) => {\n const requestBody = {\n items: [\n {\n id: itemId,\n quantity: DEFAULT_QUANTITY,\n seller: DEFAULT_SELLER,\n },\n ],\n }\n const benefitsData = await checkout.simulation(requestBody)\n return path(['ratesAndBenefitsData', 'teaser'], benefitsData) || []\n}\n\n```" } ]
code_search-engine-example_b25101c2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/stats/searchURLsCount.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { VBase } from '@vtex/api'\nimport { VBASE_BUCKET, URL_COUNT_FILE_PATH } from './constants'\nimport { SearchStatsUrlCount } from './searchStats'\n\nexport enum SORT {\n ASC = 'ASC',\n DESC = 'DESC',\n}\n\nexport const searchURLsCount = async (\n vbase: VBase,\n limit: number,\n sort: SORT = SORT.DESC\n) => {\n const data = (await vbase.getJSON<SearchStatsUrlCount>(\n VBASE_BUCKET,\n URL_COUNT_FILE_PATH,\n true\n )) as SearchStatsUrlCount\n let comparator = urlsCountDESCComparator\n\n if (sort === SORT.ASC) {\n comparator = urlsCountASCComparator\n }\n\n return (\n (data &&\n Object.entries(data.searchUrlCount)\n .sort(comparator)\n .slice(0, limit)\n .map(searchUrlStat => {\n return { path: searchUrlStat[0], count: searchUrlStat[1] }\n })) ||\n []\n )\n}\n\nconst urlsCountASCComparator = (\n urlStatsA: [string, number],\n urlStatsB: [string, number]\n) => {\n return urlStatsA[1] - urlStatsB[1]\n}\n\nconst urlsCountDESCComparator = (\n urlStatsA: [string, number],\n urlStatsB: [string, number]\n) => {\n return urlStatsB[1] - urlStatsA[1]\n}\n\n```" } ]
code_search-engine-example_711801cd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/stats/searchStats.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n PATH_SEPARATOR,\n MAP_QUERY_PARAM,\n MAP_SEPARATOR,\n VBASE_BUCKET,\n URL_COUNT_FILE_PATH,\n INDEXING_UPDATE_FREQUENCY,\n INDEXING_EVENT_ROUTE_NAME,\n} from './constants'\n\nexport interface SearchStatsUrlCount {\n updatedCount: number\n searchUrlCount: Record<string, number>\n}\n\nexport const count = async (ctx: Context, args: SearchArgs) => {\n const {\n clients: { vbase },\n } = ctx\n\n const searchURLPath = `${PATH_SEPARATOR}${args.query}?${MAP_QUERY_PARAM}=${args.map}`\n const pathSegments = args.query && args.query.split(PATH_SEPARATOR)\n const mapSegments = args.map && args.map.split(MAP_SEPARATOR)\n\n if (pathSegments && mapSegments && pathSegments.length === mapSegments.length) {\n const data = ((await vbase.getJSON<SearchStatsUrlCount>(\n VBASE_BUCKET,\n URL_COUNT_FILE_PATH,\n true\n )) || { updatedCount: 0, searchUrlCount: {} }) as SearchStatsUrlCount\n\n data.searchUrlCount[searchURLPath] = (data.searchUrlCount[searchURLPath] || 0) + 1\n data.updatedCount = data.updatedCount + 1\n if (data.updatedCount === INDEXING_UPDATE_FREQUENCY) {\n data.updatedCount = 0\n sendIndexSearchUrlsEvent(ctx)\n }\n\n vbase.saveJSON<SearchStatsUrlCount>(VBASE_BUCKET, URL_COUNT_FILE_PATH, data)\n }\n}\n\nconst sendIndexSearchUrlsEvent = async (ctx: Context) => {\n const { clients: { events }, vtex: { locale, tenant, binding } } = ctx\n events.sendEvent('', INDEXING_EVENT_ROUTE_NAME, {locale, tenant, binding})\n}\n```" } ]
code_search-engine-example_54e62692
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/stats/constants.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const VBASE_BUCKET = 'searchStats'\nexport const URL_COUNT_FILE_PATH = 'searchUrlsCount'\n\nexport const INDEXING_UPDATE_FREQUENCY = 500\nexport const INDEXING_EVENT_ROUTE_NAME = 'searchUrlsCountIndex'\n\nexport const MAP_QUERY_PARAM = 'map'\nexport const PATH_SEPARATOR = '/'\nexport const MAP_SEPARATOR = ','\n```" } ]
code_search-engine-example_56a4324a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/stats/index.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { searchURLsCount, SORT } from \"./searchURLsCount\"\n\nexport const queries = {\n searchURLsCount: async (\n _: any,\n args: { limit: number, sort?: SORT },\n ctx: Context\n ) => {\n const { clients: { vbase } } = ctx\n const count = searchURLsCount(vbase, args.limit, args.sort)\n return count\n },\n}\n\n```" } ]
code_search-engine-example_59562477
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of search-engine-example/node/resolvers/search/modules/metadata.ts from the search-engine-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n tail,\n head,\n compose,\n equals,\n prop,\n join,\n map,\n filter,\n findLastIndex,\n path,\n split,\n toLower,\n reverse,\n complement,\n isNil,\n} from 'ramda'\nimport { Functions } from '@gocommerce/utils'\n\nimport { zipQueryAndMap, findCategoryInTree, getBrandFromSlug } from '../utils'\nimport { toTitleCase } from '../../../utils/string'\n\ntype TupleString = [string, string]\n\nconst isTupleMap = compose<TupleString, string, boolean>(\n equals('c'),\n prop('1')\n)\n\nconst getLastCategoryIndex = findLastIndex(isTupleMap)\n\nconst categoriesOnlyQuery = compose<\n TupleString[],\n TupleString[],\n string[],\n string\n>(\n join('/'),\n map(prop('0')),\n filter(isTupleMap)\n)\n\nconst getAndParsePagetype = async (path: string, ctx: Context) => {\n const pagetype = await ctx.clients.search.pageType(path).catch(() => null)\n if (!pagetype) {\n return emptyTitleTag\n }\n return {\n titleTag: pagetype.title || pagetype.name,\n metaTagDescription: pagetype.metaTagDescription,\n }\n}\n\nconst getCategoryMetadata = async (\n { map, query }: SearchMetadataArgs,\n ctx: Context\n): Promise<SearchMetadata> => {\n const {\n vtex: { account },\n clients: { search },\n } = ctx\n const queryAndMap = zipQueryAndMap(query, map)\n const cleanQuery = categoriesOnlyQuery(queryAndMap)\n\n if (Functions.isGoCommerceAcc(account)) {\n // GoCommerce does not have pagetype query implemented yet\n const category =\n findCategoryInTree(\n await search.categories(cleanQuery.split('/').length),\n cleanQuery.split('/')\n ) || {}\n return {\n metaTagDescription: path(['MetaTagDescription'], category),\n titleTag: path(['Title'], category) || path(['Name'], category),\n }\n }\n\n return getAndParsePagetype(cleanQuery, ctx)\n}\n\nconst getBrandMetadata = async (\n query: SearchMetadataArgs['query'],\n ctx: Context\n): Promise<SearchMetadata> => {\n const {\n vtex: { account },\n clients: { search },\n } = ctx\n const cleanQuery = head(split('/', query || '')) || ''\n\n if (Functions.isGoCommerceAcc(account)) {\n const brand = (await getBrandFromSlug(toLower(cleanQuery), search)) || {}\n return {\n metaTagDescription: path(['metaTagDescription'], brand),\n titleTag: path(['title'], brand) || path(['name'], brand),\n }\n }\n return getAndParsePagetype(cleanQuery, ctx)\n}\n\nexport const getSpecificationFilterName = (name: string) => {\n return toTitleCase(decodeURI(name))\n}\n\nconst getPrimaryMetadata = (\n args: SearchMetadataArgs,\n ctx: Context\n): Promise<SearchMetadata> | SearchMetadata => {\n const map = args.map || ''\n const firstMap = head(map.split(','))\n if (firstMap === 'c') {\n return getCategoryMetadata(args, ctx)\n }\n if (firstMap === 'b') {\n return getBrandMetadata(args.query, ctx)\n }\n if (firstMap && firstMap.includes('specificationFilter')) {\n const cleanQuery = args.query || ''\n const name = head(cleanQuery.split('/')) || ''\n return {\n titleTag: getSpecificationFilterName(name),\n metaTagDescription: null,\n }\n }\n if (firstMap === 'ft') {\n const cleanQuery = args.query || ''\n const term = head(cleanQuery.split('/')) || ''\n return {\n titleTag: decodeURI(term),\n metaTagDescription: null,\n }\n }\n return emptyTitleTag\n}\n\nconst getNameForRemainingMaps = async (\n remainingTuples: [string, string][],\n ctx: Context\n) => {\n const {\n vtex: { account },\n clients: { search },\n } = ctx\n const lastCategoryIndex = getLastCategoryIndex(remainingTuples)\n const isGC = Functions.isGoCommerceAcc(account)\n const names = await Promise.all(\n remainingTuples.map(async ([query, map], index) => {\n if (map === 'c' && index === lastCategoryIndex && !isGC) {\n const cleanQuery = categoriesOnlyQuery(remainingTuples)\n const pagetype = await search.pageType(cleanQuery).catch(() => null)\n if (pagetype) {\n return pagetype.name\n }\n }\n if (map === 'b' && !isGC) {\n const brand = await search.pageType(decodeURI(query)).catch(() => null)\n if (brand) {\n return brand.name\n }\n }\n if (map.includes('specificationFilter')) {\n return getSpecificationFilterName(query)\n }\n return null\n })\n )\n return names\n}\n\nexport const emptyTitleTag = {\n titleTag: null,\n metaTagDescription: null,\n}\n\ntype StringNull = string | null | undefined\n\nconst isNotNil = complement(isNil)\nconst joinNames = compose<StringNull[], string[], string[], string>(\n join(' - '),\n reverse,\n filter(isNotNil) as any\n)\n\n/**\n * Get metadata of category/brand APIs\n *\n * @param _\n * @param args\n * @param ctx\n */\nexport const getSearchMetaData = async (\n _: any,\n args: SearchMetadataArgs,\n ctx: Context\n) => {\n const queryAndMap = zipQueryAndMap(args.query, args.map)\n if (queryAndMap.length === 0) {\n return emptyTitleTag\n }\n\n const isFirstCategory = queryAndMap[0][1] === 'c'\n const tailTuples = tail(queryAndMap)\n\n const validTuples = tailTuples.filter(\n ([_, m]) =>\n m === 'b' ||\n m.includes('specificationFilter') ||\n (m === 'c' && !isFirstCategory)\n )\n const [metadata, otherNames] = await Promise.all([\n getPrimaryMetadata(args, ctx),\n getNameForRemainingMaps(validTuples, ctx),\n ])\n\n return {\n titleTag: joinNames([metadata.titleTag, ...otherNames]),\n metaTagDescription: metadata.metaTagDescription,\n }\n}\n\n```" } ]
code_vtex-logger-react_d3dafde2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vtex-logger-react/messages/pt.json from the vtex-logger-react VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/test\": \"teste\",\n \"store/test\": \"teste\"\n}\n\n```" } ]
code_vtex-logger-react_0658051f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vtex-logger-react/messages/en.json from the vtex-logger-react VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/test\": \"test\",\n \"store/test\": \"test\"\n}\n\n```" } ]
code_vtex-logger-react_0e6dd22e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vtex-logger-react/messages/es.json from the vtex-logger-react VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/test\": \"teste\",\n \"store/test\": \"teste\"\n}\n\n```" } ]
code_vtex-logger-react_2baae67e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vtex-logger-react/docs/README.md from the vtex-logger-react VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# VTEX Logger React\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\n## ⚠️ Maintenance ⚠️\n*Starting June 1st 2023, this application will no longer be maintained by VTEX.*\n\n---\n\nThe VTEX Logger React app will help to make log entries in the VTEX IO Logging Service on React Apps.\n\n## Configuration\n\n1. Add the `vtex-logger-react` app as a dependency in you theme's `manifest.json` file:\n\n```diff\n \"dependencies\": {\n+ \"vtex.vtex-logger-react\": \"1.x\"\n }\n```\n\nNow, you can import any of the exported components and hooks from the app. Here's an example of a component that use the `useLog` hook from the `useLoggerVtex` to log some relevant info:\n\n```tsx\n// Notice that this is TypeScript, and this code should be in a .tsx file\nimport React, { FC } from 'react'\nimport { useLoggerVtex } from 'vtex.vtex-logger-react'\nimport { Button } from 'vtex.styleguide'\n\nconst MyComponent: FC = () => {\n const { useLog } = useLoggerVtex()\n const exampleDetail = {\n id: '1',\n name: 'Test Name',\n description: 'Test Description',\n price: '100',\n quantity: '1',\n brand: 'Test Brand',\n category: 'Test Category',\n }\n\n const handleClickLog = async () => {\n const appName = 'my-app'\n const message = 'Test log'\n await useLog({ app: appName, message: message, detail: exampleDetail })\n }\n\n return (\n <Fragment>\n <Button onClick={handleClickLog} />\n </Fragment>\n )\n}\n\nexport default MyComponent\n```\n\n:warning: _Be sure to run `vtex setup --typings` in your project to install the correct TypeScript types exported by this app._\n\n### Hooks\n\n#### `useLog`\n\nThis is the most useful export from this app. The `useLog` hook can be used to log messages to the VTEX IO Logging Service.\n\nIt needs to recieve:\n\n- `app`: The app name that want to log the message.\n- `message`: The message to be logged.\n- `detail`: An object with the details of the log. It can be any JSON-serializable object.\n\n```ts\ninterface VtexLoggerProps {\n app: string\n message: string\n detail: any\n}\n```\n\nYou should expect an object that looks like this:\n\n```json\n{\n \"logger\": {\n \"status\": 200\n }\n}\n```\n\nAlways check the `status` property to know if the log was successful.\n\n:information*source: \\_To have the full type definition in your development environment, be sure to run `vtex setup` in your project to install all TypeScript types exported by this app.*\n\n<!-- DOCS-IGNORE:start -->\n\n## Review the Logs (Splunk)\n\nWith this query you can retrieve the logs from Splunk, filtering by `app`:\n\n```\nindex=io_vtex_logs app=\"vtex.vtex-logger-graphql@0.2.0\" account={account} workspace={workspace} | spath \"data.app\" | search \"data.app\"={app}\n```\n\nExample:\n\n```\nindex=io_vtex_logs app=\"vtex.vtex-logger-graphql@0.2.0\" account=gbonacchi workspace=customstockexport | spath \"data.app\" | search \"data.app\"=\"my-app\"\n```\n\n![image](https://user-images.githubusercontent.com/55905671/146546432-2a1df845-5d46-4f5d-8ba5-049fed2b0efc.png)\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n <tr>\n <td align=\"center\"><a href=\"https://github.com/germanBonacchi\"><img src=\"https://avatars.githubusercontent.com/u/55905671?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Germán Bonacchi</b></sub></a><br /><a href=\"https://github.com/vtex-apps/vtex-logger-react/commits?author=germanBonacchi\" title=\"Code\">💻</a></td>\n <td align=\"center\"><a href=\"https://github.com/tomymehdi\"><img src=\"https://avatars.githubusercontent.com/u/774112?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Tomás Alfredo Mehdi</b></sub></a><br /><a href=\"https://github.com/vtex-apps/vtex-logger-react/commits?author=tomymehdi\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n\n<!-- markdownlint-restore -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```" } ]
code_vtex-logger-react_c093325a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vtex-logger-react/react/useLoggerVtex.ts from the vtex-logger-react VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { useMutation } from 'react-apollo'\n\nimport logger from './graphql/logger.gql'\n\ninterface VtexLoggerProps {\n app: string\n message: string\n detail: any\n}\n\nconst useLoggerVtex = () => {\n const [loggerMutation] = useMutation(logger)\n\n const useLog = async ({ app, message, detail }: VtexLoggerProps) => {\n const loggerResponse = await loggerMutation({\n variables: { app, message, detail: JSON.stringify(detail) },\n })\n\n return loggerResponse\n }\n\n return { useLog }\n}\n\nexport default useLoggerVtex\n\n```" } ]
code_vtex-logger-react_9a6843f8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vtex-logger-react/react/package.json from the vtex-logger-react VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"CHANGE_ME\",\n \"version\": \"1.0.2\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.3/public/@types/vtex.render-runtime\",\n \"vtex.vtex-logger-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.vtex-logger-graphql@0.2.0/public/@types/vtex.vtex-logger-graphql\"\n }\n}\n\n```" } ]
code_vtex-logger-react_ff21fe31
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vtex-logger-react/react/typings/gql.d.ts from the vtex-logger-react VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n import { DocumentNode } from 'graphql'\n\n const Schema: DocumentNode\n\n export default Schema\n}\n\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const schema: DocumentNode\n\n export default Schema\n}\n\n```" } ]
code_vtex-logger-react_f4cb8237
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vtex-logger-react/react/typings/css.d.ts from the vtex-logger-react VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n type Styles = {\n [selector: string]: string\n }\n\n const styles: Styles\n\n export default styles\n}\n\n```" } ]
code_vtex-logger-react_589614ba
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vtex-logger-react/react/graphql/logger.gql from the vtex-logger-react VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation logger($app: String, $message: String, $detail: String) {\n logger(app: $app, message: $message, detail: $detail)\n @context(provider: \"vtex.vtex-logger-graphql\") {\n status\n }\n}\n\n```" } ]
code_cross-device-cart_97f1c654
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/messages/pt.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/crossCart.challenge.cta\": \"Faça\",\n \"store/crossCart.challenge.text\": \"Parece que você deixou alguns itens em outro dispositivo. ¿Quer recuperá-los?\",\n \"store/crossCart.toast.success\": \"Itens adicionados com sucesso ao seu carrinho\",\n \"store/crossCart.toast.error\": \"Ocorreu um erro ao adicionar seus itens\"\n}\n\n```" } ]
code_cross-device-cart_de21e87a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/messages/en.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/crossCart.challenge.cta\": \"Do it\",\n \"store/crossCart.challenge.text\": \"It seems you left your cart in another device. Do you want to recover it?\",\n \"store/crossCart.toast.success\": \"Your last cart has been successfully added\",\n \"store/crossCart.toast.error\": \"An error occurred while retrieving your cart\",\n \"admin/cross-device-cart.title\": \"Cross Device Cart\",\n \"admin/cross-device-cart.subtitle\": \"App Settings\",\n \"admin/cross-device-cart.error\": \"There was a problem loading the application settings\",\n \"admin/cross-device-cart.automatic-toggle-automatic\": \"Automatic\",\n \"admin/cross-device-cart.automatic-toggle-manual\": \"Manual\",\n \"admin/cross-device-cart.automatic-toggle-help-text\": \"Toggle between Automatic and Manual mode\",\n \"admin/cross-device-cart.automatic-toggle-explanation\": \"When the 'Automatic' mode is selected the user will not be prompted to take any action. If 'Manual' mode is selected the user will need to confirm what they want to do with the items that were previously in the cart.\",\n \"admin/cross-device-cart.strategy-explanation.replace\": \"Replace all items on current cart with the items on the saved Cart.\",\n \"admin/cross-device-cart.strategy-explanation.combine\": \"Combine items in the current cart with the saved Cart, adding items quantities.\",\n \"admin/cross-device-cart.strategy-explanation.add\": \"Add missing items from the current cart to the saved Cart, doesn't add duplicate quantities.\"\n}\n\n```" } ]
code_cross-device-cart_f8df15e5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/messages/ca.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/crossCart.challenge.cta\": \"Recuperar\",\n \"store/crossCart.challenge.text\": \"Sembla que has deixat productes a la cistella d'un altre dispositiu. Vols recuperar-los?\",\n \"store/crossCart.toast.success\": \"Els productes s'han afegit a la cistella\",\n \"store/crossCart.toast.error\": \"Hi ha hagut un error a l'afegir els productes\"\n}\n\n```" } ]
code_cross-device-cart_7f01bd6c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/messages/context.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/crossCart.challenge.cta\": \"Challenge's call to action\",\n \"store/crossCart.challenge.text\": \"Description of service provided\",\n \"store/crossCart.toast.success\": \"Toast message for added items\",\n \"store/crossCart.toast.error\": \"Toast message for error while adding items\",\n \"admin/cross-device-cart.title\": \"Admin panel title\",\n \"admin/cross-device-cart.subtitle\": \"Admin panel subtitle\",\n \"admin/cross-device-cart.error\": \"Alert on error fetching the app settings\",\n \"admin/cross-device-cart.automatic-toggle-automatic\": \"Automatic toggle label when toggle is on\",\n \"admin/cross-device-cart.automatic-toggle-manual\": \"Automatic toggle label when toggle is off\",\n \"admin/cross-device-cart.automatic-toggle-help-text\": \"Automatic toggle help text\",\n \"admin/cross-device-cart.automatic-toggle-explanation\": \"Automatic toggle modes explanation\",\n \"admin/cross-device-cart.strategy-explanation.replace\": \"Replace strategy explanation\",\n \"admin/cross-device-cart.strategy-explanation.combine\": \"Combine strategy explanation\",\n \"admin/cross-device-cart.strategy-explanation.add\": \"Add strategy explanation\"\n}\n\n```" } ]
code_cross-device-cart_c3967194
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/messages/es.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/crossCart.challenge.cta\": \"Hazlo\",\n \"store/crossCart.challenge.text\": \"Parece que has dejado un carrito en otro dispositivo. ¿Quieres recuperarlo?\",\n \"store/crossCart.toast.success\": \"Tu ultimo carrito ha sido recuperado\",\n \"store/crossCart.toast.error\": \"Un error ocurrio al recuperar tu carrito\",\n \"admin/cross-device-cart.title\": \"Cross Device Cart\",\n \"admin/cross-device-cart.subtitle\": \"Configuración de la aplicación\",\n \"admin/cross-device-cart.error\": \"Ha ocurrido un problema cargando la configuración de la aplicación\",\n \"admin/cross-device-cart.automatic-toggle-automatic\": \"Automático\",\n \"admin/cross-device-cart.automatic-toggle-manual\": \"Manual\",\n \"admin/cross-device-cart.automatic-toggle-help-text\": \"Elija entre el modo Automático o Manual para el cross device cart.\",\n \"admin/cross-device-cart.automatic-toggle-explanation\": \"Cuando se selecciona el modo 'Automático' no se le pedirá al usuario que realice ninguna acción. Si se selecciona el modo 'Manual' el usuario deberá confirmar qué quiere hacer con los artículos que estaban previamente en el carrito.\"\n}\n\n```" } ]
code_cross-device-cart_f8393825
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/admin/navigation.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"section\": \"marketplace\",\n \"titleId\": \"admin/cross-device-cart.title\",\n \"path\": \"/admin/cross-device-cart\"\n}\n\n```" } ]
code_cross-device-cart_7ac24620
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/admin/routes.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin.app.cross-device-cart\": {\n \"component\": \"AdminPanel\",\n \"path\": \"/admin/app/cross-device-cart\"\n }\n}\n\n```" } ]
code_cross-device-cart_819f5da4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/docs/README.md from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/cross-device-cart) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# CROSS DEVICE CART\n\n## ⚠️ Maintenance ⚠️\n*Starting June 1st 2023, this application will no longer be maintained by VTEX.*\n\n---\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[![All Contributors](https://img.shields.io/badge/all_contributors-2-orange.svg?style=flat-square)](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nThe main feature users are looking for is to keep an up-to-date shopping cart through different devices; one of the most important experiences of a truly unified commerce.\n\nTo do so, this app was created to enable `logged in` users to retrieve their cart from their last session.\n\n## Configuration\n\n1. Install the app and then import it to your theme's peer dependencies in `manifest.json`,\n\n```json\n \"peerDependencies\": {\n // ...\n \"vtex.cross-device-cart\": \"1.x\"\n }\n```\n\n2. Add the `cross-device-cart` block as a children of your store header, desktop and mobile, for i.e:\n\n ```diff\n \"header-layout.desktop\": {\n \"children\": [\n + \"cross-device-cart\",\n \"flex-layout.row#1-desktop\",\n \"flex-layout.row#2-desktop\",\n \"flex-layout.row#3-desktop\",\n \"sticky-layout#4-desktop\"\n ]\n },\n \"header-layout.mobile\": {\n \"children\": [\n + \"cross-device-cart\",\n \"flex-layout.row#1-mobile\",\n \"sticky-layout#2-mobile\"\n ]\n },\n ```\n\n3. (Optional) You can tailor the default experience by accesing the admin app settings. \n By default, the app handles the replacement automatically. But it you set it to manual, a challenge block will be rendered as an action bar, for the user to interact with.\n\n## Customization\n\n| CSS Handles |\n| --------------- |\n| `actionBar` |\n| `challengeText` |\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```" } ]
code_cross-device-cart_715e34b7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/graphql/schema.graphql from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Query {\n \"\"\"\n Retrieves a cross cart OrderForm ID. Will return NULL if no reference was stored.\n \"\"\"\n getSavedCart(userId: String!, nullOnEmpty: Boolean, userType: String): String\n @cacheControl(scope: PUBLIC, maxAge: ZERO)\n\n \"\"\"\n Retrieve app settings\n \"\"\"\n getAppSettings: CrossDeviceCartSettings\n @cacheControl(scope: PUBLIC, maxAge: SHORT)\n}\n\ntype Mutation {\n \"\"\"\n Stores an OrderForm ID for a specific user, as a cross cart reference.\n \"\"\"\n saveCurrentCart(userId: String!, orderFormId: String, userType: String): String\n \"\"\"\n Replaces current cart with a saved cart. Optionally, you can request that both list of items be merged.\n \"\"\"\n replaceCart(\n savedCart: String!\n currentCart: String!\n strategy: Strategy!\n userType: String\n ): OrderForm\n\n \"\"\"\n Save app settings\n \"\"\"\n saveAppSettings(settings: SaveSettings): Boolean\n}\n\n```" } ]
code_cross-device-cart_e18134d3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/service.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 512,\n \"ttl\": 60,\n \"timeout\": 50,\n \"minReplicas\": 2,\n \"maxReplicas\": 12,\n \"cpu\": {\n \"type\": \"shared\",\n \"value\": 80,\n \"scalingPercentage\": 95\n },\n \"events\": {\n \"updateOnCreatedOrder\": {\n \"sender\": \"vtex.orders-broadcast\",\n \"topics\": [\"order-created\"]\n }\n }\n}\n\n```" } ]
code_cross-device-cart_db15cfaa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/package.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"@vtex/api\": \"6.47.0\",\n \"@vtex/clients\": \"^2.17.0\",\n \"cookie\": \"^0.4.2\"\n },\n \"devDependencies\": {\n \"@types/cookie\": \"^0.3.2\",\n \"@vtex/api\": \"6.47.0\",\n \"@vtex/test-tools\": \"vtex/test-tools\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"typescript\": \"3.9.7\",\n \"vtex.checkout-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-graphql@0.67.1/public/@types/vtex.checkout-graphql\",\n \"vtex.cross-device-cart\": \"https://vtexcrossdevice--cristianc.myvtex.com/_v/private/typings/linked/v1/vtex.cross-device-cart@1.4.9+build1719434975/public/@types/vtex.cross-device-cart\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.device-detector\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.device-detector@0.2.6/public/@types/vtex.device-detector\",\n \"vtex.order-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.12.0/public/@types/vtex.order-manager\",\n \"vtex.pixel-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-manager@1.9.0/public/@types/vtex.pixel-manager\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@7.45.0/public/@types/vtex.render-runtime\",\n \"vtex.session-client\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.session-client@1.0.2/public/@types/vtex.session-client\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.9/public/@types/vtex.styleguide\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'\"\n },\n \"version\": \"1.5.0\"\n}\n\n```" } ]
code_cross-device-cart_4d3be8e4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/index.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Service, ParamsContext, RecorderState } from '@vtex/api'\n\nimport clients, { Clients } from './clients'\nimport { queries, mutations } from './resolvers'\nimport { updateSavedCartReference } from './events'\n\nexport default new Service<Clients, RecorderState, ParamsContext>({\n clients,\n events: {\n updateOnCreatedOrder: updateSavedCartReference,\n },\n graphql: {\n resolvers: {\n Query: {\n ...queries,\n },\n Mutation: {\n ...mutations,\n },\n },\n },\n})\n\n```" } ]
code_cross-device-cart_6a289596
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/react/index.tsx from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { SessionWrapper as CrossCartDeviceBlock } from './components/SessionWrapper'\n\nexport default CrossCartDeviceBlock\n\n```" } ]
code_cross-device-cart_96f3d2f3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/react/AdminPanel.tsx from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { AdminPanel } from './components/admin/AdminPanel'\n\nexport default AdminPanel\n\n```" } ]
code_cross-device-cart_49b05e0b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/react/package.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"cross-device-cart\",\n \"version\": \"1.5.0\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\",\n \"axios\": \"^0.21.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.checkout-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-graphql@0.67.1/public/@types/vtex.checkout-graphql\",\n \"vtex.cross-device-cart\": \"https://vtexcrossdevice--cristianc.myvtex.com/_v/private/typings/linked/v1/vtex.cross-device-cart@1.4.9+build1719434975/public/@types/vtex.cross-device-cart\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.device-detector\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.device-detector@0.2.6/public/@types/vtex.device-detector\",\n \"vtex.order-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.12.0/public/@types/vtex.order-manager\",\n \"vtex.pixel-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-manager@1.9.0/public/@types/vtex.pixel-manager\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.134.2/public/@types/vtex.render-runtime\",\n \"vtex.session-client\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.session-client@1.0.2/public/@types/vtex.session-client\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.9/public/@types/vtex.styleguide\"\n }\n}\n\n```" } ]
code_cross-device-cart_dd16a01b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/store/interfaces.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"cross-device-cart\": {\n \"component\": \"index\"\n }\n}\n\n```" } ]
code_cross-device-cart_a198c950
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/public/metadata/messages/es-AR.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Cross Device Cart\",\n \"headline\": \"Permita que sus clientes registrados recuperen artículos de un carrito desde otro dispositivo\",\n \"overview\": \"La principal característica que buscan los usuarios es mantener un carrito de compras actualizado a través de diferentes dispositivos; una de las experiencias más importantes de un comercio verdaderamente unificado.\\\\\\\\n\\\\\\\\nPara logralo, esta aplicación permite a los usuarios registrados recuperar los artículos de su última sesión.\",\n \"features\": [\n \"Recupera artículos dejados en otro dispositivo o sesión\",\n \"Permite que el cliente decida cómo integrar esos artículos\",\n \"Se puede activar automáticamente, o manualmente, a través de una interfaz en la tienda\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_cross-device-cart_f8dd7323
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/public/metadata/messages/pt-BR.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Cross Device Cart\",\n \"headline\": \"Deixe seus clientes logados recuperarem itens do carrinho de compras de outro dispositivo\",\n \"overview\": \"A principal característica que os usuários procuram é manter um carrinho de compras atualizado em diferentes dispositivos; uma das experiências mais importantes de um comércio verdadeiramente unificado.\\\\\\\\n\\\\\\\\nEste aplicativo permite que usuários logados recuperem seus itens de sua última sessão.\",\n \"features\": [\n \"Recupera itens deixados em outro dispositivo ou sessão\",\n \"Permite ao cliente decidir como integrar esses itens\",\n \"Pode ser acionado automaticamente ou manualmente, por meio de uma interface de loja\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_cross-device-cart_9c074089
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/public/metadata/messages/en-US.json from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Cross Device Cart\",\n \"headline\": \"Let your logged in customers retrieve shopping cart items from another device\",\n \"overview\": \"The main feature users are looking for is to keep an up-to-date shopping cart through different devices; one of the most important experiences of a truly unified commerce.\\\\\\\\n\\\\\\\\nTo do so, this app enables logged in users to retrieve their items from their last session.\",\n \"features\": [\n \"Retrieves items left on another device or session\",\n \"Allows the customer to decide how to integrate those items\",\n \"Can be automatically triggered, or manually, via a store front interface\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_cross-device-cart_73ef9d1f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/graphql/types/global.graphql from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nscalar InputValues\n\nenum Strategy {\n REPLACE\n COMBINE\n ADD\n}\n\ntype CrossDeviceCartSettings {\n isAutomatic: Boolean\n strategy: Strategy\n}\n\ninput SaveSettings {\n isAutomatic: Boolean\n strategy: Strategy\n}\n\n\"\"\"\n We don't actually care what subfields are returned as this is used mainly\nby the setOrderForm callback; used to update the storefront context\n\"\"\"\nscalar OrderForm\n\n```" } ]
code_cross-device-cart_c81e2253
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/clients/hub.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext, RequestConfig } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nimport { statusToError } from '../utils'\n\nexport default class RequestHub extends JanusClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n ...options?.headers,\n VtexIdclientAutCookie:\n context.storeUserAuthToken ?? context.adminUserAuthToken ?? '',\n },\n })\n }\n\n /**\n * This request removes all items from a given cart, leaving it empty\n *\n * @func clearCart\n * @public\n * @param {string} orderFormId OrderForm ID\n * @see {@link https://developers.vtex.com/vtex-rest-api/reference/shopping-cart#removeallitems-1}\n */\n public clearCart = (orderFormId: string) =>\n this.post(this.routes.clearCart(orderFormId), {})\n\n protected get = <T>(url: string, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n }\n\n return this.http\n .get<T>(url, config)\n .catch((err) => statusToError(err)) as Promise<T>\n }\n\n protected post = async <T>(\n url: string,\n data?: any,\n config: RequestConfig = {}\n ) => {\n config.headers = {\n ...config.headers,\n }\n\n return this.http\n .post<T>(url, data, config)\n .catch((err) => statusToError(err)) as Promise<T>\n }\n\n private get routes() {\n return {\n clearCart: (orderFormId: string) =>\n `/api/checkout/pub/orderForm/${orderFormId}/items/removeAll`,\n }\n }\n}\n\n```" } ]
code_cross-device-cart_b39b9e1a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/clients/index.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n ClientsConfig,\n EventContext,\n IOClients,\n LRUCache,\n ServiceContext,\n} from '@vtex/api'\nimport { OMS } from '@vtex/clients'\n\nimport RequestHub from './hub'\nimport CheckoutIO from './checkout'\n\nexport class Clients extends IOClients {\n public get checkoutIO() {\n return this.getOrSet('checkoutIO', CheckoutIO)\n }\n\n public get requestHub() {\n return this.getOrSet('requestHub', RequestHub)\n }\n\n public get oms() {\n return this.getOrSet('oms', OMS)\n }\n}\n\ndeclare global {\n type Context = ServiceContext<Clients>\n\n interface StatusChangeContext extends EventContext<Clients> {\n body: {\n domain: string\n orderId: string\n currentState: string\n lastState: string\n currentChangeDate: string\n lastChangeDate: string\n userType: string\n }\n }\n}\n\nconst TIMEOUT_MS = 5000\nconst memoryCache = new LRUCache<string, any>({ max: 5000 })\n\nmetrics.trackCache('xcart', memoryCache)\n\nconst clients: ClientsConfig<Clients> = {\n implementation: Clients,\n options: {\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n concurrency: 2,\n memoryCache,\n },\n },\n}\n\nexport default clients\n\n```" } ]
code_cross-device-cart_080d8a02
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/constants/index.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const APP_NAME = 'vtex.cross-device-cart'\nexport const BUCKET = 'cross_device_cart'\nexport const SETTINGS_PATH = 'app_settings'\nexport const DEFAULT_SETTINGS = {\n isAutomatic: true,\n strategy: 'REPLACE',\n} as const\n\n```" } ]
code_cross-device-cart_6d05b6f0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/typings/global.d.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ntype Scalars = import('vtex.checkout-graphql').Scalars\ntype AssemblyOptionType = import('vtex.checkout-graphql').AssemblyOptionType\n\ninterface ReplaceCartVariables {\n savedCart: Scalars['ID']\n currentCart: Scalars['ID']\n strategy: Strategy\n userType: string\n}\n\ninterface PartialOrderFormItems {\n orderForm: { items: PartialItem[] }\n}\n\ninterface PartialOrderForm {\n value: number\n totalizers: {\n id: string\n name: string\n value: number\n }\n items: PartialItem[]\n}\n\ninterface PartialItem {\n id: number\n index?: number\n quantity: number\n seller: string\n uniqueId: string\n options?: AssemblyOptionInput[]\n}\n\ninterface Order {\n origin: 'Marketplace' | 'Fulfillment'\n paymentData: any\n orderId: string\n affiliateId: string\n totals: any\n coupon: string\n items: any\n marketingData?: any\n storePreferencesData?: any\n clientProfileData: ClientProfileData\n orderFormId: string\n}\n\ninterface ClientProfileData {\n userProfileId: string\n}\n\ninterface CurrentCartProps {\n userId: string\n crossCartData: CrossCartData\n}\n\ninterface CrossCartData {\n orderFormId: string | null\n}\n\ninterface SaveCurrentCartData extends CrossCartData {\n userId: string\n}\n\ntype Strategy = 'ADD' | 'COMBINE' | 'REPLACE'\n\ninterface AppSettings {\n settings: {\n isAutomatic: boolean\n strategy: Strategy\n }\n}\n\n```" } ]
code_cross-device-cart_98c675c4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/utils/index.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AxiosError } from 'axios'\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\n\n/**\n * Returns the appropiate VTEX's type of error depending on `err` status code.\n *\n * @function statusToError\n * @param {AxiosError} err The error received from the request.\n * @returns {Error} VTEX's error instance\n */\nexport function statusToError(err: AxiosError): Error {\n if (!err.response || !err.response.status) {\n throw err\n }\n\n const {\n response: { status },\n } = err\n\n if (status === 401) {\n throw new AuthenticationError(err)\n }\n\n if (status === 403) {\n throw new ForbiddenError(err)\n }\n\n if (status === 400) {\n throw new UserInputError(err)\n }\n\n throw err\n}\n\n/**\n * Returns a set from both provided cart's items.\n * If desired, duplicates from the second one have their\n * quantities added to the first provided list of items.\n *\n * @func mergeItems\n * @param {PartialItem[]} currentItems Current cart list of Items\n * @param {PartialItem[]} previousItems Previous cart list of Items\n * @param {boolean} sumDuplicates\n * @return {PartialItem[]} Set of items\n * @example\n *\n * mergeItems([{id: 3, qty: 1}, {id: 1, qty: 2}], [{id: 2, qty: 2}, {id: 1: qty: 1}])\n * // => [{ id: 3, qty: 1}, {id: 1, qty: 3}, {id: 2, qty: 2 }]\n */\nexport const mergeItems = (\n currentItems: PartialItem[],\n previousItems: PartialItem[],\n sumDuplicates: boolean\n): PartialItem[] =>\n [...currentItems, ...previousItems].reduce(\n (mergedItems: PartialItem[], item) => {\n const existingItem = mergedItems.find(({ id }) => id === item.id)\n\n existingItem\n ? sumDuplicates && (existingItem.quantity += item.quantity)\n : mergedItems.push(item)\n\n return mergedItems\n },\n []\n )\n\n```" } ]
code_cross-device-cart_e7074191
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/resolvers/saveCurrentCart.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { APP_NAME } from '../constants'\n\n/**\n * Store an OrderForm ID reference for a specific user\n * @param {string} userId - Unique user identification string\n * @param {string | null} orderFormId - Unique orderForm identification string\n * @returns {string} As fulfilled\n */\nexport const saveCurrentCart = async (\n _: any,\n { userId, orderFormId, userType }: { userId: string; orderFormId: string | null, userType: string },\n { clients: { vbase } }: Context\n): Promise<string> => {\n\n if( userType != \"CALL_CENTER_OPERATOR\") {\n await vbase.saveJSON(APP_NAME, userId, orderFormId)\n\n return 'success'\n } else {\n return 'Not saved is call center operator'\n }\n}\n\n```" } ]
code_cross-device-cart_be4fa868
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/resolvers/getAppSettings.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { BUCKET, DEFAULT_SETTINGS, SETTINGS_PATH } from '../constants'\n\nexport const getAppSettings = async (\n _: unknown,\n __: unknown,\n { clients: { vbase } }: Context\n): Promise<AppSettings['settings']> => {\n const appSettings = await vbase.getJSON<AppSettings | null>(\n BUCKET,\n SETTINGS_PATH,\n true\n )\n\n if (!appSettings) {\n return DEFAULT_SETTINGS\n }\n\n return appSettings.settings\n}\n\n```" } ]
code_cross-device-cart_19d9a274
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/resolvers/getSavedCart.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { APP_NAME } from '../constants'\n\n/**\n * Retrieve a previous session OrderForm ID\n * @param {string} userId - Unique user identification string\n * @param {boolean} nullOnEmpty - Return null if the orderForm doesn't have items\n * @returns {string | null} orderFormId\n */\nexport const getSavedCart = async (\n _: unknown,\n { userId, nullOnEmpty, userType }: { userId: string; nullOnEmpty: boolean, userType: string },\n { clients: { vbase, checkoutIO } }: Context\n): Promise<string | null> => {\n const orderFormId: string | null = await vbase.getJSON(APP_NAME, userId, true)\n\n if( userType != \"CALL_CENTER_OPERATOR\") {\n if (nullOnEmpty && orderFormId) {\n const savedItems = await checkoutIO.getItems(orderFormId)\n \n if (!savedItems.length) {\n return null\n }\n }\n \n return orderFormId\n\n } else {\n return null\n }\n\n}\n\n```" } ]
code_cross-device-cart_e3bd03de
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/resolvers/saveAppSettings.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { BUCKET, SETTINGS_PATH } from '../constants'\n\nexport const saveAppSettings = async (\n _: unknown,\n settings: AppSettings,\n { clients: { vbase }, vtex: { logger } }: Context\n): Promise<boolean> => {\n try {\n await vbase.saveJSON(BUCKET, SETTINGS_PATH, settings)\n\n return true\n } catch (error) {\n logger.error({\n message: 'There was a problem saving the app settings',\n error,\n })\n\n return false\n }\n}\n\n```" } ]
code_cross-device-cart_71ae7dc2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/resolvers/index.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { getAppSettings } from './getAppSettings'\nimport { getSavedCart } from './getSavedCart'\nimport { saveAppSettings } from './saveAppSettings'\nimport { saveCurrentCart } from './saveCurrentCart'\nimport { replaceCart } from './replaceCart'\n\nexport const queries = {\n getAppSettings,\n getSavedCart,\n}\n\nexport const mutations = {\n saveAppSettings,\n saveCurrentCart,\n replaceCart,\n}\n\n```" } ]
code_cross-device-cart_602412f9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/resolvers/replaceCart.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { mergeItems } from '../utils'\n\n/**\n * Cross cart main feature\n * @returns {PartialOrderForm}\n * @typedef PartialOrderForm a partial orderform, fielded\n * to update Store Framework's context relevant data.\n */\nexport const replaceCart = async (\n _: any,\n { savedCart, currentCart, strategy, userType }: ReplaceCartVariables,\n context: Context\n): Promise<PartialOrderForm | null> => {\n const {\n clients: { checkoutIO, requestHub },\n response,\n } = context\n\n if( userType != \"CALL_CENTER_OPERATOR\") {\n const host = context.get('x-forwarded-host')\n\n response.set(\n 'set-cookie',\n `checkout.vtex.com=__ofid=${savedCart}; Max-Age=15552000; Domain=${host}; path=/; secure; samesite=lax; httponly`\n )\n\n const orderForm = await checkoutIO.getOrderForm(savedCart)\n\n if (strategy !== 'REPLACE') {\n /**\n * Add to cart has a specific graphql INPUT type.\n * These calls ensure handling correct types from start to finish.\n */\n const savedItems = await checkoutIO.getItems(savedCart)\n const currentItems = await checkoutIO.getItems(currentCart)\n\n const tally = strategy === 'COMBINE'\n\n const items = mergeItems(currentItems, savedItems, tally)\n\n if (!items.length) return orderForm\n\n await requestHub.clearCart(savedCart)\n\n items.forEach((element, index) => {\n element.id = Number(element.id)\n element.index = index\n })\n\n const newOrderForm = await checkoutIO.addToCart(savedCart, items)\n\n return newOrderForm\n }\n\n return orderForm\n\n } else {\n return null\n\n }\n\n \n}\n\n```" } ]
code_cross-device-cart_4794bac9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/events/updateSavedCartReference.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { APP_NAME } from '../constants'\n\n/**\n * Listens to the event \"order-created\" from the broadcaster.\n * If the owner of the order has a cross cart reference stored with\n * the same orderForm ID, we delete it.\n */\nexport async function updateSavedCartReference(ctx: StatusChangeContext) {\n const {\n body: { orderId, userType },\n vtex: { logger },\n clients: { oms, vbase },\n } = ctx\n\n if( userType != \"CALL_CENTER_OPERATOR\") {\n\n try {\n const customerOrder = await oms.order(orderId)\n \n const {\n orderFormId,\n clientProfileData: { userProfileId },\n } = customerOrder\n \n const crossCartReference: string | null = await vbase.getJSON(\n APP_NAME,\n userProfileId,\n true\n )\n \n if (crossCartReference === orderFormId) {\n await vbase.saveJSON(APP_NAME, userProfileId, null)\n \n logger.info({\n message: `Cross Device Cart reference removed for user ${userProfileId}`,\n })\n }\n } catch (error) {\n logger.error({\n orderId,\n message: 'There was a problem removing the reference for this order.',\n data: error,\n })\n }\n } else {\n logger.info({\n message: `Is Call center Operator`,\n })\n }\n\n}\n\n```" } ]
code_cross-device-cart_4aeb804b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/clients/checkout/queries.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const GET_ORDERFORM_ITEMS_QUERY = `\nquery orderForm($orderFormId: ID) {\n orderForm(orderFormId: $orderFormId) {\n items {\n id\n quantity\n seller\n uniqueId\n options {\n assemblyId\n id\n quantity\n seller\n inputValues\n }\n }\n }\n}\n`\nexport const GET_ORDERFORM_QUERY = `\nquery orderForm($orderFormId: ID) {\n orderForm(orderFormId: $orderFormId) {\n id\n items {\n additionalInfo {\n brandName\n }\n attachments {\n name\n content\n }\n attachmentOfferings {\n name\n required\n schema\n }\n bundleItems {\n additionalInfo {\n brandName\n }\n attachments {\n name\n content\n }\n attachmentOfferings {\n name\n required\n schema\n }\n availability\n detailUrl\n id\n imageUrls {\n at1x\n at2x\n at3x\n }\n listPrice\n measurementUnit\n name\n offerings {\n id\n name\n price\n type\n attachmentOfferings {\n name\n required\n schema\n }\n }\n price\n productCategories\n productCategoryIds\n productRefId\n productId\n quantity\n seller\n sellingPrice\n skuName\n skuSpecifications {\n fieldName\n fieldValues\n }\n unitMultiplier\n uniqueId\n refId\n }\n parentAssemblyBinding\n parentItemIndex\n sellingPriceWithAssemblies\n options {\n assemblyId\n id\n quantity\n seller\n inputValues\n options {\n assemblyId\n id\n quantity\n seller\n inputValues\n options {\n assemblyId\n id\n quantity\n seller\n inputValues\n }\n }\n }\n availability\n detailUrl\n id\n imageUrls {\n at1x\n at2x\n at3x\n }\n listPrice\n manualPrice\n measurementUnit\n name\n offerings {\n id\n name\n price\n type\n attachmentOfferings {\n name\n required\n schema\n }\n }\n price\n priceTags {\n identifier\n isPercentual\n name\n rawValue\n value\n }\n productCategories\n productCategoryIds\n productRefId\n productId\n quantity\n seller\n sellingPrice\n skuName\n skuSpecifications {\n fieldName\n fieldValues\n }\n unitMultiplier\n uniqueId\n refId\n priceTags {\n identifier\n isPercentual\n rawValue\n value\n name\n ratesAndBenefitsIdentifier {\n description\n id\n featured\n name\n matchedParameters\n }\n }\n isGift\n }\n totalizers {\n id\n name\n value\n }\n shipping {\n countries\n availableAddresses {\n addressId\n addressType\n city\n complement\n country\n neighborhood\n number\n postalCode\n receiverName\n reference\n state\n street\n isDisposable\n geoCoordinates\n }\n selectedAddress {\n addressId\n addressType\n city\n complement\n country\n neighborhood\n number\n postalCode\n receiverName\n reference\n state\n street\n isDisposable\n geoCoordinates\n }\n pickupOptions {\n id\n address {\n addressId\n addressType\n city\n complement\n country\n neighborhood\n number\n postalCode\n receiverName\n reference\n state\n street\n isDisposable\n geoCoordinates\n }\n deliveryChannel\n price\n estimate\n isSelected\n friendlyName\n additionalInfo\n storeDistance\n transitTime\n businessHours {\n dayNumber\n closed\n closingTime\n openingTime\n }\n }\n isValid\n }\n }\n}\n`\nexport const ADD_ITEMS_MUTATION = `\nmutation addToCart($orderFormId: ID, $items: [ItemInput]) {\n orderForm: addToCart(orderFormId: $orderFormId, items: $items) {\n id\n items {\n additionalInfo {\n brandName\n }\n attachments {\n name\n content\n }\n attachmentOfferings {\n name\n required\n schema\n }\n bundleItems {\n additionalInfo {\n brandName\n }\n attachments {\n name\n content\n }\n attachmentOfferings {\n name\n required\n schema\n }\n availability\n detailUrl\n id\n imageUrls {\n at1x\n at2x\n at3x\n }\n listPrice\n measurementUnit\n name\n offerings {\n id\n name\n price\n type\n attachmentOfferings {\n name\n required\n schema\n }\n }\n price\n productCategories\n productCategoryIds\n productRefId\n productId\n quantity\n seller\n sellingPrice\n skuName\n skuSpecifications {\n fieldName\n fieldValues\n }\n unitMultiplier\n uniqueId\n refId\n }\n parentAssemblyBinding\n parentItemIndex\n sellingPriceWithAssemblies\n options {\n assemblyId\n id\n quantity\n seller\n inputValues\n options {\n assemblyId\n id\n quantity\n seller\n inputValues\n options {\n assemblyId\n id\n quantity\n seller\n inputValues\n }\n }\n }\n availability\n detailUrl\n id\n imageUrls {\n at1x\n at2x\n at3x\n }\n listPrice\n manualPrice\n measurementUnit\n name\n offerings {\n id\n name\n price\n type\n attachmentOfferings {\n name\n required\n schema\n }\n }\n price\n priceTags {\n identifier\n isPercentual\n name\n rawValue\n value\n }\n productCategories\n productCategoryIds\n productRefId\n productId\n quantity\n seller\n sellingPrice\n skuName\n skuSpecifications {\n fieldName\n fieldValues\n }\n unitMultiplier\n uniqueId\n refId\n priceTags {\n identifier\n isPercentual\n rawValue\n value\n name\n ratesAndBenefitsIdentifier {\n description\n id\n featured\n name\n matchedParameters\n }\n }\n isGift\n }\n totalizers {\n id\n name\n value\n }\n shipping {\n countries\n availableAddresses {\n addressId\n addressType\n city\n complement\n country\n neighborhood\n number\n postalCode\n receiverName\n reference\n state\n street\n isDisposable\n geoCoordinates\n }\n selectedAddress {\n addressId\n addressType\n city\n complement\n country\n neighborhood\n number\n postalCode\n receiverName\n reference\n state\n street\n isDisposable\n geoCoordinates\n }\n pickupOptions {\n id\n address {\n addressId\n addressType\n city\n complement\n country\n neighborhood\n number\n postalCode\n receiverName\n reference\n state\n street\n isDisposable\n geoCoordinates\n }\n deliveryChannel\n price\n estimate\n isSelected\n friendlyName\n additionalInfo\n storeDistance\n transitTime\n businessHours {\n dayNumber\n closed\n closingTime\n openingTime\n }\n }\n isValid\n }\n }\n}\n`\n\n```" } ]
code_cross-device-cart_69560704
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/node/clients/checkout/index.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n IOContext,\n InstanceOptions,\n Serializable,\n GraphQLResponse,\n} from '@vtex/api'\nimport { AppGraphQLClient } from '@vtex/api'\nimport { ItemInput } from 'vtex.checkout-graphql'\n\nimport {\n GET_ORDERFORM_ITEMS_QUERY,\n GET_ORDERFORM_QUERY,\n ADD_ITEMS_MUTATION,\n} from './queries'\n\nclass CustomGraphQLError extends Error {\n public graphQLErrors: any\n\n constructor(message: string, graphQLErrors: any[]) {\n super(message)\n this.graphQLErrors = graphQLErrors\n }\n}\n\nfunction throwOnGraphQLErrors<T extends Serializable>(message: string) {\n return function maybeGraphQLResponse(response: GraphQLResponse<T>) {\n if (response && response.errors && response.errors.length > 0) {\n throw new CustomGraphQLError(message, response.errors)\n }\n\n return response\n }\n}\n\nexport default class CheckoutIO extends AppGraphQLClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super('vtex.checkout-graphql@0.x', context, {\n ...options,\n headers: {\n ...options?.headers,\n },\n })\n }\n\n /**\n * Retrieves the Items associated to a given shopping cart\n *\n * @func getItems\n * @public\n * @param {string} orderFormId OrderForm ID\n * @return {PartialItem[]} List of partial Items\n */\n public getItems = async (orderFormId: string): Promise<PartialItem[]> => {\n const partialItems = await this.graphql\n .query<PartialOrderFormItems, { orderFormId: string }>(\n {\n query: GET_ORDERFORM_ITEMS_QUERY,\n variables: {\n orderFormId,\n },\n },\n {\n metric: 'checkout-orderform',\n }\n )\n .then(\n throwOnGraphQLErrors(\n 'Error getting items data from vtex.checkout-graphql'\n )\n )\n .then((query) => {\n return query.data!.orderForm.items\n })\n\n return partialItems\n }\n\n /**\n * Retrieves data associated to a given shopping cart\n *\n * @func getOrderForm\n * @public\n * @param {string} orderFormId OrderForm ID\n * @return {PartialOrderForm} New partial OrderForm\n */\n public getOrderForm = async (\n orderFormId: string\n ): Promise<PartialOrderForm> => {\n const partialOrderForm = await this.graphql\n .query<{ orderForm: PartialOrderForm }, { orderFormId: string }>(\n {\n query: GET_ORDERFORM_QUERY,\n variables: {\n orderFormId,\n },\n },\n {\n metric: 'checkout-orderform',\n }\n )\n .then(\n throwOnGraphQLErrors('Error getting data from vtex.checkout-graphql')\n )\n .then((query) => {\n return query.data!.orderForm\n })\n\n return partialOrderForm\n }\n\n /**\n * @func addToCart\n * @public\n * @param {string} orderFormId OrderForm ID\n * @param {ItemInput[]} items Input list of Items\n * @return {PartialOrderForm} New partial OrderForm\n */\n public addToCart = async (\n orderFormId: string,\n items: ItemInput[]\n ): Promise<PartialOrderForm> => {\n const partialOrderForm = await this.graphql\n .mutate<\n { orderForm: PartialOrderForm },\n { orderFormId: string; items: ItemInput[] }\n >(\n {\n mutate: ADD_ITEMS_MUTATION,\n variables: {\n orderFormId,\n items,\n },\n },\n {\n metric: 'checkout-add-items',\n }\n )\n .then(\n throwOnGraphQLErrors('Error adding items with vtex.checkout-graphql')\n )\n .then((query) => {\n return query.data!.orderForm\n })\n\n return partialOrderForm\n }\n}\n\n```" } ]
code_cross-device-cart_d3b54c26
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cross-device-cart/react/typings/gql.d.ts from the cross-device-cart VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n import { DocumentNode } from 'graphql'\n\n const Schema: DocumentNode\n\n export default Schema\n}\n\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const schema: DocumentNode\n\n export default Schema\n}\n\n```" } ]