id
stringlengths
12
53
messages
listlengths
3
3
code_store-graphql_34f5a1fb
[ { "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 store-graphql/node/resolvers/catalog/searchBreadcrumb.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Functions } from '@gocommerce/utils'\nimport { equals, toLower } from 'ramda'\n\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: Category[]\n categoriesSearched: string[]\n products: Product[]\n}\n\nconst findClusterNameFromId = (products: Product[], clusterId: string) => {\n const productWithCluster = products.find(\n ({ productClusters }) => !!productClusters[clusterId]\n )\n\n return productWithCluster?.productClusters[clusterId]\n}\n\nconst findSellerFromSellerId = (products: Product[], sellerId: string) => {\n for (const product of products) {\n for (const item of product.items) {\n const seller = item.sellers.find((sel) => sel.sellerId === sellerId)\n\n if (seller) {\n return seller.sellerName\n }\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')\n\nconst getCategoryInfo = (\n { categoriesSearched, queryUnit, categories }: BreadcrumbParams,\n isVtex: boolean,\n ctx: Context\n) => {\n const queryPosition = categoriesSearched.findIndex((cat) => cat === queryUnit)\n\n if (!isVtex) {\n return findCategoryInTree(\n categories,\n categoriesSearched.slice(0, queryPosition + 1)\n )\n }\n\n return ctx.clients.catalog\n .pageType(categoriesSearched.slice(0, queryPosition + 1).join('/'))\n .catch(() => null)\n}\n\nconst getBrandInfo = async (\n { queryUnit }: BreadcrumbParams,\n isVtex: boolean,\n { clients: { catalog } }: Context\n) => {\n if (!isVtex) {\n return getBrandFromSlug(toLower(queryUnit), catalog)\n }\n\n return catalog.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\n const { queryUnit, mapUnit, index, queryArray, products } = obj\n const defaultName = queryArray[index]\n const isVtex = !Functions.isGoCommerceAcc(account)\n\n if (isProductClusterMap(mapUnit)) {\n const clusterName = findClusterNameFromId(products, queryUnit)\n\n if (clusterName) {\n return clusterName\n }\n }\n\n if (isCategoryMap(mapUnit)) {\n const categoryData = await getCategoryInfo(obj, isVtex, ctx)\n\n if (categoryData) {\n return categoryData.name\n }\n }\n\n if (isSellerMap(mapUnit)) {\n const sellerName = findSellerFromSellerId(products, queryUnit)\n\n if (sellerName) {\n return sellerName\n }\n }\n\n if (isBrandMap(mapUnit)) {\n const brandData = await getBrandInfo(obj, isVtex, ctx)\n\n return brandData ? brandData.name : defaultName\n }\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)) {\n return `/${queryUnit}/d`\n }\n\n if (index === 0 && isBrandMap(mapUnit)) {\n return `/${queryUnit}/b`\n }\n\n if (mapArray.every(isCategoryMap)) {\n return `/${sliceAndJoin(queryArray, index + 1, '/')}`\n }\n\n return `/${sliceAndJoin(queryArray, index + 1, '/')}?map=${sliceAndJoin(\n mapArray,\n index + 1,\n ','\n )}`\n },\n },\n}\n\n```" } ]
code_store-graphql_71ac0581
[ { "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 store-graphql/node/resolvers/catalog/slug.ts from the store-graphql 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·/_,:;'\n\nconst to =\n 'AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa------'\n\nconst removeAccents = (str: string) => {\n let newStr = str.slice(0)\n\n for (let i = 0; i < from.length; i++) {\n newStr = newStr.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i))\n }\n\n return newStr\n}\n\n// Parameter \"S. Coifman\" should output \"s--coifman\"\nexport function catalogSlugify(str: string) {\n // According to Bacelar, the catalog 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 replaced = str.replace(/[*+~.()'\"!:@&\\[\\]`,/ %$#?{}|><=_^]/g, '-')\n\n return toLower(removeAccents(replaced))\n}\n\n```" } ]
code_store-graphql_a2c291e0
[ { "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 store-graphql/node/resolvers/catalog/facets.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { map, prop, toPairs, zip } from 'ramda'\n\nimport { pathToCategoryHref } from './category'\n\nconst objToNameValue = (\n keyName: string,\n valueName: string,\n record: Record<string, any>\n) =>\n map(\n ([key, value]) => ({ [keyName]: key, [valueName]: value }),\n toPairs(record)\n )\n\nconst formatCategoriesTree = (root: any) => {\n const format = (tree: any[] = []): any => {\n return tree.map((node) => {\n return {\n ...node,\n Children: format(node.Children),\n }\n })\n }\n\n return format(root)\n}\n\nconst addSelected = (\n facets: any[],\n options: { query: string; map: string }\n): any => {\n return facets.map((facet: any) => {\n let children = facet.Children\n\n if (children) {\n children = addSelected(children, options)\n }\n\n const currentFacetSlug = decodeURIComponent(facet.Value).toLowerCase()\n\n const isSelected =\n zip(\n options.query.toLowerCase().split('/').map(decodeURIComponent),\n options.map.toLowerCase().split(',')\n ).find(\n ([slug, slugMap]) => slug === currentFacetSlug && facet.Map === slugMap\n ) !== undefined\n\n return {\n ...facet,\n Children: children,\n selected: isSelected,\n }\n })\n}\n\nconst baseFacetResolvers = {\n quantity: prop('Quantity'),\n name: prop('Name'),\n link: prop('Link'),\n linkEncoded: prop('LinkEncoded'),\n map: prop('Map'),\n value: prop('Value'),\n}\n\nexport const resolvers = {\n FilterFacet: {\n ...baseFacetResolvers,\n\n name: prop('Name'),\n },\n DepartmentFacet: {\n ...baseFacetResolvers,\n\n id: prop('Id'),\n\n name: prop('Name'),\n },\n BrandFacet: {\n ...baseFacetResolvers,\n\n id: prop('Id'),\n },\n PriceRangesFacet: {\n ...baseFacetResolvers,\n\n slug: prop('Slug'),\n },\n CategoriesTreeFacet: {\n ...baseFacetResolvers,\n\n id: prop('Id'),\n\n children: prop('Children'),\n\n href: ({ Link }: { Link: string }) => {\n const [linkPath] = Link.split('?')\n\n return pathToCategoryHref(linkPath)\n },\n\n name: prop('Name'),\n },\n Facets: {\n Departments: ({ Departments = [], queryArgs = {} }: any) => {\n return addSelected(Departments, queryArgs)\n },\n departments: (root: any) => {\n return resolvers.Facets.Departments(root)\n },\n\n Brands: ({ Brands = [], queryArgs = {} }: any) => {\n return addSelected(Brands, queryArgs)\n },\n brands: (root: any) => {\n return resolvers.Facets.Brands(root)\n },\n\n SpecificationFilters: ({\n SpecificationFilters = {},\n queryArgs = {},\n }: any) => {\n const specificationFilters = objToNameValue(\n 'name',\n 'facets',\n SpecificationFilters\n )\n\n return specificationFilters.map((specificationFilter: any) => ({\n ...specificationFilter,\n facets: addSelected(specificationFilter.facets, queryArgs),\n }))\n },\n specificationFilters: (root: any) => {\n return resolvers.Facets.SpecificationFilters(root)\n },\n\n CategoriesTrees: ({ CategoriesTrees = [], queryArgs = {} }: any) => {\n return addSelected(formatCategoriesTree(CategoriesTrees), queryArgs)\n },\n categoriesTrees: (root: any) => {\n return resolvers.Facets.CategoriesTrees(root)\n },\n\n priceRanges: prop('PriceRanges'),\n\n recordsFiltered: async (root: any, _: any, ctx: Context) => {\n const {\n clients: { catalog },\n } = ctx\n\n try {\n return catalog.productsQuantity(root.queryArgs)\n } catch (e) {\n return 0\n }\n },\n },\n}\n\n```" } ]
code_store-graphql_a066edf3
[ { "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 store-graphql/node/resolvers/catalog/brand.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop } from 'ramda'\n\nimport { catalogSlugify } from './slug'\n\nexport const resolvers = {\n Brand: {\n titleTag: prop('title'),\n\n metaTagDescription: prop('metaTagDescription'),\n\n active: prop('isActive'),\n\n cacheId: (brand: any) => catalogSlugify(brand.name),\n\n slug: (brand: any) => catalogSlugify(brand.name),\n },\n}\n\n```" } ]
code_store-graphql_37bee7a6
[ { "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 store-graphql/node/resolvers/catalog/itemMetadataUnit.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ntype AnyMetadataItem = Partial<MetadataItem & CatalogMetadataItem>\n\n/**\n * This is used because the itemMetadata that comes from the catalog has capitalized Name and MainImage.\n * The itemMetadata that comes from the checkout API has name and imageUrl. This unify the patterns\n */\n\nexport const resolvers = {\n ItemMetadataUnit: {\n imageUrl: ({ imageUrl, MainImage }: AnyMetadataItem) =>\n imageUrl ?? MainImage,\n skuName: ({ skuName, Name }: AnyMetadataItem) => skuName ?? Name,\n name: ({ name, NameComplete }: AnyMetadataItem) => name ?? NameComplete,\n productId: ({ productId, ProductId }: AnyMetadataItem) =>\n productId ?? ProductId,\n },\n}\n\n```" } ]
code_store-graphql_f88c516f
[ { "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 store-graphql/node/resolvers/catalog/autocomplete.ts from the store-graphql 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: any) => {\n const href = split('/', item.href)\n\n return item.criteria ? `${href[3]}/${href[4]}` : href[3]\n}\n\nexport const resolvers = {\n Items: {\n slug: (root: any) => extractSlug(root),\n\n productId: ({ items }: { items?: [{ productId?: string }] }) =>\n items ? path([0, 'productId'], items) : null,\n },\n}\n\n```" } ]
code_store-graphql_9c78052d
[ { "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 store-graphql/node/resolvers/catalog/search.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { reduce, sort, zip } from 'ramda'\n\nimport { queries } from '.'\n\n/**\n * This sorting exists because the catalog API returns inconsistent\n * results when the categories are mixed up in the query, so we sort\n * them to appear first, so we get consistency 👌\n */\nconst sortMapAndQuery = (map: string[], query: string[]) => {\n const zipped = zip(map, query)\n\n const sorted = sort(([a], [b]) => {\n if (a !== b && a === 'productClusterIds') {\n return -1\n }\n\n if (a !== b && a === 'c') {\n return -1\n }\n\n if (a === b && a === 'c') {\n return 0\n }\n\n return 1\n }, zipped)\n\n return reduce(\n (acc, [m, q]: any) => ({\n map: acc.map.concat(m),\n query: acc.query.concat(q),\n }),\n { map: [], query: [] },\n sorted\n )\n}\n\nconst getQueryAndFacets = ({\n map: unsortedMap = '',\n query: queryParam = '',\n rest = '',\n}) => {\n let unsortedQuery = queryParam\n\n if (rest) {\n unsortedQuery += `/${rest.replace(/,/g, '/')}`\n }\n\n const { query: sortedQuery, map: sortedMap } = sortMapAndQuery(\n unsortedMap.split(','),\n unsortedQuery.split('/')\n )\n\n const map = sortedMap.join(',')\n const query = sortedQuery.join('/')\n\n return {\n facets: `${query}?map=${map}`,\n map,\n query,\n }\n}\n\nexport const resolvers = {\n Search: {\n facets: async (root: any, _: any, ctx: Context) => {\n const args = root.queryArgs || {}\n\n const { facets } = getQueryAndFacets(args)\n\n const response = await queries.facets(root, { ...args, facets }, ctx)\n\n response.queryArgs = args\n\n return response\n },\n products: (root: any, _: any, ctx: Context) => {\n const args = root.queryArgs || {}\n\n const { map, query } = getQueryAndFacets(args)\n\n return queries.products(root, { ...args, query, map }, ctx)\n },\n recordsFiltered: async (root: any, _: any, ctx: Context) => {\n const {\n clients: { catalog },\n } = ctx\n\n try {\n return catalog.productsQuantity({\n ...root.queryArgs,\n ...getQueryAndFacets(root.queryArgs),\n })\n } catch (e) {\n return 0\n }\n },\n },\n}\n\n```" } ]
code_store-graphql_aac60fb2
[ { "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 store-graphql/node/resolvers/catalog/product.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { compose, last, map, omit, reject, split, toPairs } from 'ramda'\n\nimport { queries as benefitsQueries } from '../benefits'\nimport { buildCategoryMap } from './utils'\n\ntype MaybeRecord = false | Record<string, any>\nconst objToNameValue = (\n keyName: string,\n valueName: string,\n record: Record<string, any>\n) =>\n compose<\n Record<string, any>,\n Array<[string, any]>,\n MaybeRecord[],\n MaybeRecord\n >(\n reject<MaybeRecord>(\n (value) => typeof value === 'boolean' && value === false\n ),\n map<[string, any], MaybeRecord>(\n ([key, value]) =>\n typeof value === 'string' && { [keyName]: key, [valueName]: value }\n ),\n toPairs\n )(record)\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\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 {\n categories,\n categoriesIds,\n categoryId: prodCategoryId,\n }: { categories: string[]; categoriesIds: string[]; categoryId: string },\n _: any,\n { clients: { catalog }, 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) => catalog.category(Number(categoryId)))\n }\n\n const categoriesTree = await catalog.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 }: any, _: any, ctx: Context) =>\n benefitsQueries.benefits(_, { id: productId }, ctx),\n\n categoryTree: productCategoriesToCategoryTree,\n\n cacheId: ({ linkText }: any) => linkText,\n\n clusterHighlights: ({ clusterHighlights = {} }) =>\n objToNameValue('id', 'name', clusterHighlights),\n\n jsonSpecifications: (product: any) => {\n const { Specifications = [] } = product\n const specificationsMap = Specifications.reduce((acc: any, key: any) => {\n acc[key] = product[key]\n\n return acc\n }, {})\n\n return JSON.stringify(specificationsMap)\n },\n\n productClusters: ({ productClusters = {} }) =>\n objToNameValue('id', 'name', productClusters),\n\n properties: (product: any) =>\n map(\n (name: string) => ({ name, values: product[name] }),\n product.allSpecifications || []\n ),\n\n propertyGroups: (product: any) => {\n const { allSpecifications = [] } = product\n const notPG = knownNotPG.concat(allSpecifications)\n\n return objToNameValue('name', 'values', omit(notPG, product))\n },\n\n recommendations: (product: any) => product,\n\n specificationGroups: (product: any) => {\n const productSpecificationGroups = (product?.allSpecificationsGroups ??\n []) as string[]\n\n const allSpecificationsGroups = productSpecificationGroups.concat([\n 'allSpecifications',\n ])\n\n const specificationGroups = allSpecificationsGroups.map(\n (groupName: string) => ({\n name: groupName,\n specifications: (product[groupName] || []).map((name: string) => ({\n name,\n values: product[name] || [],\n })),\n })\n )\n\n return specificationGroups || []\n },\n\n items: (product: any) => {\n const {\n allSpecifications,\n items,\n productName,\n description: productDescription,\n brand: brandName,\n } = product\n\n const productSpecifications: ProductSpecification[] = []\n\n ;(allSpecifications || []).forEach((specification: string) => {\n const fieldValues: string[] = []\n\n ;(product[specification] || []).forEach((value: string) => {\n fieldValues.push(value)\n })\n\n productSpecifications.push({\n fieldName: specification,\n fieldValues,\n })\n })\n\n if (items && items.length > 0) {\n items.forEach((item: any) => {\n item.productSpecifications = productSpecifications\n item.productName = productName\n item.productDescription = productDescription\n item.brandName = brandName\n })\n }\n\n return items\n },\n },\n\n OnlyProduct: {\n categoryTree: productCategoriesToCategoryTree,\n },\n}\n\n```" } ]
code_store-graphql_f4451300
[ { "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 store-graphql/node/resolvers/catalog/discount.ts from the store-graphql 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 },\n}\n\n```" } ]
code_store-graphql_e51b897c
[ { "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 store-graphql/node/resolvers/catalog/utils.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport crypto from 'crypto'\n\nimport { compose, last, split, toLower } from 'ramda'\n\nimport { catalogSlugify, Slugify } from './slug'\n\n// eslint-disable-next-line no-restricted-syntax\nexport enum CatalogCrossSellingTypes {\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>(last, split('/'))\n\nexport function hashMD5(text: string) {\n const hash = crypto.createHash('md5')\n\n return hash.update(text).digest('hex')\n}\n\nexport function findCategoryInTree(\n tree: Category[],\n values: string[],\n index = 0\n): Category | null {\n for (const node of tree) {\n const slug = lastSegment(node.url)\n\n if (slug.toUpperCase() === values[index].toUpperCase()) {\n if (index === values.length - 1) {\n return node\n }\n\n return findCategoryInTree(node.children, values, index + 1)\n }\n }\n\n return null\n}\n\nexport const getBrandFromSlug = async (\n brandSlug: string,\n catalog: Context['clients']['catalog']\n) => {\n const brands = await catalog.brands()\n\n return brands.find(\n (brand) =>\n brand.isActive &&\n (toLower(catalogSlugify(brand.name)) === brandSlug ||\n toLower(Slugify(brand.name)) === brandSlug)\n )\n}\n\ntype CategoryMap = Record<string, Category>\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 Catalog team fixes this issue with the category API.\n */\nexport async function getCategoryInfo(\n catalog: Context['clients']['catalog'],\n id: number,\n levels: number\n) {\n const categories = await catalog.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: Category[]) {\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(mapCategories: CategoryMap, category: Category) {\n mapCategories[category.id] = category\n\n mapCategories = category.children.reduce(appendToMap, mapCategories)\n\n return mapCategories\n}\n\nexport function translatePageType(catalogPageType: string): string {\n return pageTypeMapping[catalogPageType] || 'search'\n}\n\ninterface CategoryArgs {\n department?: string\n category?: string\n subcategory?: string\n}\n\nconst typesPossible = ['Department', 'Category', 'SubCategory']\n\nexport const searchContextGetCategory = async (\n args: CategoryArgs,\n catalog: Context['clients']['catalog'],\n isVtex: boolean,\n logger: Context['clients']['logger']\n) => {\n if (!isVtex) {\n return getIdFromTree(args, catalog)\n }\n\n const { department, category, subcategory } = args\n\n if (!department && !category && !subcategory) {\n return null\n }\n\n const url = [department, category, subcategory]\n .filter(Boolean)\n .map((str) => catalogSlugify(str!))\n .join('/')\n\n const pageType = await catalog.pageType(url).catch(() => null)\n\n if (!pageType) {\n logger.info(\n `category ${url}, args ${JSON.stringify(args)}`,\n 'pagetype-category-error'\n )\n }\n\n if (!pageType || !typesPossible.includes(pageType.pageType)) {\n return getIdFromTree(args, catalog)\n }\n\n return pageType.id\n}\n\nconst getIdFromTree = async (\n args: CategoryArgs,\n catalog: Context['clients']['catalog']\n) => {\n if (args.department) {\n const departments = await catalog.categories(3)\n\n const compareGenericSlug = ({\n entity,\n url,\n }: {\n entity: 'category' | 'department' | 'subcategory'\n url: string\n }) => {\n const slug = args[entity]\n\n if (!slug) {\n return false\n }\n\n return (\n url.endsWith(`/${toLower(catalogSlugify(slug))}`) ||\n url.endsWith(`/${toLower(Slugify(slug))}`)\n )\n }\n\n let found\n\n found = departments.find((department) =>\n compareGenericSlug({ entity: 'department', url: department.url })\n )\n\n if (args.category && found) {\n found = found.children.find((category) =>\n compareGenericSlug({ entity: 'category', url: category.url })\n )\n }\n\n if (args.subcategory && found) {\n found = found.children.find((subcategory) =>\n compareGenericSlug({ entity: 'subcategory', url: subcategory.url })\n )\n }\n\n return found ? found.id : null\n }\n\n return null\n}\n\n```" } ]
code_store-graphql_cdc44fb1
[ { "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 store-graphql/node/resolvers/catalog/recommendation.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { CatalogCrossSellingTypes } from './utils'\n\nexport const resolvers = {\n Recommendation: {\n buy: ({ productId }: Product, _: any, { clients: { catalog } }: Context) =>\n catalog.crossSelling(\n productId,\n CatalogCrossSellingTypes.whoboughtalsobought\n ),\n\n similars: (\n { productId }: Product,\n _: any,\n { clients: { catalog } }: Context\n ) => catalog.crossSelling(productId, CatalogCrossSellingTypes.similars),\n\n view: ({ productId }: Product, _: any, { clients: { catalog } }: Context) =>\n catalog.crossSelling(productId, CatalogCrossSellingTypes.whosawalsosaw),\n },\n}\n\n```" } ]
code_store-graphql_cbf45337
[ { "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 store-graphql/node/resolvers/catalog/itemMetadata.ts from the store-graphql 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'\n\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: CatalogMetadataItem[]\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.segment()\n\n let marketingData: Record<string, string> = {}\n\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 Array<{\n compositionItem: CompositionItem\n simulationPayload: SimulationPayload\n items: CatalogMetadataItem[]\n parent: CatalogMetadataItem\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 const itemsWithAssembly = items.filter(\n (item) => item.assemblyOptions.length > 0\n )\n\n const priceTableMap: PriceTableMap = {}\n\n for (const item of itemsWithAssembly) {\n const { assemblyOptions } = item\n\n for (const assemblyOption of assemblyOptions) {\n const { composition } = assemblyOption\n\n if (composition?.items) {\n for (const compItem of composition.items) {\n const { priceTable } = compItem\n const currentArray = priceTableMap[priceTable] || []\n\n currentArray.push({\n compositionItem: compItem,\n simulationPayload,\n items: itemsWithAssembly,\n parent: item,\n assemblyOption,\n })\n priceTableMap[priceTable] = currentArray\n }\n }\n }\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_store-graphql_e08952e4
[ { "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 store-graphql/node/resolvers/catalog/itemMetadataPriceTableItem.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { isEmpty, path } from 'ramda'\n\nimport { getItemChoiceType, CHOICE_TYPES } from '../checkout/attachmentsHelper'\n\ninterface Params {\n compositionItem: CompositionItem\n simulationPayload: {\n marketingData: Record<string, string>\n countryCode: string\n }\n items: CatalogMetadataItem[]\n parent: CatalogMetadataItem\n assemblyOption: AssemblyOption\n}\n\n// Generate a valid simulation list with this child, considering its a single item type\nconst getSimulationPayloadItemsForSingleFromTree = (\n parent: CatalogMetadataItem,\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: CatalogMetadataItem,\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\n const basicChildItem = {\n id: childId,\n seller,\n quantity: 1,\n parentItemIndex: 0,\n parentAssemblyBinding: assemblyOption.id,\n }\n\n const siblings = parentBasicTree.filter(\n ({ parentAssemblyBinding }) => parentAssemblyBinding === assemblyOption.id\n )\n\n const siblingCount = siblings.length\n\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\n return brotherComposition!.minQuantity === 0\n })\n\n if (!brotherToBeRemoved) {\n return []\n }\n\n const withoutBrother = parentBasicTree.filter(\n ({ id, parentAssemblyBinding }) =>\n id !== brotherToBeRemoved.id &&\n parentAssemblyBinding !== brotherToBeRemoved.parentAssemblyBinding\n )\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: CatalogMetadataItem,\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\n if (basicItemQuantity <= siblingsAllowed) {\n return [parentPayloadItem, ...siblings, basicChildItem]\n }\n\n let currentSiblingCount = siblingCount\n\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\n const oldBrotherQuantity = brother.quantity\n\n brother.quantity = brotherComposition!.minQuantity\n currentSiblingCount -= oldBrotherQuantity - brotherComposition!.minQuantity\n const currentSiblingsAllowed =\n assemblyOption.composition!.maxQuantity - currentSiblingCount\n\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\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\n return childInTree ? childInTree.sellingPrice : 0\n}\n\nconst getSimulationPayloadItems = (\n assemblyOption: AssemblyOption,\n compositionItem: CompositionItem,\n parent: CatalogMetadataItem,\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\n if (assemblyType === CHOICE_TYPES.TOGGLE) {\n return getSimulationPayloadItemsForToggleFromTree(\n parent,\n compositionItem.id,\n compositionItem.seller,\n assemblyOption,\n fatherBasicTree\n )\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\n if (!fatherAssemblyOption.composition) {\n continue\n }\n\n const groupMinimum = fatherAssemblyOption.composition!.minQuantity\n const itemsInitialsSum = fatherAssemblyOption.composition!.items.reduce(\n (sum, item) => sum + item.initialQuantity,\n 0\n )\n\n // The basic tree will not contain children of this group\n if (groupMinimum !== itemsInitialsSum) {\n continue\n }\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\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\n return simulateAndGetPrice(\n { ...payload, items: newSimulationPayloadItems },\n checkout,\n id,\n assemblyOption.id\n )\n },\n },\n}\n\n```" } ]
code_store-graphql_bf280681
[ { "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 store-graphql/node/resolvers/catalog/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Functions } from '@gocommerce/utils'\nimport { NotFoundError, ResolverWarning, UserInputError } from '@vtex/api'\nimport {\n compose,\n equals,\n filter,\n head,\n isEmpty,\n isNil,\n join,\n map,\n path,\n prop,\n split,\n test,\n toLower,\n zip,\n} from 'ramda'\n\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 facetsResolvers } from './facets'\nimport { resolvers as itemMetadataResolvers } from './itemMetadata'\nimport { resolvers as itemMetadataUnitResolvers } from './itemMetadataUnit'\nimport { resolvers as itemMetadataPriceTableItemResolvers } from './itemMetadataPriceTableItem'\nimport { resolvers as offerResolvers } from './offer'\nimport { resolvers as productResolvers } from './product'\nimport { resolvers as productSearchResolvers } from './productSearch'\nimport { resolvers as recommendationResolvers } from './recommendation'\nimport { resolvers as searchResolvers } from './search'\nimport { resolvers as breadcrumbResolvers } from './searchBreadcrumb'\nimport { resolvers as skuResolvers } from './sku'\nimport {\n CatalogCrossSellingTypes,\n findCategoryInTree,\n getBrandFromSlug,\n searchContextGetCategory,\n translatePageType,\n} from './utils'\nimport { catalogSlugify } from './slug'\n\ninterface SearchContext {\n brand: string | null\n category: string | number | null\n contextKey: string\n}\n\ninterface SearchContextParams {\n brand?: string\n department?: string\n category?: string\n subcategory?: string\n}\n\ninterface SearchMetadataArgs {\n query?: string | null\n map?: string | null\n}\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\ninterface PageTypeArgs {\n path: string\n query: string\n}\n\n// eslint-disable-next-line no-restricted-syntax\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 inputToCatalogCrossSelling = {\n [CrossSellingInput.buy]: CatalogCrossSellingTypes.whoboughtalsobought,\n [CrossSellingInput.view]: CatalogCrossSellingTypes.whosawalsosaw,\n [CrossSellingInput.similars]: CatalogCrossSellingTypes.similars,\n [CrossSellingInput.viewAndBought]: CatalogCrossSellingTypes.whosawalsobought,\n [CrossSellingInput.accessories]: CatalogCrossSellingTypes.accessories,\n [CrossSellingInput.suggestions]: CatalogCrossSellingTypes.suggestions,\n}\n\nconst brandFromList = async (\n slug: string,\n catalog: Context['clients']['catalog']\n) => {\n const dataBrandFromList = await getBrandFromSlug(toLower(slug), catalog)\n\n return dataBrandFromList?.id ?? null\n}\n\nconst getBrandId = async (\n brand: string | undefined,\n catalog: Context['clients']['catalog'],\n isVtex: boolean,\n logger: Context['clients']['logger']\n) => {\n if (!brand) {\n return null\n }\n\n if (!isVtex) {\n return brandFromList(brand, catalog)\n }\n\n const slugified = catalogSlugify(brand)\n const brandPagetype = await catalog.pageType(slugified).catch(() => null)\n\n if (!brandPagetype) {\n logger.info(`brand ${brand}, slug ${slugified}`, 'pagetype-brand-error')\n }\n\n if (!brandPagetype || brandPagetype.pageType !== 'Brand') {\n return brandFromList(brand, catalog)\n }\n\n return brandPagetype.id\n}\n\ntype TupleString = [string, string]\n\nconst isTupleMap = compose<TupleString, string, boolean>(equals('c'), prop('1'))\n\nconst categoriesOnlyQuery = compose<\n TupleString[],\n TupleString[],\n string[],\n string\n>(join('/'), map(prop('0')), filter(isTupleMap))\n\nconst getAndParsePagetype = async (pathQuery: string, ctx: Context) => {\n const pagetype = await ctx.clients.catalog\n .pageType(pathQuery)\n .catch(() => null)\n\n if (!pagetype) {\n return { titleTag: null, metaTagDescription: null }\n }\n\n return {\n titleTag: pagetype.title ?? pagetype.name,\n metaTagDescription: pagetype.metaTagDescription,\n }\n}\n\nconst getCategoryMetadata = async (\n options: SearchMetadataArgs,\n ctx: Context\n) => {\n const {\n vtex: { account },\n } = ctx\n\n const queryAndMap: TupleString[] = zip(\n (options.query ?? '').split('/'),\n (options.map ?? '').split(',')\n )\n\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 queries.categories(\n {},\n { treeLevel: cleanQuery.split('/').length },\n ctx\n ),\n cleanQuery.split('/')\n ) ?? {}\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,\n ctx: Context\n) => {\n const {\n vtex: { account },\n clients: { catalog },\n } = ctx\n\n const cleanQuery = head(split('/', query ?? '')) ?? ''\n\n if (Functions.isGoCommerceAcc(account)) {\n const brand = (await getBrandFromSlug(toLower(cleanQuery), catalog)) ?? {}\n\n return {\n metaTagDescription: path(['metaTagDescription'], brand),\n titleTag: path(['title'], brand) || path(['name'], brand),\n }\n }\n\n return getAndParsePagetype(cleanQuery, ctx)\n}\n\n/**\n * Get metadata of category/brand APIs\n *\n * @param _\n * @param args\n * @param ctx\n */\nconst getSearchMetaData = async (\n _: any,\n args: SearchMetadataArgs,\n ctx: Context\n) => {\n const argsMap = args.map ?? ''\n const firstMap = head(argsMap.split(','))\n\n if (firstMap === 'c') {\n return getCategoryMetadata(args, ctx)\n }\n\n if (firstMap === 'b') {\n return getBrandMetadata(args, ctx)\n }\n\n return { titleTag: null, metaTagDescription: null }\n}\n\nconst translateToStoreDefaultLanguage = async (\n clients: Context['clients'],\n term: string\n): Promise<any> => {\n const { segment, messagesGraphQL } = clients\n const [{ cultureInfo: to }, { cultureInfo: from }] = await Promise.all([\n segment.getSegmentByToken(null),\n segment.getSegment(),\n ])\n\n return from && from !== to\n ? messagesGraphQL\n .translateV2({\n indexedByFrom: [\n {\n from,\n messages: [{ content: term }],\n },\n ],\n to,\n })\n .then(head)\n : term\n}\n\nexport const fieldResolvers = {\n ...autocompleteResolvers,\n ...brandResolvers,\n ...categoryResolvers,\n ...facetsResolvers,\n ...itemMetadataResolvers,\n ...itemMetadataUnitResolvers,\n ...itemMetadataPriceTableItemResolvers,\n ...offerResolvers,\n ...discountResolvers,\n ...productResolvers,\n ...recommendationResolvers,\n ...searchResolvers,\n ...skuResolvers,\n ...breadcrumbResolvers,\n ...productSearchResolvers,\n}\n\nconst isValidProductIdentifier = (identifier: ProductIndentifier | undefined) =>\n !!identifier && !isNil(identifier.value) && !isEmpty(identifier.value)\n\nexport const queries = {\n autocomplete: async (_: any, args: any, ctx: Context) => {\n const {\n clients: { catalog },\n clients,\n } = ctx\n\n const translatedTerm = await translateToStoreDefaultLanguage(\n clients,\n args.searchTerm\n )\n\n const { itemsReturned } = await catalog.autocomplete({\n maxRows: args.maxRows,\n searchTerm: translatedTerm,\n })\n\n return {\n cacheId: args.searchTerm,\n itemsReturned,\n }\n },\n\n facets: async (_: any, args: FacetsArgs, ctx: Context) => {\n const {\n clients: { catalog },\n clients,\n } = ctx\n\n if (args.facets?.includes('undefined')) {\n throw new UserInputError('Bad facets parameter provided')\n }\n\n let result\n const translatedQuery = await translateToStoreDefaultLanguage(\n clients,\n args.query\n )\n\n const segmentData = ctx.vtex.segment\n const salesChannel = segmentData?.channel.toString() ?? ''\n\n const unavailableString = args.hideUnavailableItems\n ? `&fq=isAvailablePerSalesChannel_${salesChannel}:1`\n : ''\n\n if (args.facets) {\n result = await catalog.facets(args.facets)\n } else {\n result = await catalog.facets(\n `${translatedQuery}?map=${args.map}${unavailableString}`\n )\n }\n\n result.queryArgs = {\n query: translatedQuery,\n map: args.map,\n }\n\n return result\n },\n\n product: async (_: any, rawArgs: ProductArgs, ctx: Context) => {\n const {\n vtex: { account },\n clients: { catalog },\n } = ctx\n\n const args =\n rawArgs &&\n isValidProductIdentifier(rawArgs.identifier) &&\n !Functions.isGoCommerceAcc(account)\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 Product[]\n\n switch (field) {\n case 'id':\n products = await catalog.productById(value)\n break\n\n case 'slug':\n products = await catalog.product(value)\n break\n\n case 'ean':\n products = await catalog.productByEan(value)\n break\n\n case 'reference':\n products = await catalog.productByReference(value)\n break\n\n case 'sku':\n products = await catalog.productBySku([value])\n break\n\n default:\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: { catalog },\n } = ctx\n\n const queryTerm = args.query\n\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\n return catalog.products(args)\n },\n\n productsByIdentifier: async (\n _: any,\n args: ProductsByIdentifierArgs,\n ctx: Context\n ) => {\n const {\n clients: { catalog },\n } = ctx\n\n let products = [] as Product[]\n const { field, values } = args\n\n switch (field) {\n case 'id':\n products = await catalog.productsById(values)\n break\n\n case 'ean':\n products = await catalog.productsByEan(values)\n break\n\n case 'reference':\n products = await catalog.productsByReference(values)\n break\n\n case 'sku':\n products = await catalog.productBySku(values)\n break\n\n default:\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: SearchArgs, ctx: Context) => {\n const {\n clients,\n clients: { catalog },\n } = ctx\n\n const queryTerm = args.query\n\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\n const query = await translateToStoreDefaultLanguage(\n clients,\n args.query ?? ''\n )\n\n const translatedArgs = {\n ...args,\n query,\n }\n\n const [productsRaw, searchMetaData] = await Promise.all([\n catalog.products(args, true),\n getSearchMetaData(_, translatedArgs, ctx),\n ])\n\n return {\n translatedArgs,\n searchMetaData,\n productsRaw,\n }\n },\n\n brand: async (\n _: any,\n { id }: { id?: number },\n { clients: { catalog } }: Context\n ) => {\n if (id == null) {\n throw new ResolverWarning(`No brand ID provided`)\n }\n\n const brand = await catalog.brand(id)\n\n if (!brand) {\n throw new NotFoundError(`Brand not found`)\n }\n\n return brand\n },\n\n brands: async (_: any, __: any, { clients: { catalog } }: Context) =>\n catalog.brands(),\n\n category: async (\n _: any,\n { id }: { id?: number },\n { clients: { catalog } }: Context\n ) => {\n if (id == null) {\n throw new ResolverWarning(`No category ID provided`)\n }\n\n return catalog.category(id)\n },\n\n categories: async (\n _: any,\n { treeLevel }: { treeLevel: number },\n { clients: { catalog } }: Context\n ) => catalog.categories(treeLevel),\n\n /** TODO: This method should be removed in the next major.\n * @author Bruno Dias\n */\n search: async (_: any, args: any, ctx: Context) => {\n if (args.query == null || args.map == null) {\n throw new UserInputError('Search query/map cannot be null')\n }\n\n const { titleTag, metaTagDescription }: any = await getSearchMetaData(\n _,\n args,\n ctx\n )\n\n return {\n metaTagDescription,\n queryArgs: args,\n titleTag,\n }\n },\n\n searchContextFromParams: async (\n _: any,\n args: SearchContextParams,\n { clients: { catalog, logger }, vtex: { account } }: Context\n ) => {\n const isVtex = !Functions.isGoCommerceAcc(account)\n const response: SearchContext = {\n brand: null,\n category: null,\n contextKey: 'search',\n }\n\n const [brandId, categoryId] = await Promise.all<\n string | null,\n string | number | null\n >([\n getBrandId(args.brand, catalog, isVtex, logger),\n searchContextGetCategory(args, catalog, isVtex, logger),\n ])\n\n response.brand = brandId\n response.category = categoryId\n\n return response\n },\n\n pageType: async (_: any, args: PageTypeArgs, ctx: Context) => {\n const response = await ctx.clients.catalog.pageType(args.path, args.query)\n\n return {\n id: response.id,\n type: translatePageType(response.pageType),\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\n const catalogType = inputToCatalogCrossSelling[type]\n let productId = identifier.value\n\n if (identifier.field !== 'id') {\n const product = await queries.product(_, { identifier }, ctx)\n\n productId = product!.productId\n }\n\n return ctx.clients.catalog.crossSelling(productId, catalogType)\n },\n\n searchMetadata: async (_: any, args: SearchMetadataArgs, ctx: Context) => {\n const { clients } = ctx\n const queryTerm = args.query\n\n if (queryTerm == null || test(/[?&[\\]=]/, queryTerm)) {\n throw new UserInputError(\n `The query term contains invalid characters. query=${queryTerm}`\n )\n }\n\n const query = await translateToStoreDefaultLanguage(\n clients,\n args.query ?? ''\n )\n\n const translatedArgs = {\n ...args,\n query,\n }\n\n return getSearchMetaData(_, translatedArgs, ctx)\n },\n}\n\n```" } ]
code_store-graphql_dce2cbf8
[ { "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 store-graphql/node/resolvers/catalog/offer.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { gte, lte, propOr } from 'ramda'\n\nconst InstallmentsCriteria = {\n ALL: 'ALL',\n MAX: 'MAX',\n MIN: 'MIN',\n}\n\nexport const resolvers = {\n Offer: {\n Installments: (\n { Installments }: any,\n { criteria, rates }: { criteria?: string; rates?: boolean }\n ) => {\n if (criteria === InstallmentsCriteria.ALL || Installments.length === 0) {\n return Installments\n }\n\n const filteredInstallments = !rates\n ? Installments\n : Installments.filter(({ InterestRate }: any) => !InterestRate)\n\n const compareFunc = criteria === InstallmentsCriteria.MAX ? gte : lte\n const value = filteredInstallments.reduce(\n (acc: any, currentValue: any) =>\n compareFunc(\n currentValue.NumberOfInstallments,\n acc.NumberOfInstallments\n )\n ? currentValue\n : acc,\n filteredInstallments[0]\n )\n\n return [value]\n },\n teasers: propOr([], 'Teasers'),\n giftSkuIds: propOr([], 'GiftSkuIds'),\n discountHighlights: propOr([], 'DiscountHighLight'),\n spotPrice: (offer: Seller['commertialOffer']) => {\n const sellingPrice = offer.Price\n const spotPrice: number | undefined = offer.Installments.find(\n ({ NumberOfInstallments, Value }) => {\n return NumberOfInstallments === 1 && Value < sellingPrice\n }\n )?.Value\n\n return spotPrice ?? sellingPrice\n },\n },\n}\n\n```" } ]
code_store-graphql_33320af3
[ { "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 store-graphql/node/resolvers/catalog/productSearch.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { path, zip } from 'ramda'\nimport { IOResponse } from '@vtex/api'\nimport { Functions } from '@gocommerce/utils'\n\ninterface ProductSearchParent {\n productsRaw: IOResponse<Product[]>\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\n const [, quantity] = resources.split('/')\n\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: { catalog } }: Context\n ) => {\n const query = translatedArgs.query ?? ''\n const map = translatedArgs.map ?? ''\n const queryAndMap = zip(\n query.toLowerCase().split('/').map(decodeURIComponent),\n map.split(',')\n )\n\n const categoriesSearched = queryAndMap\n .filter(([__, m]) => m === 'c')\n .map(([q]) => q)\n\n const categoriesCount = map.split(',').filter((m) => m === 'c').length\n const categories =\n !!categoriesCount && Functions.isGoCommerceAcc(account)\n ? await catalog.categories(categoriesCount)\n : []\n\n return queryAndMap.map(\n ([queryUnit, mapUnit]: [string, string], index: number) => ({\n queryUnit,\n mapUnit,\n index,\n queryArray: query.split('/'),\n mapArray: map.split(','),\n categories,\n categoriesSearched,\n products,\n })\n )\n },\n },\n}\n\n```" } ]
code_store-graphql_24626f44
[ { "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 store-graphql/node/resolvers/catalog/sku.ts from the store-graphql 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 = [] }: any) =>\n map(\n (attachment: any) => ({\n ...attachment,\n domainValues: JSON.parse(attachment.domainValues),\n }),\n attachments\n ),\n\n images: ({ images = [] }: any, { quantity }: any) =>\n map(\n (image: any) => ({\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: ({ kitItems }: any, _: any, { clients: { catalog } }: Context) =>\n !kitItems\n ? []\n : Promise.all(\n kitItems.map(async (kitItem: any) => {\n const products = await catalog.productBySku([kitItem.itemId])\n const { items: skus = [], ...product } = head(products) ?? {}\n const sku = find(\n ({ itemId }: any) => itemId === kitItem.itemId,\n skus\n )\n\n return { ...kitItem, product, sku }\n })\n ),\n\n variations: (sku: any) =>\n sku &&\n map(\n (name: string) => ({ name, values: sku[name] }),\n sku.variations || []\n ),\n\n videos: ({ Videos }: any) =>\n map(\n (video: string) => ({\n videoUrl: video,\n }),\n Videos\n ),\n\n skuSpecifications: (sku: any) => {\n const { variations } = sku\n const skuSpecifications: SkuSpecification[] = []\n\n ;(variations || []).forEach((variation: string) => {\n const fieldValues: string[] = []\n\n ;(sku[variation] || []).forEach((value: string) => {\n fieldValues.push(value)\n })\n\n skuSpecifications.push({\n fieldName: variation,\n fieldValues,\n })\n })\n\n return skuSpecifications\n },\n },\n}\n\n```" } ]
code_store-graphql_ec56c681
[ { "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 store-graphql/node/resolvers/document/attachment.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\nimport FormData from 'form-data'\n\nimport { generateRandomName } from '../../utils'\n\nexport async function uploadAttachment(args: any, ctx: Context) {\n const {\n clients: { masterdata },\n } = ctx\n\n const { acronym, documentId, field, file } = args\n const { createReadStream, filename, mimetype } = await file\n const buffer = (await new Promise((resolve, reject) => {\n const bufs: any[] = []\n const stream = createReadStream()\n\n stream.on('data', (d: any) => bufs.push(d))\n stream.on('end', () => {\n resolve(Buffer.concat(bufs))\n })\n stream.on('error', reject)\n })) as Buffer\n\n const formData = new FormData()\n\n const randomName = `${generateRandomName()}${getFileExtension(filename)}`\n\n formData.append(field, buffer, {\n contentType: mimetype,\n filename: randomName,\n knownLength: buffer.byteLength,\n })\n\n const response = await masterdata.uploadAttachment(\n acronym,\n documentId,\n field,\n formData\n )\n\n if (response) {\n throw new ResolverError(response)\n }\n\n return { filename: randomName, mimetype }\n}\n\nfunction getFileExtension(fileName: any) {\n return fileName.match(/\\.[0-9a-z]+$/i)[0]\n}\n\n```" } ]
code_store-graphql_8613c178
[ { "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 store-graphql/node/resolvers/document/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\nimport { compose, map, union, prop, replace } from 'ramda'\n\nimport { parseFieldsToJson } from '../../utils/object'\nimport { resolvers as documentSchemaResolvers } from './documentSchema'\n\nexport const queries = {\n documents: async (_: any, args: DocumentsArgs, context: Context) => {\n const {\n acronym,\n fields,\n page,\n pageSize,\n where,\n schema,\n sort,\n account,\n } = args\n\n const {\n clients: { masterdata },\n } = context\n\n const fieldsWithId = union(fields, ['id'])\n const data = (await masterdata.searchDocuments(\n acronym,\n fieldsWithId,\n where,\n {\n page,\n pageSize,\n },\n schema,\n sort,\n account\n )) as any\n\n return map((document: any) => ({\n cacheId: document.id,\n id: document.id,\n fields: mapKeyAndStringifiedValues(document),\n }))(data)\n },\n\n document: async (_: any, args: DocumentArgs, context: Context) => {\n const { acronym, fields, id, account } = args\n const {\n clients: { masterdata },\n } = context\n\n const data = await masterdata.getDocument(acronym, id, fields, account)\n\n return {\n cacheId: id,\n id,\n fields: mapKeyAndStringifiedValues(data),\n }\n },\n\n documentSchema: async (\n _: any,\n args: DocumentSchemaArgs,\n context: Context\n ) => {\n const { dataEntity, schema } = args\n\n const {\n clients: { masterdata },\n } = context\n\n const data = await masterdata.getSchema<Record<string, unknown>>(\n dataEntity,\n schema\n )\n\n return { ...data, name: data ? args.schema : null }\n },\n\n documentPublicSchema: async (\n _: any,\n args: DocumentSchemaArgs,\n context: Context\n ) => {\n const { dataEntity, schema } = args\n\n const {\n clients: { masterdata },\n } = context\n\n const data = await masterdata.getPublicSchema<Record<string, unknown>>(\n dataEntity,\n schema\n )\n\n return { schema: data }\n },\n}\n\nexport const fieldResolvers = {\n ...documentSchemaResolvers,\n}\n\nexport const mutations = {\n createDocument: async (\n _: any,\n args: CreateDocumentArgs,\n context: Context\n ) => {\n const {\n acronym,\n document: { fields },\n account,\n schema,\n } = args\n\n const {\n clients: { masterdata },\n } = context\n\n const response = (await masterdata.createDocument(\n acronym,\n parseFieldsToJson(fields),\n schema,\n account\n )) as DocumentResponse\n\n const documentId = removeAcronymFromId(acronym, response)\n\n return {\n cacheId: documentId,\n id: prop('Id', response),\n href: prop('Href', response),\n documentId: removeAcronymFromId(acronym, response),\n }\n },\n\n createDocumentV2: async (\n _: any,\n args: CreateDocumentV2Args,\n context: Context\n ) => {\n const {\n dataEntity,\n document: { document },\n account,\n schema,\n } = args\n\n const {\n clients: { masterdata },\n } = context\n\n const response = (await masterdata.createDocument(\n dataEntity,\n document,\n schema,\n account\n )) as DocumentResponseV2\n\n const documentId = removeAcronymFromId(dataEntity, response)\n\n return {\n cacheId: documentId,\n id: prop('Id', response),\n href: prop('Href', response),\n documentId,\n }\n },\n\n updateDocument: async (\n _: any,\n args: UpdateDocumentArgs,\n context: Context\n ) => {\n const {\n acronym,\n document: { fields },\n account: accountName,\n } = args\n\n const documentId = prop('id', parseFieldsToJson(fields)) as string\n\n if (!documentId) {\n throw new UserInputError('document id field cannot be null/undefined')\n }\n\n const {\n clients: { masterdata },\n vtex: { account },\n } = context\n\n await masterdata.updateDocument(\n acronym,\n documentId,\n parseFieldsToJson(fields),\n accountName\n )\n\n return {\n cacheId: documentId,\n documentId,\n href: generateHref(account, acronym, documentId),\n id: getId(acronym, documentId),\n }\n },\n\n deleteDocument: async (\n _: any,\n args: DeleteDocumentArgs,\n context: Context\n ) => {\n const { acronym, documentId } = args\n const {\n clients: { masterdata },\n vtex: { account },\n } = context\n\n await masterdata.deleteDocument(acronym, documentId)\n\n return {\n documentId,\n href: generateHref(account, acronym, documentId),\n id: getId(acronym, documentId),\n cacheId: documentId,\n }\n },\n}\n\n/**\n * Map a document object to a list of {key: 'property', value: 'propertyValue'},\n * Uses `JSON.stringify` in every value.\n */\nconst mapKeyAndStringifiedValues = (document: any) =>\n Object.keys(document).map((key) => ({\n key,\n value:\n typeof document[key] === 'string'\n ? document[key]\n : JSON.stringify(document[key]),\n }))\n\nconst removeAcronymFromId = (acronym: string, data: { Id: string }) => {\n return compose<any, any, any>(\n replace(new RegExp(`${acronym}-`), ''),\n prop('Id')\n )(data)\n}\n\nconst getId = (acronym: string, documentId: string) =>\n `${acronym}-${documentId}`\n\nconst generateHref = (account: string, acronym: string, documentId: string) =>\n `http://api.vtex.com/${account}/dataentities/${acronym}/documents/${documentId}`\n\n```" } ]
code_store-graphql_8effaab7
[ { "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 store-graphql/node/resolvers/document/documentSchema.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop, toPairs, map } from 'ramda'\n\nexport const resolvers = {\n DocumentSchema: {\n properties: ({ properties }: any) =>\n map(\n ([name, rest]: any) => ({\n name,\n type: rest.type,\n optional: rest.optional || false,\n }),\n toPairs(properties)\n ),\n indexed: prop('v-indexed'),\n cache: prop('v-cache'),\n security: prop('v-security'),\n },\n}\n\n```" } ]
code_store-graphql_986441c2
[ { "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 store-graphql/node/resolvers/checkout/paymentTokenResolver.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport http from 'axios'\nimport { last, mergeRight, propEq, reject } from 'ramda'\nimport pMapSeries from 'p-map-series'\n\nimport paths from '../paths'\n\nconst createClient = (account: any, orderFormId: any, authToken: any) => {\n const headers = {\n Accept: 'application/json',\n Authorization: `bearer ${authToken}`,\n 'Content-Type': 'application/json',\n }\n\n return {\n addToken: (paymentToken: any) => {\n const payload = {\n paymentToken,\n expectedOrderFormSections: ['items', 'paymentData'],\n }\n\n const url = paths.orderFormPaymentToken(account, { orderFormId })\n\n return http.put(url, payload, { headers })\n },\n\n removeToken: (tokenId: any) => {\n const url = paths.orderFormPaymentTokenId(account, {\n orderFormId,\n tokenId,\n })\n\n return http.delete(url, {\n headers,\n data: { expectedOrderFormSections: ['items'] },\n })\n },\n }\n}\n\nexport default async (body: any, ioContext: any) => {\n const {\n data: { orderFormId, paymentToken },\n } = body\n\n const checkout = createClient(\n ioContext.account,\n orderFormId,\n ioContext.authToken\n )\n\n const response = await checkout.addToken(paymentToken)\n\n const {\n data: {\n paymentData: { availableTokens },\n },\n } = response\n\n const tokensToRemove = reject(\n propEq('tokenId', paymentToken.tokenId),\n availableTokens\n )\n\n if (tokensToRemove.length === 0) {\n return { data: mergeRight(body.data, response.data) }\n }\n\n const lastDeleteResponse = await pMapSeries(\n tokensToRemove,\n ({ tokenId }: any) => checkout.removeToken(tokenId)\n ).then<any>(last)\n\n return { data: mergeRight(body.data, lastDeleteResponse.data) }\n}\n\n```" } ]
code_store-graphql_fc805305
[ { "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 store-graphql/node/resolvers/checkout/orderFormItem.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { partition, propEq } from 'ramda'\n\nimport { getPositionInOrderForm } from './attachmentsHelper'\n\ninterface Params extends OrderFormItem {\n assemblyOptionsData: {\n childs: OrderFormItem[]\n index: number\n assemblyOptionsMap: Record<string, AssemblyOption[]>\n orderForm: OrderForm\n }\n}\n\nconst getPriceForItem = (\n children: OrderFormItem[],\n fatherIndex: number,\n fatherItem: OrderFormItem,\n orderForm: OrderForm\n): number => {\n const [itemChildren, others] = partition(\n propEq('parentItemIndex', fatherIndex),\n children\n )\n\n return itemChildren.reduce(\n (sum, currentChildren) =>\n sum +\n getPriceForItem(\n others,\n getPositionInOrderForm(orderForm, currentChildren),\n currentChildren,\n orderForm\n ),\n fatherItem.sellingPrice * fatherItem.quantity\n )\n}\n\nexport const resolvers = {\n OrderFormItem: {\n assemblyOptions: ({\n assemblyOptionsData: { childs, index, orderForm, assemblyOptionsMap },\n ...item\n }: Params) => ({ item, childs, index, orderForm, assemblyOptionsMap }),\n cartIndex: ({ assemblyOptionsData: { index } }: Params) => index,\n canHaveAttachment: ({ attachmentOfferings }: OrderFormItem) => {\n return attachmentOfferings && attachmentOfferings.length > 0\n },\n imageUrl: ({ imageUrl }: Params) =>\n imageUrl?.replace('http://', 'https://'),\n listPrice: ({ listPrice }: Params) => listPrice / 100,\n price: ({ price }: Params) => price / 100,\n sellingPrice: ({ sellingPrice }: Params) => sellingPrice / 100,\n sellingPriceWithAssemblies: ({\n assemblyOptionsData: { childs, index, orderForm },\n ...item\n }: Params) => {\n if (childs.length === 0) {\n return item.sellingPrice / 100\n }\n\n return (\n getPriceForItem(childs, index, item, orderForm) / item.quantity / 100\n )\n },\n },\n}\n\n```" } ]
code_store-graphql_b06c9bb4
[ { "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 store-graphql/node/resolvers/checkout/shipping.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const fieldResolvers = {\n ShippingSLA: {\n friendlyName: ({ name, pickupStoreInfo, deliveryChannel }: SLA) => {\n if (deliveryChannel === 'pickup-in-point') {\n return pickupStoreInfo.friendlyName\n }\n\n return name\n },\n },\n}\n\n```" } ]
code_store-graphql_60ef3452
[ { "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 store-graphql/node/resolvers/checkout/assemblyOptionItem.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { values } from 'ramda'\n\nimport {\n buildAddedOptionsForItem,\n buildRemovedOptions,\n} from './attachmentsHelper'\n\ninterface Params {\n item: OrderFormItem\n childs: OrderFormItem[]\n index: number\n assemblyOptionsMap: Record<string, AssemblyOption[]>\n orderForm: OrderForm\n}\n\nexport const resolvers = {\n AssemblyOptionItem: {\n added: ({ item, childs, index, assemblyOptionsMap, orderForm }: Params) => {\n if (childs.length === 0 || values(assemblyOptionsMap).length === 0) {\n return []\n }\n\n return buildAddedOptionsForItem(\n item,\n index,\n childs,\n assemblyOptionsMap,\n orderForm\n )\n },\n parentPrice: ({ item }: Params) => item.sellingPrice * 0.01,\n removed: ({ item, orderForm, assemblyOptionsMap }: Params) => {\n if (values(assemblyOptionsMap).length === 0) {\n return []\n }\n\n return buildRemovedOptions(item, orderForm, assemblyOptionsMap)\n },\n },\n}\n\n```" } ]
code_store-graphql_6766a0b0
[ { "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 store-graphql/node/resolvers/checkout/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\nimport { compose, reject, path } from 'ramda'\n\nimport { headers, withAuthToken } from '../headers'\nimport httpResolver from '../httpResolver'\nimport { queries as logisticsQueries } from '../logistics/index'\nimport paths from '../paths'\nimport { fieldResolvers as slasResolvers } from './checkoutSLA'\nimport { resolvers as assemblyOptionsItemResolvers } from './assemblyOptionItem'\nimport {\n addOptionsForItems,\n buildAssemblyOptionsMap,\n isParentItem,\n} from './attachmentsHelper'\nimport { resolvers as orderFormItemResolvers } from './orderFormItem'\nimport paymentTokenResolver from './paymentTokenResolver'\nimport { fieldResolvers as shippingFieldResolvers } from './shipping'\nimport {\n ASPXAUTH_COOKIE,\n CHECKOUT_COOKIE,\n OWNERSHIP_COOKIE,\n parseCookie,\n} from '../../utils'\nimport {\n getSimulationPayloadsByItem,\n orderFormItemToSeller,\n} from '../../utils/simulation'\nimport { LogisticPickupPoint } from '../logistics/types'\nimport logisticPickupResolvers from '../logistics/fieldResolvers'\nimport { isSellerFlaggedForChangingOnSimulationBasedOnRegion } from '../../utils/flags/flagRegionalization'\n\nconst ALL_SET_COOKIES = [CHECKOUT_COOKIE, ASPXAUTH_COOKIE, OWNERSHIP_COOKIE]\n\nconst filterAllowedCookies = (setCookies: string[], allowList: string[]) => {\n return setCookies.filter((setCookie) => {\n const [key] = setCookie.split('=')\n\n return allowList.includes(key)\n })\n}\n\n/**\n * It will convert an integer to float moving the\n * float point two positions left.\n *\n * The OrderForm REST API return an integer\n * colapsing the floating point into the integer\n * part. We needed to make a convention of the product\n * price on different API's. Once the Checkout API\n * returns an integer instead of a float, and the\n * Catalog API returns a float.\n *\n * @param int An integer number\n */\nconst convertIntToFloat = (int: number) => int * 0.01\n\ninterface AddItemArgs {\n orderFormId?: string\n items?: OrderFormItemInput[]\n utmParams?: UTMParams\n utmiParams?: UTMIParams\n}\n\ninterface SkuPickupSLAListArgs {\n itemId: string\n seller: string\n lat: string\n long: string\n country: string\n}\n\ninterface SkuPickupSLAArgs extends SkuPickupSLAListArgs {\n pickupId: string\n}\n\ninterface SLAFromLogistics {\n id: string\n shippingEstimate: null\n pickupStoreInfo: {\n friendlyName: string\n address: CheckoutAddress\n }\n}\n\nconst checkouSlaFromLogisticPickup = (\n logisticPickup: LogisticPickupPoint\n): SLAFromLogistics => {\n return {\n id: logisticPickup.id,\n shippingEstimate: null,\n pickupStoreInfo: {\n friendlyName: logisticPickup.name,\n address: {\n ...logisticPickupResolvers.PickupPoint.address(logisticPickup),\n geoCoordinates: [\n logisticPickup.address.location.longitude,\n logisticPickup.address.location.latitude,\n ],\n },\n },\n }\n}\n\ntype AllSLAs = SLAItem | SLAFromLogistics\n\nconst shouldUpdateMarketingData = (\n orderFormMarketingTags: OrderFormMarketingData | null,\n utmParams?: UTMParams,\n utmiParams?: UTMIParams\n) => {\n const {\n utmCampaign = null,\n utmMedium = null,\n utmSource = null,\n utmiCampaign = null,\n utmiPart = null,\n utmipage = null,\n } = orderFormMarketingTags ?? {}\n\n if (\n !utmParams?.source &&\n !utmParams?.medium &&\n !utmParams?.campaign &&\n !utmiParams?.campaign &&\n !utmiParams?.page &&\n !utmiParams?.part\n ) {\n // Avoid updating at any costs if all fields are invalid\n return false\n }\n\n return (\n (utmParams?.source ?? null) !== utmSource ||\n (utmParams?.medium ?? null) !== utmMedium ||\n (utmParams?.campaign ?? null) !== utmCampaign ||\n (utmiParams?.part ?? null) !== utmiPart ||\n (utmiParams?.page ?? null) !== utmipage ||\n (utmiParams?.campaign ?? null) !== utmiCampaign\n )\n}\n\ntype Resolver<TArgs = any, TRoot = any> = (\n root: TRoot,\n args: TArgs,\n context: Context\n) => Promise<any>\n\nexport const fieldResolvers = {\n OrderForm: {\n cacheId: (orderForm: OrderForm) => {\n return orderForm.orderFormId\n },\n items: (orderForm: OrderForm) => {\n const childs = reject(isParentItem, orderForm.items)\n const assemblyOptionsMap = buildAssemblyOptionsMap(orderForm)\n\n return orderForm.items.map((item, index) => ({\n ...item,\n assemblyOptionsData: {\n assemblyOptionsMap,\n childs,\n index,\n orderForm,\n },\n }))\n },\n pickupPointCheckedIn: (orderForm: OrderForm, _: any, ctx: Context) => {\n const { isCheckedIn, checkedInPickupPointId } = orderForm\n\n if (!isCheckedIn || !checkedInPickupPointId) {\n return null\n }\n\n return logisticsQueries.pickupPoint(\n {},\n { id: checkedInPickupPointId },\n ctx\n )\n },\n value: (orderForm: OrderForm) => {\n return convertIntToFloat(orderForm.value)\n },\n },\n ...assemblyOptionsItemResolvers,\n ...orderFormItemResolvers,\n ...shippingFieldResolvers,\n ...slasResolvers,\n}\n\nconst replaceDomain = (host: string) => (cookie: string) =>\n cookie.replace(/domain=.+?(;|$)/, `domain=${host};`)\n\nexport async function syncWithStoreLocale(\n orderForm: OrderForm,\n cultureInfo: string,\n checkout: Context['clients']['checkout']\n) {\n const clientPreferencesData = orderForm.clientPreferencesData || {\n locale: cultureInfo,\n }\n\n const shouldUpdateClientPreferencesData =\n cultureInfo &&\n clientPreferencesData.locale &&\n cultureInfo !== clientPreferencesData.locale\n\n if (shouldUpdateClientPreferencesData) {\n const newClientPreferencesData = {\n ...clientPreferencesData,\n }\n\n newClientPreferencesData.locale = cultureInfo\n\n try {\n return await checkout.updateOrderFormClientPreferencesData(\n orderForm.orderFormId,\n newClientPreferencesData\n )\n } catch (e) {\n console.error(e)\n\n return orderForm\n }\n }\n\n return orderForm\n}\n\nexport async function setCheckoutCookies(\n rawHeaders: Record<string, any>,\n ctx: Context,\n allowList: string[] = ALL_SET_COOKIES\n) {\n const responseSetCookies: string[] = rawHeaders?.['set-cookie'] || []\n\n const host = ctx.get('x-forwarded-host')\n const forwardedSetCookies = filterAllowedCookies(\n responseSetCookies,\n allowList\n )\n\n const parseAndClean = compose(parseCookie, replaceDomain(host))\n\n const cleanCookies = forwardedSetCookies.map(parseAndClean)\n\n cleanCookies.forEach(({ name, value, options }) => {\n if (options.secure && !ctx.cookies.secure) {\n ctx.cookies.secure = true\n }\n\n ctx.cookies.set(name, value, options)\n })\n}\n\nexport const queries: Record<string, Resolver> = {\n orderForm: async (_, __, ctx) => {\n const {\n clients: { checkout },\n vtex: { segment, logger },\n } = ctx\n\n let { headers: responseHeaders, data } = await checkout.orderFormRaw()\n\n const hasBrokenCookie = data?.clientProfileData?.email?.startsWith(\n 'vrn--vtexsphinx--aws-us-east-1'\n )\n\n if (hasBrokenCookie) {\n logger.info({\n message: 'Broken order form',\n orderFormId: data.orderFormId,\n })\n\n await checkout.changeToAnonymousUser(data.orderFormId)\n\n const obj = await checkout.orderFormRaw()\n\n data = obj.data\n responseHeaders = obj.headers\n }\n\n const orderForm = await syncWithStoreLocale(\n data,\n segment!.cultureInfo,\n checkout\n )\n\n setCheckoutCookies(responseHeaders, ctx)\n\n return orderForm\n },\n\n searchOrderForm: async (_, { orderFormId }, ctx) => {\n const {\n clients: { checkout },\n } = ctx\n\n const orderForm = await checkout.orderForm(orderFormId)\n\n return orderForm\n },\n\n orders: (_, __, { clients: { checkout } }) => {\n return checkout.orders()\n },\n\n shipping: (_, args: any, { clients: { checkout } }) => {\n return checkout.simulation(args)\n },\n\n skuPickupSLAs: async (\n _: any,\n { itemId, seller, lat, long, country }: SkuPickupSLAListArgs,\n { clients: { checkout, logistics } }: Context\n ) => {\n const simulationPayload = {\n items: [\n {\n id: itemId,\n seller,\n quantity: 1,\n },\n ],\n country,\n shippingData: {\n selectedAddresses: [\n {\n geoCoordinates: [long, lat],\n country,\n },\n ],\n },\n }\n\n const [simulation, allPickupsOutput] = await Promise.all([\n checkout.simulation(simulationPayload),\n logistics.nearPickupPoints(lat, long),\n ])\n\n const slas = simulation?.logisticsInfo?.[0]?.slas ?? []\n const slasPickup = slas.filter(\n (sla) => sla.deliveryChannel === 'pickup-in-point'\n ) as AllSLAs[]\n\n const slaIdsSet = slasPickup.reduce((acc, { pickupStoreInfo }) => {\n if (pickupStoreInfo.address?.addressId) {\n acc.add(pickupStoreInfo.address.addressId)\n }\n\n return acc\n }, new Set<string>())\n\n allPickupsOutput.items.forEach((logisticItem) => {\n if (logisticItem.isActive && !slaIdsSet.has(logisticItem.id)) {\n const checkouSla = checkouSlaFromLogisticPickup(logisticItem)\n\n slasPickup.push(checkouSla)\n }\n })\n\n return slasPickup\n },\n\n skuPickupSLA: async (\n _: any,\n { itemId, seller, lat, long, country, pickupId }: SkuPickupSLAArgs,\n ctx: Context\n ) => {\n const slas = (await queries.skuPickupSLAs(\n {},\n { itemId, seller, lat, long, country },\n ctx\n )) as SLA[]\n\n return slas.find(\n (s) => path(['pickupStoreInfo', 'address', 'addressId'], s) === pickupId\n )\n },\n\n itemsWithSimulation: async (\n _,\n {\n items,\n regionId,\n salesChannel,\n postalCode,\n }: {\n items: ItemWithSimulationInput[]\n regionId?: string\n salesChannel?: string\n postalCode?: string\n },\n ctx: Context\n ) => {\n const {\n clients: { pvtCheckout },\n vtex: { segment, logger },\n } = ctx\n\n const changeSeller = isSellerFlaggedForChangingOnSimulationBasedOnRegion(\n ctx.vtex.account\n )\n\n const countryCode = ctx.vtex.segment?.countryCode\n\n return items.map((item) => {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const simulationPayloads = getSimulationPayloadsByItem(\n item,\n segment,\n regionId,\n changeSeller,\n postalCode,\n countryCode\n )\n\n const simulationPromises = simulationPayloads.map((payload) =>\n pvtCheckout.simulation(payload, salesChannel)\n )\n\n const simulations = await Promise.all(\n simulationPromises.map((p) => p.catch((e: any) => e))\n )\n\n const sellers = simulations.map((simulation, idx) => {\n if (simulation instanceof Error) {\n logger.error(simulation)\n\n return {\n error: simulation.message,\n sellerId: item.sellers[idx].sellerId,\n commertialOffer: {\n spotPrice: null,\n AvailableQuantity: 0,\n Price: null,\n ListPrice: null,\n PriceValidUntil: null,\n discountHighlights: [],\n teasers: [],\n Installments: [],\n },\n }\n }\n\n const [simulationItem] = simulation.items\n\n return orderFormItemToSeller({\n ...simulationItem,\n paymentData: simulation.paymentData,\n ratesAndBenefitsData: simulation.ratesAndBenefitsData,\n logisticsInfo: simulation.logisticsInfo ?? [],\n })\n })\n\n resolve({\n itemId: item.itemId,\n sellers,\n })\n })\n })\n },\n}\n\ninterface UTMParams {\n campaign?: string\n medium?: string\n source?: string\n}\n\ninterface UTMIParams {\n campaign?: string\n part?: string\n page?: string\n}\n\nexport const mutations: Record<string, Resolver> = {\n addItem: async (\n _,\n {\n orderFormId: paramsOrderFormId,\n items,\n utmParams,\n utmiParams,\n }: AddItemArgs,\n ctx: Context\n ) => {\n const {\n clients: { checkout },\n vtex,\n } = ctx\n\n const { orderFormId } = vtex\n\n if (orderFormId == null) {\n throw new Error('No orderformid in cookies')\n }\n\n if (items == null) {\n throw new UserInputError('No items to add provided')\n }\n\n if (orderFormId !== paramsOrderFormId) {\n ctx.vtex.logger.warn(\n `Different orderFormId found: provided=${paramsOrderFormId} and in cookies=${orderFormId}`\n )\n }\n\n const { marketingData, items: previousItems } = await checkout.orderForm()\n\n if (shouldUpdateMarketingData(marketingData, utmParams, utmiParams)) {\n const newMarketingData = {\n ...(marketingData ?? {}),\n }\n\n newMarketingData.utmCampaign = utmParams?.campaign\n newMarketingData.utmMedium = utmParams?.medium\n newMarketingData.utmSource = utmParams?.source\n newMarketingData.utmiCampaign = utmiParams?.campaign\n newMarketingData.utmiPart = utmiParams?.part\n newMarketingData.utmipage = utmiParams?.page\n\n if (newMarketingData.marketingTags == null) {\n delete newMarketingData.marketingTags\n } else if (Array.isArray(newMarketingData.marketingTags)) {\n newMarketingData.marketingTags = newMarketingData.marketingTags.filter(\n Boolean\n )\n }\n\n const atLeastOneValidField = Object.values(newMarketingData).some(\n (value) => {\n if (value == null || value === '') {\n return false\n }\n\n if (Array.isArray(value) && value.length === 0) {\n return false\n }\n\n return true\n }\n )\n\n // If all fields of newMarketingData are invalid, it causes checkout to answer with an error 400\n if (atLeastOneValidField) {\n try {\n await checkout.updateOrderFormMarketingData(\n orderFormId,\n newMarketingData\n )\n } catch (e) {\n ctx.vtex.logger.error({\n message: 'Error when updating orderformmarketing data',\n id: orderFormId,\n chkArgs: JSON.stringify(newMarketingData),\n graphqlArgs: JSON.stringify({ utmParams, utmiParams }),\n })\n }\n }\n }\n\n const cleanItems = items.map(({ options, ...rest }) => rest)\n const withOptions = items.filter(\n ({ options }) => !!options && options.length > 0\n )\n\n const addItem = await checkout.addItem(orderFormId, cleanItems)\n\n await addOptionsForItems(withOptions, checkout, addItem, previousItems)\n\n return withOptions.length === 0 ? addItem : checkout.orderForm()\n },\n\n addOrderFormPaymentToken: paymentTokenResolver,\n\n cancelOrder: async (\n _,\n { orderFormId, reason },\n { clients: { checkout } }\n ) => {\n await checkout.cancelOrder(orderFormId, reason)\n\n return true\n },\n\n createPaymentSession: httpResolver({\n enableCookies: true,\n headers: withAuthToken(headers.json),\n method: 'POST',\n secure: true,\n url: paths.gatewayPaymentSession,\n }),\n\n createPaymentTokens: httpResolver({\n data: ({ payments }: any) => payments,\n enableCookies: true,\n headers: withAuthToken(headers.json),\n method: 'POST',\n url: paths.gatewayTokenizePayment,\n }),\n\n setOrderFormCustomData: (\n _,\n { appId, field, value },\n { clients: { checkout }, vtex: { orderFormId } }\n ) => {\n if (orderFormId == null) {\n throw new Error('No orderformid in cookies')\n }\n\n return checkout.setOrderFormCustomData(orderFormId, appId, field, value)\n },\n\n updateItems: (\n _,\n { orderFormId: paramsOrderFormId, items },\n { clients: { checkout }, vtex }\n ) => {\n const { orderFormId } = vtex\n\n if (orderFormId == null) {\n throw new Error('No orderformid in cookies')\n }\n\n if (orderFormId !== paramsOrderFormId) {\n vtex.logger.warn(\n `Different orderFormId found: provided=${paramsOrderFormId} and in cookies=${vtex.orderFormId}`\n )\n }\n\n return checkout.updateItems(orderFormId, items)\n },\n\n updateOrderFormIgnoreProfile: (\n _,\n { ignoreProfileData },\n { clients: { checkout }, vtex: { orderFormId } }\n ) => {\n if (orderFormId == null) {\n throw new Error('No orderformid in cookies')\n }\n\n return checkout.updateOrderFormIgnoreProfile(orderFormId, ignoreProfileData)\n },\n\n updateOrderFormPayment: (\n _,\n { payments },\n { clients: { checkout }, vtex: { orderFormId } }\n ) => {\n if (orderFormId == null) {\n throw new Error('No orderformid in cookies')\n }\n\n return checkout.updateOrderFormPayment(orderFormId, payments)\n },\n\n updateOrderFormProfile: (_, { fields }, ctx) => {\n const {\n clients: { checkout },\n vtex: { orderFormId },\n } = ctx\n\n if (orderFormId == null) {\n throw new Error('No orderformid in cookies')\n }\n\n return checkout.updateOrderFormProfile(orderFormId, fields, ctx)\n },\n\n updateOrderFormShipping: async (_, { address }, ctx) => {\n const {\n clients: { checkout },\n vtex: { orderFormId },\n } = ctx\n\n if (orderFormId == null) {\n throw new Error('No orderformid in cookies')\n }\n\n return checkout.updateOrderFormShipping(orderFormId, {\n clearAddressIfPostalCodeNotFound: false,\n selectedAddresses: [address],\n })\n },\n\n addAssemblyOptions: (\n _,\n { itemId, assemblyOptionsId, options },\n { clients: { checkout }, vtex: { orderFormId } }\n ) => {\n if (orderFormId == null) {\n throw new Error('No orderformid in cookies')\n }\n\n const body = {\n composition: {\n items: options,\n },\n noSplitItem: true,\n }\n\n return checkout.addAssemblyOptions(\n orderFormId,\n itemId,\n assemblyOptionsId,\n body\n )\n },\n\n updateOrderFormCheckin: (\n _,\n { checkin }: any,\n { clients: { checkout }, vtex: { orderFormId } }\n ) => {\n if (orderFormId == null) {\n throw new Error('No orderformid in cookies')\n }\n\n return checkout.updateOrderFormCheckin(orderFormId, checkin)\n },\n\n newOrderForm: async (_, { orderFormId }, ctx) => {\n const {\n clients: { checkout },\n } = ctx\n\n const { data, headers: responseHeaders } = await checkout.newOrderForm(\n orderFormId\n )\n\n await setCheckoutCookies(responseHeaders, ctx)\n\n return data\n },\n}\n\n```" } ]
code_store-graphql_ed0314e1
[ { "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 store-graphql/node/resolvers/checkout/attachmentsHelper.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n all,\n filter,\n find,\n partition,\n propEq,\n omit,\n compose,\n equals,\n} from 'ramda'\n\nexport const CHOICE_TYPES = {\n MULTIPLE: 'MULTIPLE',\n SINGLE: 'SINGLE',\n TOGGLE: 'TOGGLE',\n}\n\nconst getNewItemsOnly = (\n previousItems: OrderFormItem[],\n allItems: OrderFormItem[]\n) => {\n const idSet = new Set<string>()\n\n previousItems.forEach((item) => idSet.add(item.uniqueId))\n\n return allItems.filter((item) => !idSet.has(item.uniqueId))\n}\n\nconst findRecentlyAddedParent = (\n recentlyAdded: OrderFormItem[],\n id: string,\n assemblyId: string | null\n) =>\n recentlyAdded.find(\n (i) => i.id === id && i.parentAssemblyBinding === assemblyId\n )\n\ntype OptionItems = Array<Omit<AssemblyOptionInput, 'assemblyId'>>\n\ninterface OptionRequestUnit {\n items: OptionItems\n inputValues: Record<string, string | boolean>\n}\n\ninterface AddOptionsLogicInput {\n checkout: Context['clients']['checkout']\n orderForm: OrderForm\n itemIndex: string | number\n options?: AssemblyOptionInput[]\n oldItems: OrderFormItem[]\n}\n\ninterface AssemblyOptionBody {\n noSplitItem?: boolean\n composition?: {\n items: Array<{\n id: string\n quantity: number\n seller: string\n }>\n }\n inputValues?: Record<string, string>\n}\n\nconst addAssemblyBody = (option: OptionRequestUnit) => {\n const body: AssemblyOptionBody = {}\n\n if (option.items.length > 0) {\n body.noSplitItem = true\n body.composition = {\n items: option.items.map(omit(['options', 'inputValues'])),\n }\n }\n\n if (option.inputValues) {\n body.noSplitItem = true\n body.inputValues = Object.keys(option.inputValues).reduce<\n Record<string, string>\n >((acc, key) => {\n // Transforming boolean values to string\n acc[key] = `${option.inputValues[key]}`\n\n return acc\n }, {})\n }\n\n return body\n}\n\nconst removeAssemblyBody = (option: OptionRequestUnit) => ({\n composition: {\n items: option.items.map(omit(['quantity', 'options'])),\n },\n})\n\nconst joinOptionsWithType = (options: AssemblyOptionInput[]) => {\n const result: Record<string, OptionRequestUnit> = {}\n\n for (const option of options) {\n const { assemblyId, ...rest } = option\n const currentArray = result[assemblyId]?.items || []\n\n if (rest.id) {\n currentArray.push(rest)\n }\n\n result[assemblyId] = {\n inputValues: rest.inputValues,\n items: currentArray,\n }\n }\n\n return result\n}\n\nconst addOptionsRecursive = async (\n items: OptionItems,\n assemblyId: string,\n orderForm: OrderForm,\n oldItems: OrderFormItem[],\n checkout: Context['clients']['checkout']\n) => {\n const recentlyAdded = getNewItemsOnly(oldItems, orderForm.items)\n const results = []\n\n for (const item of items) {\n const parentItem = findRecentlyAddedParent(\n recentlyAdded,\n item.id!.toString(),\n assemblyId\n )\n\n const parentIndex =\n parentItem &&\n orderForm.items.findIndex(propEq('uniqueId', parentItem.uniqueId))\n\n if (parentIndex == null || parentIndex < 0) {\n continue\n }\n\n results.push(\n addOptionsLogic({\n checkout,\n itemIndex: parentIndex,\n options: item.options,\n orderForm,\n oldItems,\n })\n )\n }\n\n await Promise.all(results)\n}\n\nconst addOptionsLogic = async (input: AddOptionsLogicInput) => {\n const { checkout, orderForm, itemIndex, options, oldItems } = input\n\n if (!options || options.length === 0) {\n return\n }\n\n const isRemove = (option: AssemblyOptionInput) => option.quantity === 0\n const [toRemove, toAdd] = partition<AssemblyOptionInput>(isRemove, options)\n const joinedToAdd = joinOptionsWithType(toAdd)\n const joinedToRemove = joinOptionsWithType(toRemove)\n const idsToAdd = Object.keys(joinedToAdd)\n const idsToRemove = Object.keys(joinedToRemove)\n let recentOrderForm = orderForm\n\n for (const assemblyId of idsToRemove) {\n const parsedOptions = joinedToRemove[assemblyId]\n // eslint-disable-next-line no-await-in-loop\n const response = await checkout\n .removeAssemblyOptions(\n orderForm.orderFormId,\n itemIndex,\n assemblyId,\n removeAssemblyBody(parsedOptions)\n )\n // eslint-disable-next-line no-loop-func\n .catch(() => ({ data: recentOrderForm }))\n\n recentOrderForm = response.data\n }\n\n for (const assemblyId of idsToAdd) {\n const parsedOptions = joinedToAdd[assemblyId]\n\n // eslint-disable-next-line no-await-in-loop\n recentOrderForm = await checkout\n .addAssemblyOptions(\n orderForm.orderFormId,\n itemIndex,\n assemblyId,\n addAssemblyBody(parsedOptions)\n )\n // eslint-disable-next-line no-loop-func\n .catch(() => recentOrderForm)\n }\n\n const results = []\n\n for (const assemblyId of idsToAdd) {\n const parsedOptions = joinedToAdd[assemblyId]\n const itemsWithRecursiveOptions = parsedOptions.items.filter(\n (arg) => !!arg.options\n )\n\n if (itemsWithRecursiveOptions.length > 0) {\n results.push(\n addOptionsRecursive(\n itemsWithRecursiveOptions,\n assemblyId,\n recentOrderForm,\n oldItems,\n checkout\n )\n )\n }\n }\n\n await Promise.all(results)\n}\n\n/**\n * Goes through each item being added and check if there are any attachments into that item object.\n * If yes, call appropriate checkout API to add assembly option to that item.\n * @param items items coming from the addItem mutation\n * @param checkout checkout datasource\n * @param orderForm order form object with current items and ID\n */\nexport const addOptionsForItems = async (\n items: OrderFormItemInput[],\n checkout: Context['clients']['checkout'],\n orderForm: OrderForm,\n oldItems: OrderFormItem[]\n) => {\n const recentlyAdded =\n items.length > 0 ? getNewItemsOnly(oldItems, orderForm.items) : []\n\n const results = []\n\n for (const item of items) {\n if (!item.options || item.options.length === 0) {\n continue\n }\n\n const parentItem = findRecentlyAddedParent(\n recentlyAdded,\n item.id!.toString(),\n null\n )\n\n const parentIndex =\n parentItem &&\n orderForm.items.findIndex(propEq('uniqueId', parentItem.uniqueId))\n\n if (parentIndex == null || parentIndex < 0) {\n continue\n }\n\n results.push(\n addOptionsLogic({\n checkout,\n itemIndex: parentIndex,\n options: item.options,\n orderForm,\n oldItems,\n })\n )\n }\n\n await Promise.all(results)\n}\n\nconst filterCompositionNull = (assemblyOptions: AssemblyOption[]) =>\n assemblyOptions.filter(({ composition }) => !!composition)\n\nexport const buildAssemblyOptionsMap = (orderForm: OrderForm) => {\n const metadataItems = orderForm?.itemMetadata?.items ?? []\n\n return metadataItems\n .filter(\n ({ assemblyOptions }) => assemblyOptions && assemblyOptions.length > 0\n )\n .reduce((prev, curr) => {\n prev[curr.id] = filterCompositionNull(curr.assemblyOptions)\n\n return prev\n }, {} as Record<string, AssemblyOption[]>)\n}\n\nconst isParentOptionSingleChoice = ({ composition }: AssemblyOption) => {\n if (!composition) {\n return false\n }\n\n return composition.minQuantity === 1 && composition.maxQuantity === 1\n}\n\nconst isParentOptionToggleChoice = ({ composition }: AssemblyOption) => {\n if (!composition) {\n return false\n }\n\n return all(propEq('maxQuantity', 1))(composition.items)\n}\n\nexport const getItemChoiceType = (childAssemblyData?: AssemblyOption) => {\n if (!childAssemblyData) {\n return CHOICE_TYPES.MULTIPLE\n }\n\n const isSingle = isParentOptionSingleChoice(childAssemblyData!)\n\n if (isSingle) {\n return CHOICE_TYPES.SINGLE\n }\n\n const isToggle = isParentOptionToggleChoice(childAssemblyData)\n\n if (isToggle) {\n return CHOICE_TYPES.TOGGLE\n }\n\n return CHOICE_TYPES.MULTIPLE\n}\n\nconst getItemComposition = (\n id: string,\n childAssemblyData?: AssemblyOption\n): CompositionItem | undefined => {\n if (!childAssemblyData) {\n return undefined\n }\n\n const items = childAssemblyData.composition?.items ?? []\n\n return find<CompositionItem>(propEq('id', id), items)\n}\n\nconst isSonOfItem = (parentIndex: number) =>\n propEq('parentItemIndex', parentIndex)\n\nexport const isParentItem = ({\n parentItemIndex,\n parentAssemblyBinding,\n}: OrderFormItem) => parentItemIndex == null && parentAssemblyBinding == null\n\nexport const getPositionInOrderForm = (\n { items }: OrderForm,\n { uniqueId }: OrderFormItem\n) => items.findIndex((orderItem) => orderItem.uniqueId === uniqueId)\n\nexport const buildAddedOptionsForItem = (\n item: OrderFormItem,\n index: number,\n childs: OrderFormItem[],\n assemblyOptionsMap: Record<string, AssemblyOption[]>,\n orderForm: OrderForm\n) => {\n const children = filter<OrderFormItem>(isSonOfItem(index), childs)\n\n return children.map((childItem) => {\n const parentAssemblyOptions = assemblyOptionsMap[item.id]\n\n const childAssemblyData = find<AssemblyOption>(\n propEq('id', childItem.parentAssemblyBinding)\n )(parentAssemblyOptions)\n\n const compositionItem = getItemComposition(\n childItem.id,\n childAssemblyData\n ) ?? { initialQuantity: 0 }\n\n return {\n choiceType: getItemChoiceType(childAssemblyData),\n compositionItem,\n extraQuantity:\n childItem.quantity / item.quantity - compositionItem.initialQuantity,\n item: {\n ...childItem,\n assemblyOptionsData: {\n index: getPositionInOrderForm(orderForm, childItem),\n assemblyOptionsMap,\n childs,\n orderForm,\n },\n },\n normalizedQuantity: childItem.quantity / item.quantity,\n }\n })\n}\n\nconst findInitialItemOnCart = (initialItem: InitialItem) => (\n cartItem: OrderFormItem\n) =>\n cartItem.parentAssemblyBinding === initialItem.parentAssemblyBinding &&\n initialItem.id === cartItem.id\n\nconst isInitialItemMissing = (\n parentCartItem: OrderFormItem,\n orderForm: OrderForm\n) => (initialItem: InitialItem): RemovedItem | null => {\n const orderFormItem = find(\n findInitialItemOnCart(initialItem),\n orderForm.items\n )\n\n const selectedQuantity =\n orderFormItem && orderFormItem.quantity / parentCartItem.quantity\n\n // If we selected more or same as initialQuantity, item is not missing\n if (selectedQuantity && selectedQuantity >= initialItem.initialQuantity) {\n return null\n }\n\n const metadataItems = orderForm?.itemMetadata?.items\n const metadataItem =\n metadataItems && find(propEq('id', initialItem.id), metadataItems)\n\n if (!metadataItem) {\n return null\n }\n\n return {\n initialQuantity: initialItem.initialQuantity,\n name: metadataItem.name,\n removedQuantity: initialItem.initialQuantity - (selectedQuantity ?? 0),\n }\n}\n\ninterface InitialItem extends CompositionItem {\n parentAssemblyBinding: string\n}\n\nconst isAssemblyOptionToggle = compose<AssemblyOption, string, boolean>(\n equals(CHOICE_TYPES.TOGGLE),\n getItemChoiceType\n)\n\nexport const buildRemovedOptions = (\n item: OrderFormItem,\n orderForm: OrderForm,\n assemblyOptionsMap: Record<string, AssemblyOption[]>\n): RemovedItem[] => {\n const assemblyOptions = assemblyOptionsMap[item.id]\n\n if (!assemblyOptions) {\n return []\n }\n\n // For now, it makes sense it should only work for toggle type of assembly options\n const onlyToggleAssemblies = assemblyOptions.filter(isAssemblyOptionToggle)\n\n const itemsWithInitials: InitialItem[] = []\n\n for (const assemblyOption of onlyToggleAssemblies) {\n if (assemblyOption.composition) {\n for (const compItem of assemblyOption.composition.items) {\n if (compItem.initialQuantity > 0) {\n itemsWithInitials.push({\n ...compItem,\n parentAssemblyBinding: assemblyOption.id,\n })\n }\n }\n }\n }\n\n const removed = itemsWithInitials\n .map(isInitialItemMissing(item, orderForm))\n .filter(Boolean) as RemovedItem[]\n\n return removed\n}\n\n```" } ]
code_store-graphql_b2ba86ba
[ { "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 store-graphql/node/resolvers/checkout/checkoutSLA.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop } from 'ramda'\n\nexport const fieldResolvers = {\n CheckoutSLA: {\n cacheId: prop('id'),\n },\n}\n\n```" } ]
code_store-graphql_31ae4119
[ { "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 store-graphql/node/resolvers/profile/fieldResolvers.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop } from 'ramda'\n\nimport {\n getAddresses,\n getPasswordLastUpdate,\n getPayments,\n pickCustomFieldsFromData,\n} from './services'\n\nexport default {\n Address: {\n cacheId: prop('addressName'),\n id: prop('addressName'),\n geoCoordinates: ({ geoCoordinate, geoCoordinates }: any) =>\n geoCoordinate || geoCoordinates,\n },\n PaymentProfile: {\n cacheId: prop('id'),\n },\n Profile: {\n address: (obj: any, __: any, context: any) => getAddresses(context, obj),\n addresses: (obj: any, __: any, context: any) => getAddresses(context, obj),\n birthDate: (obj: any) =>\n obj.birthDate ? new Date(obj.birthDate).toISOString() : obj.birthDate,\n cacheId: prop('email'),\n customFields: (obj: any) =>\n typeof obj.customFields === 'string'\n ? pickCustomFieldsFromData(obj.customFields, obj)\n : obj.customFields,\n passwordLastUpdate: (_: any, __: any, context: any) =>\n getPasswordLastUpdate(context),\n payments: (_: any, __: any, context: any) => getPayments(context),\n profilePicture: (obj: any, _: any, context: any) =>\n obj.profilePicture &&\n `https://${context.vtex.account}.vteximg.com.br/assets/vtex.store-graphql/image/${obj.profilePicture}`,\n // the next transformations are necessary since the profile system and\n // this profile graphql query (the same applies to mutations) were built upon different contracts.\n corporateDocument: (obj: any, _: any, __: any) => obj.businessDocument,\n isCorporate: (obj: any, _: any, __: any) => obj.isPJ === 'True',\n tradeName: (obj: any, _: any, __: any) => obj.fancyName,\n pii: (obj: any, _: any, __: any) => obj.pii,\n },\n ProfileCustomField: {\n cacheId: (root: any) => root.key,\n },\n}\n\n```" } ]
code_store-graphql_b18446c8
[ { "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 store-graphql/node/resolvers/profile/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { path } from 'ramda'\nimport { MutationSaveAddressArgs } from 'vtex.store-graphql'\n\nimport type { DefaultUser, User } from '../../dataSources/identity'\nimport fieldR from './fieldResolvers'\nimport {\n createAddress,\n deleteAddress,\n getProfile,\n updateAddress,\n updateProfile,\n updateProfilePicture,\n saveAddress,\n} from './services'\n\nconst TRUE = 'True'\nconst FALSE = 'False'\n\ninterface CheckUserAuthorizationParams {\n context: Context\n email: string\n}\n\nconst checkUserAuthorization = async ({\n context,\n email,\n}: CheckUserAuthorizationParams): Promise<boolean> => {\n const {\n vtex: { storeUserAuthToken, account },\n dataSources: { identity },\n } = context\n\n let validUser = !!storeUserAuthToken\n\n const tokenUser = await identity\n .getUserWithToken(storeUserAuthToken ?? '')\n .catch(() => {\n return { authStatus: '' } as DefaultUser\n })\n\n validUser =\n validUser &&\n Boolean(tokenUser) &&\n 'id' in tokenUser &&\n tokenUser.account === account &&\n tokenUser.user.length === email.length\n\n for (let i = 0; i < email.length; i++) {\n if (validUser && email[i] !== (tokenUser as User)?.user?.[i]) {\n validUser = false\n }\n }\n\n return validUser\n}\n\ninterface SubscribeNewsletterArgs {\n email: string\n fields?: {\n name?: string\n phone?: string\n bindingUrl?: string\n bindingId?: string\n }\n isNewsletterOptIn: boolean\n}\n\nexport const mutations = {\n createAddress: (_: any, { fields }: any, context: Context) =>\n createAddress(context, fields),\n\n saveAddress: (_: void, args: MutationSaveAddressArgs, context: Context) =>\n saveAddress(context, args),\n\n deleteAddress: (_: any, { id }: any, context: Context) =>\n deleteAddress(context, id),\n\n updateAddress: (_: any, args: any, context: Context) =>\n updateAddress(context, args),\n\n updateProfile: (_: any, { fields, customFields }: any, context: Context) =>\n updateProfile(context, fields, customFields),\n\n updateProfilePicture: (_: any, __: any, context: Context) =>\n updateProfilePicture('updateProfilePicture', context),\n\n uploadProfilePicture: (_: any, __: any, context: Context) =>\n updateProfilePicture('uploadProfilePicture', context),\n\n subscribeNewsletter: async (\n _: any,\n { email, fields, isNewsletterOptIn }: SubscribeNewsletterArgs,\n context: Context\n ) => {\n const { profile } = context.clients\n const optIn =\n isNewsletterOptIn === undefined || isNewsletterOptIn === true\n ? TRUE\n : FALSE\n\n const updatedPersonalPreferences: PersonalPreferences = {\n isNewsletterOptIn: optIn,\n }\n\n const userProfile = await profile\n .getProfileInfo({ email, userId: '' }, context, undefined)\n .catch(() => ({}))\n\n if (fields) {\n const { name, phone, bindingId, bindingUrl } = fields\n\n const userHasFirstName = Boolean(userProfile.firstName)\n const userHasPhone = Boolean(userProfile.cellPhone)\n const userHasBindingId = Boolean(userProfile.bindingId)\n const userHasBindingUrl = Boolean(userProfile.bindingUrl)\n\n // Prevents 'firstName' field from being overridden.\n if (!userHasFirstName && name) {\n updatedPersonalPreferences.firstName = name\n }\n\n // Prevents 'homePhone' field from being overridden.\n if (!userHasPhone && phone) {\n updatedPersonalPreferences.homePhone = phone\n }\n\n // Prevents 'bindingId' field from being overridden.\n if (!userHasBindingId && bindingId) {\n updatedPersonalPreferences.bindingId = bindingId\n }\n\n // Prevents 'bindingUrl' field from being overridden.\n if (!userHasBindingUrl && bindingUrl) {\n updatedPersonalPreferences.bindingUrl = bindingUrl\n }\n }\n\n let updateData = true\n\n if (userProfile.createdIn) {\n updateData = await checkUserAuthorization({\n context,\n email,\n })\n }\n\n if (updateData) {\n await profile.updatePersonalPreferences(\n { email, userId: '' },\n updatedPersonalPreferences,\n context\n )\n }\n\n return true\n },\n}\n\nexport const queries = {\n profile: (_: any, { customFields }: any, context: Context) =>\n getProfile(context, customFields),\n\n checkProfileAllowed: async (_: any, __: any, context: Context) => {\n const {\n clients: { catalog, customSession },\n vtex: { segment },\n cookies,\n } = context\n\n const salesChannel = segment ? segment.channel : null\n\n const { sessionData } = await customSession.getSession(\n cookies.get('vtex_session')!,\n ['*']\n )\n\n const email: string | undefined = path(\n ['namespaces', 'profile', 'email', 'value'],\n sessionData\n )\n\n const availableSalesChannels = await catalog\n .salesChannelAvailable(email)\n .catch(() => [])\n\n // Checking with `==` since `sc.Id` is an Integer and salesChannel a string\n // eslint-disable-next-line eqeqeq\n const available = availableSalesChannels.find((sc) => sc.Id == salesChannel)\n\n return {\n allowed: Boolean(available),\n condition: available\n ? 'authorized'\n : email\n ? 'forbidden' // The user is logged in and not allowed\n : 'unauthorized', // We don't know the user identity\n }\n },\n}\n\nexport const fieldResolvers = fieldR\n\n```" } ]
code_store-graphql_9ad2eb83
[ { "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 store-graphql/node/resolvers/profile/services.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { parse } from 'cookie'\nimport { compose, mapObjIndexed, pick, split, values } from 'ramda'\nimport { MutationSaveAddressArgs, AddressInput } from 'vtex.store-graphql'\n\nimport { generateRandomName } from '../../utils'\nimport { makeRequest } from '../auth'\nimport paths from '../paths'\n\nexport async function getProfile(context: Context, customFields?: string) {\n const {\n clients: { profile },\n vtex: { currentProfile },\n } = context\n\n const extraFields = customFields\n ? `${customFields},profilePicture,id`\n : `profilePicture,id`\n\n return profile\n .getProfileInfo(currentProfile, context, extraFields)\n .then((profileData) => {\n if (profileData) {\n return {\n ...profileData,\n customFields,\n }\n }\n\n return { email: currentProfile.email }\n })\n}\n\nexport function getPasswordLastUpdate(context: Context) {\n const {\n request: {\n headers: { cookie },\n },\n vtex: { account },\n } = context\n\n const url = paths.getUser(account)\n const parsedCookies = parse(cookie)\n const userCookie: string = parsedCookies[`VtexIdclientAutCookie_${account}`]\n\n if (!userCookie) return null\n\n return makeRequest({\n ctx: context.vtex,\n url,\n authCookieAdmin: userCookie,\n }).then((response: any) => response.data.passwordLastUpdate)\n}\n\nexport function getAddresses(context: Context, currentUserProfile?: Profile) {\n const {\n clients: { profile },\n vtex: { currentProfile },\n } = context\n\n // Filter out temporarily addresses with addressType \"pickup\" because its also saved at Profile V2\n return profile\n .getUserAddresses(currentProfile, context, currentUserProfile)\n .then((addresses: any[]) => {\n const residentialAddresses = addresses.filter(\n (address: { addressType: string }) => address.addressType !== 'pickup'\n )\n return residentialAddresses\n })\n}\n\nexport async function getPayments(context: Context) {\n const {\n clients: { profile, licenseManagerExtended },\n vtex: { currentProfile },\n } = context\n\n const { PIIEnabled } = await licenseManagerExtended.getCurrentAccount()\n const paymentsRawData = await profile.getUserPayments(currentProfile, context)\n const isPaymentDataEmpty = PIIEnabled\n ? !paymentsRawData[0]?.document?.paymentData\n : !paymentsRawData?.paymentData\n\n if (isPaymentDataEmpty) {\n return null\n }\n const addresses = await getAddresses(context)\n\n const paymentData = PIIEnabled\n ? paymentsRawData[0]?.document?.paymentData\n : JSON.parse(paymentsRawData.paymentData)\n\n const { availableAccounts } = paymentData\n\n return availableAccounts.map((account: any) => {\n const { bin, availableAddresses, accountId, ...cleanAccount } = account\n const accountAddress = addresses.find(\n (addr: Address) => addr.addressName === availableAddresses[0]\n )\n\n return { ...cleanAccount, id: accountId, address: accountAddress }\n })\n}\n\nexport async function updateProfile(\n context: Context,\n profile: Profile,\n customFields: CustomField[] | undefined\n) {\n const {\n clients,\n vtex: { currentProfile },\n } = context\n\n const extraFields = customFields && mapCustomFieldsToObjNStr(customFields)\n\n // Remove email field from profile to prevent sending it in the payload\n const { email, ...profileWithoutEmail } = profile\n\n const newData = {\n ...profileWithoutEmail,\n // Read the comments in Profile in fieldResolvers.ts files\n // to understand the following transformations\n businessDocument: profile.corporateDocument,\n isPJ: profile.isCorporate ? 'True' : 'False',\n fancyName: profile.tradeName,\n ...extraFields?.customFieldsObj,\n }\n\n return clients.profile\n .updateProfileInfo(\n currentProfile,\n newData,\n context,\n extraFields?.customFieldsStr\n )\n .then(() => getProfile(context, extraFields?.customFieldsStr))\n}\n\nexport function updateProfilePicture(mutationsName: string, context: Context) {\n console.warn(\n `The ${mutationsName} mutation is deprecated and no longer supported.`\n )\n\n return getProfile(context)\n}\n\n// CRUD Address\n\nexport function createAddress(context: Context, address: AddressInput) {\n const {\n clients: { profile },\n vtex: { currentProfile },\n } = context\n\n const addressesData = mapNewAddressToProfile(address, currentProfile)\n\n return profile\n .updateAddress(currentProfile, addressesData, context)\n .then(() => getProfile(context))\n}\n\nexport function deleteAddress(context: Context, addressName: string) {\n const {\n clients: { profile },\n vtex: { currentProfile },\n } = context\n\n return profile\n .deleteAddress(currentProfile, addressName, context)\n .then(() => getProfile(context))\n}\n\nexport function updateAddress(\n context: Context,\n { id, fields: { geoCoordinates, ...addressFields } }: UpdateAddressArgs\n) {\n const {\n clients: { profile },\n vtex: { currentProfile },\n } = context\n\n const addressesData = {} as any\n\n addressesData[id] = JSON.stringify({\n ...addressFields,\n geoCoordinate: geoCoordinates,\n userId: currentProfile.userId,\n })\n\n return profile\n .updateAddress(currentProfile, addressesData, context)\n .then(() => getProfile(context))\n}\n\nexport function pickCustomFieldsFromData(customFields: string, data: any) {\n return (\n customFields &&\n compose(\n values,\n mapObjIndexed((value, key) => ({ key, value })),\n pick(split(',', customFields)) as any\n )(data)\n )\n}\n\nexport async function saveAddress(\n context: Context,\n args: MutationSaveAddressArgs\n): Promise<Address> {\n const {\n clients: { profile },\n vtex: { currentProfile },\n } = context\n\n const addressesData = mapNewAddressToProfile(args.address, currentProfile)\n const [newId] = Object.keys(addressesData)\n\n const result = await profile.updateAddress(\n currentProfile,\n addressesData,\n context\n )\n\n if (result?.document) {\n return result.document\n }\n\n if (result?.id) {\n return result.id\n }\n\n const currentAddresses = await profile.getUserAddresses(\n currentProfile,\n context\n )\n\n return currentAddresses.find(\n (address: Address) => address.addressName === newId\n ) as Address\n}\n\n// Aux\n\nfunction mapCustomFieldsToObjNStr(customFields: CustomField[] = []) {\n let customFieldsStr = ''\n const customFieldsObj = customFields.reduce((acc: any, currentValue, i) => {\n customFieldsStr +=\n i < customFields.length - 1 ? `${currentValue.key},` : currentValue.key\n\n acc[currentValue.key] = currentValue.value\n\n return acc\n }, {})\n\n return {\n customFieldsObj,\n customFieldsStr,\n }\n}\n\nfunction mapNewAddressToProfile(\n address: AddressInput,\n currentProfile: CurrentProfile,\n id: string = generateRandomName()\n) {\n const { geoCoordinates, ...addr } = address\n\n return {\n [id]: JSON.stringify({\n ...addr,\n geoCoordinate: geoCoordinates,\n addressName: id,\n userId: currentProfile.userId,\n }),\n }\n}\n\ninterface UpdateAddressArgs {\n id: string\n fields: Address\n}\n\ninterface CustomField {\n key: string\n value: string\n}\n\n```" } ]
code_store-graphql_44021b77
[ { "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 store-graphql/node/resolvers/list/util.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\nimport { filter, path } from 'ramda'\n\nimport { Clients } from '../../clients'\nimport { Catalog } from '../../clients/catalog'\n\nexport const fields = [\n 'name',\n 'isPublic',\n 'isEditable',\n 'owner',\n 'createdIn',\n 'updatedIn',\n 'items',\n 'id',\n]\nexport const fieldsListProduct = [\n 'id',\n 'quantity',\n 'skuId',\n 'productId',\n 'createdIn',\n]\nexport const acronymListProduct = 'LP'\nexport const acronymList = 'WL'\n\nexport interface Item {\n id: string\n skuId: string\n productId: string\n quantity: number\n}\n\nconst checkListItemQuantity = (quantity: any) => {\n if (!quantity || quantity < 0) {\n throw new UserInputError('The item quantity should be greater than 0')\n }\n}\n\n// Make this query to check if the skuId received is valid\n// If it isn't, it throws an exception.\nconst checkProduct = async (item: Item, catalog: Catalog) => {\n const response = await catalog.productBySku([path(['skuId'], item) as string])\n\n if (!response.length) {\n throw new UserInputError('Cannot add an invalid product')\n }\n}\n\nconst checkDuplicatedListItem = (items: Item[], item: Item) => {\n const itemDuplicated = filter(\n (i: Item) => path(['skuId'], i) === path(['skuId'], item),\n items\n )\n\n if (itemDuplicated.length > 1) {\n throw new UserInputError('Cannot add duplicated items.')\n }\n}\n\nconst validateListItem = (items: Item[], item: Item, clients: Clients) => {\n const { catalog } = clients\n\n checkListItemQuantity(path(['quantity'], item))\n checkDuplicatedListItem(items, item)\n checkProduct(item, catalog)\n}\n\n// eslint-disable-next-line @typescript-eslint/default-param-last\nconst validateItems = (items: Item[] = [], clients: Clients) => {\n items.forEach((item) => validateListItem(items, item, clients))\n}\n\nexport { validateItems, validateListItem }\n\n```" } ]
code_store-graphql_2a1055d5
[ { "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 store-graphql/node/resolvers/list/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\nimport { concat, groupBy, last, map, nth, path } from 'ramda'\n\nimport { Catalog } from '../../clients/catalog'\nimport { MasterData } from '../../clients/masterdata'\nimport {\n acronymList,\n acronymListProduct,\n fields,\n fieldsListProduct,\n Item,\n validateItems,\n} from './util'\n\nconst getListItemsWithProductInfo = (items: Item[], catalog: Catalog) =>\n Promise.all(\n map(async (item: Item) => {\n const productsResponse = await catalog.productBySku([\n path(['skuId'], item) as string,\n ])\n\n const product = nth(0, productsResponse)\n\n return { ...item, product }\n }, items)\n )\n\nconst getListItems = async (\n itemsId: string[],\n catalog: Catalog,\n masterdata: MasterData\n) => {\n const items: Item[] = itemsId\n ? ((await Promise.all(\n map(\n (id: string) =>\n masterdata.getDocument(acronymListProduct, id, fieldsListProduct),\n itemsId\n )\n )) as Item[])\n : []\n\n return getListItemsWithProductInfo(items, catalog)\n}\n\nconst addListItem = async (item: Item, masterdata: MasterData) => {\n const { DocumentId } = (await masterdata.createDocument(\n acronymListProduct,\n item\n )) as DocumentResponse\n\n return DocumentId\n}\n\nconst addItems = async (\n // eslint-disable-next-line @typescript-eslint/default-param-last\n items: Item[] = [],\n { clients, clients: { masterdata } }: Context\n) => {\n validateItems(items, clients)\n const promises = map(async (item) => addListItem(item, masterdata), items)\n\n return Promise.all(promises)\n}\n\nconst deleteItems = (items: Item[], masterdata: MasterData) =>\n items &&\n Promise.all(\n items.map((item: Item) =>\n masterdata.deleteDocument(\n acronymListProduct,\n path(['id'], item) as string\n )\n )\n )\n\nconst updateItems = async (items: Item[], masterdata: MasterData) => {\n const itemsWithoutDuplicated = Object.values(\n groupBy(({ skuId }) => skuId, items)\n ).map((itemArray) => last(itemArray)) as Item[]\n\n const itemsToBeDeleted = itemsWithoutDuplicated.filter(\n (item) => item?.id && item?.quantity === 0\n )\n\n const itemsToBeAdded = itemsWithoutDuplicated.filter((item) => !item?.id)\n const itemsToBeUpdated = itemsWithoutDuplicated.filter(\n (item) => item?.id && item?.quantity > 0\n )\n\n deleteItems(itemsToBeDeleted, masterdata)\n\n const itemsIdAdded = await Promise.all(\n map(async (item: Item) => addListItem(item, masterdata), itemsToBeAdded)\n )\n\n const itemsIdUpdated = map((item: Item) => {\n masterdata.updateDocument(\n acronymListProduct,\n path(['id'], item) ?? '',\n item\n )\n\n return path(['id'], item)\n }, itemsToBeUpdated)\n\n return concat(itemsIdAdded, itemsIdUpdated)\n}\n\nexport const queries = {\n list: async (\n _: any,\n { id }: any,\n { clients: { masterdata, catalog } }: Context\n ) => {\n const list = await masterdata.getDocument<any>(acronymList, id, fields)\n const items = await getListItems(list.items, catalog, masterdata)\n\n return { id, ...list, items }\n },\n\n listsByOwner: async (\n _: any,\n { owner, page, pageSize }: any,\n context: Context\n ) => {\n const {\n clients: { masterdata },\n } = context\n\n const lists = (await masterdata.searchDocuments<any>(\n acronymList,\n ['id'],\n `owner=${owner}`,\n { page, pageSize }\n )) as any[]\n\n const listsWithProducts = map(\n (list) => queries.list(_, { id: list.id }, context),\n lists\n )\n\n return Promise.all(listsWithProducts)\n },\n}\n\nexport const mutation = {\n createList: async (\n _: any,\n { list, list: { items } }: any,\n context: Context\n ) => {\n const {\n clients: { masterdata },\n } = context\n\n try {\n const itemsId = await addItems(items, context)\n const { DocumentId } = (await masterdata.createDocument(acronymList, {\n ...list,\n items: itemsId,\n })) as DocumentResponse\n\n return queries.list(_, { id: DocumentId }, context)\n } catch (error) {\n throw new UserInputError(`Cannot create list: ${error}`)\n }\n },\n\n deleteList: async (\n _: any,\n { id }: any,\n { clients: { masterdata } }: Context\n ) => {\n const { items } = await masterdata.getDocument<any>(acronymList, id, fields)\n\n await deleteItems(items, masterdata)\n\n return masterdata.deleteDocument(acronymList, id)\n },\n\n /**\n * Update the list informations and its items.\n * If the item given does not have the id, add it as a new item in the list\n * If the item given has got an id, but its quantity is 0, remove it from the list\n * Otherwise, update it.\n */\n updateList: async (\n _: any,\n { id, list, list: { items } }: any,\n context: Context\n ) => {\n const {\n clients: { masterdata },\n } = context\n\n try {\n const itemsUpdatedId = await updateItems(items, masterdata)\n\n await masterdata.updateDocument(acronymList, id, {\n ...list,\n items: itemsUpdatedId,\n } as any)\n\n return queries.list(_, { id }, context)\n } catch (error) {\n throw new UserInputError(`Cannot update the list: ${error}`)\n }\n },\n}\n\n```" } ]
code_store-graphql_663c8fa9
[ { "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 store-graphql/node/resolvers/benefits/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { flatten, indexOf, path } from 'ramda'\n\nimport { queries as checkoutQueries } from '../checkout'\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: { catalog } }: Context) => {\n const { teaserType, conditions, effects } = benefit\n\n if (teaserType !== CATALOG) {\n return\n }\n\n const {\n parameters: conditionsParameters,\n minimumQuantity = parseInt(DEFAULT_QUANTITY, 10),\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\n const discount = effectsParameters[index].value\n const products = await catalog.productBySku(skuIds)\n\n return products.map((product: any) => {\n const benefitSKUIds: any = []\n\n product.items.forEach((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\n return flatten(items)\n },\n },\n}\n\nexport const queries = {\n /**\n * There are two ways to make the request data\n * First of them is passing the graphql args with the items property which is an array of Shipping Items.\n * Second is passing just the id of the product itself as a graphql argument.\n */\n benefits: async (_: any, args: any, config: any) => {\n const requestBody = {\n items: args.items\n ? args.items\n : [\n {\n id: args.id,\n quantity: DEFAULT_QUANTITY,\n seller: DEFAULT_SELLER,\n },\n ],\n }\n\n const benefitsData = await checkoutQueries.shipping(_, requestBody, config)\n\n return path(['ratesAndBenefitsData', 'teaser'], benefitsData) || []\n },\n}\n\n```" } ]
code_store-graphql_0d342ecc
[ { "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 store-graphql/node/resolvers/logistics/fieldResolvers.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop } from 'ramda'\n\nimport { LogisticPickupPoint } from './types'\nimport { SalesChannel } from '../../clients/portal'\n\nexport default {\n LogisticsData: {\n shipsTo: async (obj: any, __: any, context: Context) => {\n if (!obj || !obj.shipsTo || obj.shipsTo.length === 0) {\n const defaultSalesChannelCountry = prop(\n 'CountryCode',\n (await context.clients.portal.defaultSalesChannel()) as SalesChannel\n )\n\n return [defaultSalesChannelCountry]\n }\n\n return obj.shipsTo\n },\n },\n PickupPoint: {\n address: ({ id, address: logAddress }: LogisticPickupPoint) => {\n const { country, location, ...rest } = logAddress\n\n return {\n ...rest,\n receiverName: null,\n addressId: id,\n addressType: 'pickup',\n country: country.acronym,\n geoCoordinate: [location.longitude, location.latitude],\n id,\n }\n },\n friendlyName: ({ name }: LogisticPickupPoint) => name,\n },\n}\n\n```" } ]
code_store-graphql_e390e974
[ { "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 store-graphql/node/resolvers/logistics/types.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface LogisticAddress {\n country: { acronym: string; name: string }\n location: { latitude: number; longitude: number }\n postalCode: string\n city: string\n state: string\n neighborhood: string\n street: string\n number: string\n complement: string\n reference: string\n}\n\nexport interface LogisticPickupPoint {\n name: string\n address: LogisticAddress\n id: string\n description: string | null\n instructions: string\n formatted_address: string | null\n isActive: boolean\n distance: number\n seller: string\n businessHours: Array<{\n closingTime: string\n openingTime: string\n dayOfWeek: number\n }>\n tagsLabel: any[]\n pickupHolidays: any[]\n}\n\ninterface Paging {\n page: number\n perPage: number\n total: number\n pages: number\n}\n\nexport interface LogisticOutput {\n items: LogisticPickupPoint[]\n paging: Paging\n}\n\nexport interface NearPickupPointsArgs {\n lat: string\n long: string\n maxDistance: number | undefined\n}\n\nexport interface PickupPointArgs {\n id: string\n}\n\n```" } ]
code_store-graphql_87896f95
[ { "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 store-graphql/node/resolvers/logistics/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { NearPickupPointsArgs, PickupPointArgs } from './types'\nimport fieldR from './fieldResolvers'\n\nexport const fieldResolvers = fieldR\n\nexport const queries = {\n logistics: (_: any, __: any, { clients: { logistics } }: Context) =>\n logistics.shipping(),\n\n nearPickupPoints: (\n _: any,\n { lat, long, maxDistance }: NearPickupPointsArgs,\n { clients: { logistics } }: Context\n ) => logistics.nearPickupPoints(lat, long, maxDistance),\n\n pickupPoint: (\n _: any,\n { id }: PickupPointArgs,\n { clients: { logistics } }: Context\n ) => logistics.pickupById(id),\n}\n\n```" } ]
code_store-graphql_22f8e34a
[ { "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 store-graphql/node/resolvers/session/sessionPickup.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { path } from 'ramda'\n\nexport const fieldResolvers = {\n SessionPickup: {\n cacheId: path(['address', 'addressId']),\n },\n}\n\n```" } ]
code_store-graphql_422b6211
[ { "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 store-graphql/node/resolvers/session/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { serialize } from 'cookie'\nimport { identity } from 'ramda'\n\nimport { fieldResolvers as sessionPickupResolvers } from './sessionPickup'\nimport { vtexIdCookies } from '../../utils/vtexId'\nimport { setCheckoutCookies, syncWithStoreLocale } from '../checkout'\nimport { VTEX_SESSION, getSession } from './service'\n\nconst IMPERSONATED_EMAIL = 'vtex-impersonated-customer-email'\n// maxAge of 1-day defined in vtex-impersonated-customer-email cookie\nconst VTEXID_EXPIRES = 86400\n\ninterface SavePickupArgs {\n name: string\n address: CheckoutAddress\n}\n\nconst convertCheckoutAddressToProfile = (\n checkoutAddress: CheckoutAddress | null\n) => {\n if (!checkoutAddress) {\n return checkoutAddress\n }\n\n const { geoCoordinates, ...rest } = checkoutAddress\n\n return { ...rest, geoCoordinate: geoCoordinates }\n}\n\n// Disclaimer: These queries and mutations assume that vtex_session was passed in cookies.\nexport const queries = {\n /**\n * Get user session\n * @return Session\n */\n getSession: async (_: any, __: any, ctx: Context) => {\n return getSession(ctx)\n },\n}\n\ninterface ImpersonateArg {\n email: string\n}\n\nexport const mutations = {\n impersonate: async (_: any, { email }: ImpersonateArg, ctx: Context) => {\n const {\n clients: { customSession, checkout },\n cookies,\n } = ctx\n\n await customSession.updateSession(\n IMPERSONATED_EMAIL,\n email,\n [],\n cookies.get(VTEX_SESSION)!,\n vtexIdCookies(ctx)\n )\n\n const orderForm = await checkout.orderForm()\n const clientProfileData = orderForm?.clientProfileData\n ? orderForm.clientProfileData\n : {}\n\n if (clientProfileData.email !== email && orderForm.orderFormId) {\n await checkout.updateOrderFormProfile(\n orderForm.orderFormId,\n {\n ...clientProfileData,\n email,\n },\n ctx\n )\n }\n\n ctx.response.set(\n 'Set-Cookie',\n serialize(IMPERSONATED_EMAIL, email, {\n encode: identity,\n maxAge: VTEXID_EXPIRES,\n path: '/',\n })\n )\n\n return queries.getSession({}, {}, ctx)\n },\n\n depersonify: async (_: any, __: any, ctx: Context) => {\n const {\n clients: { customSession, checkout },\n cookies,\n vtex: { segment },\n } = ctx\n\n await customSession.updateSession(\n IMPERSONATED_EMAIL,\n '',\n [],\n cookies.get(VTEX_SESSION)!,\n vtexIdCookies(ctx)\n )\n\n const { data, headers } = await checkout.newOrderForm()\n\n await syncWithStoreLocale(data, segment!.cultureInfo, checkout)\n\n setCheckoutCookies(headers, ctx)\n\n ctx.cookies.set(IMPERSONATED_EMAIL, '', {\n maxAge: 0,\n path: '/',\n })\n\n return true\n },\n\n savePickupInSession: async (_: any, args: SavePickupArgs, ctx: Context) => {\n const { address, name } = args\n const {\n clients: { customSession },\n cookies,\n } = ctx\n\n await customSession.updateSession(\n 'favoritePickup',\n { address: convertCheckoutAddressToProfile(address), name },\n [],\n cookies.get(VTEX_SESSION)!,\n vtexIdCookies(ctx)\n )\n\n return queries.getSession({}, {}, ctx)\n },\n}\n\nexport const fieldResolvers = {\n ...sessionPickupResolvers,\n}\n\n```" } ]
code_store-graphql_0f3068b9
[ { "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 store-graphql/node/resolvers/session/sessionResolver.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { path, toLower } from 'ramda'\n\ninterface ProfileFields {\n document?: string\n email?: string\n firstName?: string\n id?: string\n isAuthenticatedAsCustomer?: boolean\n lastName?: string\n phone?: string\n priceTables: string[]\n}\n\nexport interface SessionFields {\n adminUserEmail?: string\n adminUserId?: string\n id?: string\n cacheId?: string\n impersonable?: boolean\n impersonate?: { profile: ProfileFields }\n orderFormId?: string\n address?: any\n profile?: ProfileFields\n utmParams?: UtmParams\n utmiParams?: UtmiParams\n favoritePickup?: { address: CheckoutAddress; name: string }\n public?: {\n [key: string]: {\n value: string\n }\n }\n}\n\ninterface UtmParams {\n source?: string\n medium?: string\n campaign?: string\n term?: string\n content?: string\n}\n\ninterface UtmiParams {\n campaign?: string\n page?: string\n part?: string\n}\n\nconst convertToBool = (str: any) => !!str && toLower(str) === 'true'\n\nconst priceTables = (profile: SessionProfile): string[] => {\n const priceTablesValue = profile?.priceTables?.value\n\n return priceTablesValue ? priceTablesValue.split(',') : []\n}\n\nconst profileFields = (\n profile: SessionProfile,\n user: SessionImpersonate | SessionAuthentication\n): ProfileFields => ({\n document: path(['document', 'value'], profile),\n email:\n path(['email', 'value'], profile) ??\n path(['storeUserEmail', 'value'], user),\n firstName: path(['firstName', 'value'], profile),\n id: path(['id', 'value'], profile),\n isAuthenticatedAsCustomer: convertToBool(\n path(['isAuthenticated', 'value'], profile)\n ),\n lastName: path(['lastName', 'value'], profile),\n phone: path(['phone', 'value'], profile),\n priceTables: priceTables(profile),\n})\n\nconst setProfileData = (\n profile: SessionProfile,\n user: SessionImpersonate | SessionAuthentication\n) =>\n path(['storeUserId', 'value'], user) && {\n profile: {\n ...profileFields(profile, user),\n },\n }\n\nconst setUtmParams = (publicFields: SessionPublic) => ({\n source: path(['utm_source', 'value'], publicFields),\n medium: path(['utm_medium', 'value'], publicFields),\n campaign: path(['utm_campaign', 'value'], publicFields),\n term: path(['utm_term', 'value'], publicFields),\n content: path(['utm_content', 'value'], publicFields),\n})\n\nconst setUtmiParams = (publicFields: SessionPublic) => ({\n campaign: path(['utmi_cp', 'value'], publicFields),\n page: path(['utmi_p', 'value'], publicFields),\n part: path(['utmi_pc', 'value'], publicFields),\n})\n\nexport const sessionFields = (\n session: Session\n): SessionFields | Record<string, unknown> => {\n const { namespaces } = session\n\n return namespaces\n ? {\n address: path(['public', 'address', 'value'], namespaces),\n adminUserEmail: path(\n ['authentication', 'adminUserEmail', 'value'],\n namespaces\n ),\n adminUserId: path(\n ['authentication', 'adminUserId', 'value'],\n namespaces\n ),\n id: session.id,\n cacheId: session.id,\n impersonable: convertToBool(\n path(['impersonate', 'canImpersonate', 'value'], namespaces)\n ),\n impersonate: {\n ...setProfileData(namespaces.profile, namespaces.impersonate),\n },\n public: namespaces.public,\n utmParams: setUtmParams(namespaces.public),\n utmiParams: setUtmiParams(namespaces.public),\n orderFormId: path(['public', 'orderFormId', 'value'], namespaces),\n favoritePickup: path(['public', 'favoritePickup', 'value'], namespaces),\n ...setProfileData(namespaces.profile, namespaces.authentication),\n }\n : ({} as any)\n}\n\n```" } ]
code_store-graphql_57a944b0
[ { "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 store-graphql/node/resolvers/session/service.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\n\nimport { sessionFields } from './sessionResolver'\n\nexport const VTEX_SESSION = 'vtex_session'\n\nexport async function getSession(context: Context) {\n const {\n clients: { customSession },\n cookies,\n } = context\n\n const sessionCookie = cookies.get(VTEX_SESSION)\n\n if (sessionCookie === undefined)\n throw new ResolverError(\n `Invalid request for session, the ${VTEX_SESSION} wasn't provided!`\n )\n\n const { sessionData } = await customSession.getSession(sessionCookie, ['*'])\n\n return sessionFields(sessionData)\n}\n\n```" } ]
code_store-graphql_c0f72b84
[ { "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 store-graphql/node/__tests__/checkout/index.test.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { mutations } from '../../resolvers/checkout'\n// eslint-disable-next-line jest/no-mocks-import\nimport orderForm from '../../__mocks__/orderForm'\n\nconst mockContext = {\n vtex: {\n orderFormId: orderForm.orderFormId,\n },\n clients: {\n checkout: {\n orderForm: jest.fn().mockImplementation(() => orderForm),\n updateOrderFormMarketingData: jest.fn(),\n addItem: jest.fn(),\n },\n },\n}\n\nbeforeEach(() => {\n jest.clearAllMocks()\n})\n\ntest('should call add item with correct param', async () => {\n const itemToAdd = {\n id: 100,\n quantity: 1,\n seller: '1',\n }\n\n await mutations.addItem(\n {},\n {\n orderFormId: orderForm.orderFormId,\n items: [itemToAdd],\n },\n mockContext as any\n )\n\n const checkoutClient = mockContext.clients.checkout\n\n expect(checkoutClient.addItem.mock.calls[0][0]).toBe(orderForm.orderFormId)\n expect(checkoutClient.addItem.mock.calls[0][1]).toMatchObject([itemToAdd])\n expect(checkoutClient.updateOrderFormMarketingData).toBeCalledTimes(0)\n})\n\ntest.each([\n null,\n {\n utmSource: 'SOURCE DIFFERENT',\n utmMedium: 'medium',\n utmCampaign: 'campaign',\n utmiCampaign: 'campaign',\n utmiPart: 'part',\n utmipage: 'page33',\n },\n])(\n 'should correctly update order form marketing data when necessary',\n async (currentMarketingData: any) => {\n const itemToAdd = {\n id: 100,\n quantity: 1,\n seller: '1',\n }\n\n const checkoutClient = mockContext.clients.checkout\n\n checkoutClient.orderForm.mockImplementationOnce(() => ({\n ...orderForm,\n marketingData: currentMarketingData,\n }))\n await mutations.addItem(\n {},\n {\n orderFormId: orderForm.orderFormId,\n items: [itemToAdd],\n utmParams: { source: 'source', medium: 'medium', campaign: 'campaign' },\n utmiParams: { part: 'part', page: 'page', campaign: 'campaign' },\n },\n mockContext as any\n )\n\n expect(checkoutClient.addItem.mock.calls[0][0]).toBe(orderForm.orderFormId)\n expect(checkoutClient.addItem.mock.calls[0][1]).toMatchObject([itemToAdd])\n expect(checkoutClient.updateOrderFormMarketingData).toBeCalledTimes(1)\n expect(checkoutClient.updateOrderFormMarketingData.mock.calls[0][0]).toBe(\n orderForm.orderFormId\n )\n expect(\n checkoutClient.updateOrderFormMarketingData.mock.calls[0][1]\n ).toMatchObject({\n utmSource: 'source',\n utmMedium: 'medium',\n utmCampaign: 'campaign',\n utmiCampaign: 'campaign',\n utmiPart: 'part',\n utmipage: 'page',\n })\n }\n)\n\ntest.each<any>([\n [\n {\n utmSource: 'source',\n utmMedium: 'medium',\n utmCampaign: 'campaign',\n utmiCampaign: 'campaign',\n utmiPart: 'part',\n utmipage: 'page',\n },\n { source: 'source', medium: 'medium', campaign: 'campaign' },\n { part: 'part', page: 'page', campaign: 'campaign' },\n ],\n [\n {\n utmSource: 'source',\n utmMedium: null,\n utmCampaign: null,\n utmiCampaign: null,\n utmiPart: null,\n utmipage: null,\n },\n { source: 'source' },\n {},\n ],\n])(\n 'should not update order form marketing if it is identical to the arg sent',\n async (currentMarketingData: any, utmParams: any, utmiParams: any) => {\n const itemToAdd = {\n id: 100,\n quantity: 1,\n seller: '1',\n }\n\n const checkoutClient = mockContext.clients.checkout\n\n checkoutClient.orderForm.mockImplementationOnce(() => ({\n ...orderForm,\n marketingData: currentMarketingData,\n }))\n\n await mutations.addItem(\n {},\n {\n orderFormId: orderForm.orderFormId,\n items: [itemToAdd],\n utmParams,\n utmiParams,\n },\n mockContext as any\n )\n\n expect(checkoutClient.addItem.mock.calls[0][0]).toBe(orderForm.orderFormId)\n expect(checkoutClient.addItem.mock.calls[0][1]).toMatchObject([itemToAdd])\n expect(checkoutClient.updateOrderFormMarketingData).toBeCalledTimes(0)\n }\n)\n\ntest.each<any>([\n [undefined, undefined],\n [{}, {}],\n])(\n 'empty utmParams and utmiParams do not call updateOrderFormMarketingData',\n async (utmParams, utmiParams) => {\n const itemToAdd = {\n id: 100,\n quantity: 1,\n seller: '1',\n }\n\n const checkoutClient = mockContext.clients.checkout\n\n checkoutClient.orderForm.mockImplementationOnce(() => ({\n ...orderForm,\n marketingData: { coupon: null, marketingTags: [] },\n }))\n\n await mutations.addItem(\n {},\n {\n orderFormId: orderForm.orderFormId,\n items: [itemToAdd],\n utmParams,\n utmiParams,\n },\n mockContext as any\n )\n\n expect(checkoutClient.addItem.mock.calls[0][0]).toBe(orderForm.orderFormId)\n expect(checkoutClient.addItem.mock.calls[0][1]).toMatchObject([itemToAdd])\n expect(checkoutClient.updateOrderFormMarketingData).toBeCalledTimes(0)\n }\n)\n\n```" } ]
code_store-graphql_3964074c
[ { "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 store-graphql/node/__tests__/price/calculatePrice.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { calculatePrice } from '../../utils/calculatePrice'\nimport prices from '../../__mocks__/calculatePrice'\n\ndescribe('calculatePrice', () => {\n prices.forEach((priceObj) => {\n const { calculatedSellingPrice, unitMultiplier, price } = priceObj\n\n calculatedSellingPrice.forEach((sellingPrice) => {\n unitMultiplier.forEach((multiplier) => {\n it(`should calculate the correct real price with sellingPrice ${sellingPrice} and unitMultiplier ${multiplier} and`, () => {\n const realPrice = calculatePrice(multiplier, sellingPrice, price)\n const formatRealPrice = Number((realPrice / 100).toFixed(3))\n const realSellingPrice = Math.floor(\n formatRealPrice * multiplier * 100\n )\n\n expect(realSellingPrice).toBe(sellingPrice)\n })\n })\n })\n })\n})\n\n```" } ]
code_product-availability-gallery_ed0b0cbb
[ { "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 product-availability-gallery/docs/README.md from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n## ⚠️ Maintenance ⚠️\n*Starting September 1st 2022, this application will no longer be maintained by VTEX. Code is released for free under the GNU/PL Agreement for you to use and modify at your convenience. The VTEX repository shall remain unchanged with the original version.*\n\n---\n\n# Product Availability Gallery\n\n## Description\n\nThe Product Availability component shows the available amount of products. It also implements the needed services to request availability using the inventory API and validating USERS using masterdata.\n**IMPORTANT** This block was built to work only in account: ```arvital``` , however it can be easily evolved to support other customers.\n\nIt is available to be used in product page, gallery , category and search.\n\n:loudspeaker: **Disclaimer:** Don't fork this project; use, contribute, or open issue with your feature request\n\n## Table of Contents\n\n- [Usage](#usage)\n - [Blocks API](#blocks-api)\n - [Configuration](#configuration)\n - [Styles API](#styles-api)\n - [CSS Namespaces](#css-namespaces)\n- [Troubleshooting](#troubleshooting)\n- [Tests](#tests)\n\n## Usage\n\nThis app uses our store builder with the blocks architecture. To know more about Store Builder [click here.](https://help.vtex.com/en/tutorial/understanding-storebuilder-and-stylesbuilder#structuring-and-configuring-our-store-with-object-object)\n\nTo use this app or override the default CSS you need import it in your dependencies on `manifest.json` file.\n\n```json\n \"dependencies\": {\n \"vtexarg.product-availability-gallery-gallery\": \"1.x\"\n }\n```\n\nThen, add `product-availability-gallery-gallery` block to your `blocks.json`\n\nNow, you can change the behavior of the `product-availability-gallery-gallery` block.\n\n\nSee an example of how to configure **showing availability**:\n\n```json\n\"product-availability-gallery-gallery\": {\n \"props\": {\n \"showAvailability\": true,\n \"showAvailabilityMessage\": \"Available items:\"\n }\n}\n```\n\n### Blocks API\n\nWhen implementing this app as a block, various inner blocks may be available. The following interface lists the available blocks within product-availability-gallery-gallery and describes if they are required or optional.\n\n```json\n{\n \"product-availability-gallery-gallery\": {\n \"component\": \"ProductAvailability\"\n }\n}\n```\n\nFor now this block does not have any required or optional blocks.\n\n#### Configuration\n\nThrough the Storefront, you can change the product-availability-gallery's behavior and interface. However, you also can make in your theme app, as Store theme does.\n\n| Prop name | Type | Description |\n| ------------------- | --------- | ------------------------------------------------------------------------------------------- |\n| `threshold` | `Number` | DefineMinimum quantity that makes low stock message appear (if message is set). Default: 0 |\n| `lowStockMessage` | `String` | String to be shown to user when stock is lower than threshold. Should have {quantity} inside the given string, to be replaced for the threshold property. Example: \\\"Only {quantity} left!\\\". Leave empty to not show. Default: \"\" |\n| `highStockMessage` | `String` | String to be shown when stock is higher or equal than threshold. If left empty, won\\'t show. Default: \"\" |\n| `showAvailability` | `Boolean` | Enables the possibility to show the available items instead of lowStockMessage or highStockMessage. Default: false |\n| `showAvailabilityMessage` | `String` | String to be shown when show available option is true. If left empty, won\\'t show. Default: \"\" |\n\n### Styles API\n\nThis app provides some CSS classes as an API for style customization.\n\nTo use this CSS API, you must add the `styles` builder and create an app styling CSS file.\n\n1. Add the `styles` builder to your `manifest.json`:\n\n```json\n \"builders\": {\n \"styles\": \"1.x\"\n }\n```\n\n2. Create a file called `vtex.product-availability-gallery.css` inside the `styles/css` folder. Add your custom styles:\n\n```css\n.container {\n margin-top: 10px;\n}\n```\n\n#### CSS Namespaces\n\nBelow, we describe the namespaces that are defined in the product-availability-gallery.\n\n| Token name | Component | Description |\n| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |\n| `container` | [index](https://github.com/vtex-apps/product-availability-gallery/blob/master/react/components/ProductAvailability.tsx) | The main container of `ProductAvailability` |\n| `lowStockText` | [index](https://github.com/vtex-apps/product-availability-gallery/blob/master/react/components/LowStock.tsx) | Normal text for the low stock message.\n| `lowStockHighlight` | [index](https://github.com/vtex-apps/product-availability-gallery/blob/master/react/components/LowStock.tsx) | Number of the low stock message that is supposed to be highlighted. |\n| `highStockText` | [index](https://github.com/vtex-apps/product-availability-gallery/blob/master/react/components/HighStock.tsx) | Text of the hight stock message. |\n| `showAvailableText` | [index](https://github.com/vtex-apps/product-availability-gallery/blob/master/react/components/ShowAvailable.tsx) | Text of the show available message. |\n\n## Troubleshooting\n\nYou can check if others are passing through similar issues [here](https://github.com/vtex-apps/product-availability-gallery-gallery/issues). Also feel free to [open issues](https://github.com/vtex-apps/product-availability-gallery/issues/new) or contribute with pull requests.\n\n### Travis CI\n\n[![Build Status](https://travis-ci.org/vtex-apps/product-availability-gallery.svg?branch=master)](https://travis-ci.org/vtex-apps/product-availability-gallery)\n[![Coverage Status](https://coveralls.io/repos/github/vtex-apps/product-availability-gallery/badge.svg?branch=master)](https://coveralls.io/github/vtex-apps/product-availability-gallery?branch=master)\n\n\n<!-- DOCS-IGNORE:start -->\n___\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n\n<table>\n <tr>\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-enable -->\n<!-- prettier-ignore-end -->\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_product-availability-gallery_d3fbae99
[ { "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 product-availability-gallery/node/service.json from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 5,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"workers\": 1,\n \"routes\": {\n \"status\": {\n \"path\": \"/_v/status/:code/:warehouse\",\n \"public\": true\n },\n \"user\": {\n \"path\": \"/_v/user/:userId\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_product-availability-gallery_26f95e75
[ { "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 product-availability-gallery/node/package.json from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"ramda\": \"^0.25.0\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.4\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"typescript\": \"3.9.7\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\"\n },\n \"version\": \"0.2.0\"\n}\n\n```" } ]
code_product-availability-gallery_7b5b3c7f
[ { "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 product-availability-gallery/node/index.ts from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ClientsConfig, ServiceContext, RecorderState } from '@vtex/api'\nimport { LRUCache, method, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { status } from './middlewares/status'\nimport { user } from './middlewares/user'\nimport { validate } from './middlewares/validate'\n\nconst TIMEOUT_MS = 5000\n\n// Create a LRU memory cache for the Status client.\n// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.\nconst memoryCache = new LRUCache<string, any>({ max: 5000 })\n\nmetrics.trackCache('status', memoryCache)\n\n// This is the configuration for clients available in `ctx.clients`.\nconst clients: ClientsConfig<Clients> = {\n // We pass our custom implementation of the clients bag, containing the Status client.\n implementation: Clients,\n options: {\n // All IO Clients will be initialized with these options, unless otherwise specified.\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n // This key will be merged with the default options and add this cache to our Status client.\n status: {\n memoryCache,\n },\n },\n}\n\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\n type Context = ServiceContext<Clients, State>\n\n // The shape of our State object found in `ctx.state`. This is used as state bag to communicate between middlewares.\n interface State extends RecorderState {\n code: number\n userId: string\n warehouse: string\n }\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service({\n clients,\n routes: {\n // `status` is the route ID from service.json. It maps to an array of middlewares (or a single handler).\n status: method({\n GET: [validate, status],\n }),\n user: method({\n GET: [validate, user],\n }),\n },\n})\n\n```" } ]
code_product-availability-gallery_5075a65b
[ { "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 product-availability-gallery/react/package.json from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"node-fetch\": \"^2.6.1\",\n \"react\": \"^17.0.1\",\n \"react-apollo\": \"^3.1.5\",\n \"react-dom\": \"^17.0.1\",\n \"react-intl\": \"^5.12.3\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.4\",\n \"@types/node-fetch\": \"^2.5.10\",\n \"@vtex/api\": \"6.42.1\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@1.0.0/public/@types/vtex.css-handles\",\n \"vtex.product-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.9.9/public/@types/vtex.product-context\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.128.4/public/@types/vtex.render-runtime\"\n },\n \"version\": \"0.1.0\"\n}\n\n```" } ]
code_product-availability-gallery_9dea1633
[ { "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 product-availability-gallery/react/ProductAvailability.tsx from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport ProductAvailabilityWrapper from './components/ProductAvailabilityWrapper'\n\nexport default ProductAvailabilityWrapper\n\n\n```" } ]
code_product-availability-gallery_e2275c17
[ { "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 product-availability-gallery/store/interfaces.json from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"product-availability-gallery\": {\n \"component\": \"ProductAvailability\"\n }\n}\n\n```" } ]
code_product-availability-gallery_57787712
[ { "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 product-availability-gallery/node/clients/status.ts from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext, IOResponse } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nexport default class Status extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super('https://portal.vtexcommercestable.com.br/api/logistics/pvt/inventory/skus/', context,\n {\n ...options,\n headers: {\n 'VtexIdclientAutCookie': `${context.adminUserAuthToken}`,\n },\n })\n }\n\n public async getStatus(status: number, warehouse: string): Promise<string> {\n return this.http.get( `${status.toString()}?an=${warehouse}`, {\n metric: 'status-get',\n })\n }\n\n public async getStatusWithHeaders(\n status: number,\n warehouse: string\n ): Promise<IOResponse<string>> {\n return this.http.getRaw(`${status.toString()}?an=${warehouse}`, {\n metric: 'status-get-raw',\n })\n }\n}\n\n```" } ]
code_product-availability-gallery_8f5818e6
[ { "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 product-availability-gallery/node/clients/additionalDataClient.ts from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nexport default class AdditionalDataClient extends ExternalClient {\n\n constructor(context: IOContext, options?: InstanceOptions) {\n super(`http://${context.account}.vtexcommercestable.com.br/api/dataentities/CL/`, context,\n {\n ...options,\n headers: {\n 'VtexIdclientAutCookie': context.authToken,\n },\n })\n\n // console.log(context.authToken)\n // console.log(context.adminUserAuthToken)\n\n }\n\n public async get(userId: string) {\n const resp = await this.http.get(`search?_where=userId=${userId}&_fields=_all`)\n // console.log(resp.data)\n return resp\n }\n}\n\n```" } ]
code_product-availability-gallery_f5640e04
[ { "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 product-availability-gallery/node/clients/index.ts from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport Status from './status'\nimport AdditionalDataClient from './additionalDataClient'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get status() {\n return this.getOrSet('status', Status)\n }\n public get additionalData() {\n return this.getOrSet('additionalDataClient', AdditionalDataClient)\n }\n}\n\n```" } ]
code_product-availability-gallery_587adc77
[ { "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 product-availability-gallery/node/middlewares/status.ts from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport async function status(ctx: Context, next: () => Promise<any>) {\n const {\n state: { code, warehouse },\n clients: { status: statusClient },\n } = ctx\n\n // console.info('Received code:', code)\n // console.info('Received ctx:', ctx.state)\n\n const statusResponse = await statusClient.getStatus(code, warehouse)\n\n // console.info('Status response:', statusResponse)\n\n // const {\n // headers,\n // data,\n // status: responseStatus,\n // } = await statusClient.getStatusWithHeaders(code,warehouse)\n\n // console.info('Status headers', headers)\n // console.info('Status data:', data)\n\n // ctx.status = responseStatus\n ctx.body = statusResponse\n // ctx.set('Cache-Control', headers['cache-control'])\n\n await next()\n}\n\n```" } ]
code_product-availability-gallery_14aaff55
[ { "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 product-availability-gallery/node/middlewares/validate.ts from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n// import { UserInputError } from '@vtex/api'\n\nexport async function validate(ctx: Context, next: () => Promise<any>) {\n const {\n vtex: {\n route: { params },\n },\n } = ctx\n\n // console.info('Received params:', params)\n\n const { code, userId, warehouse } = params\n\n // if (!code ) {\n // throw new UserInputError('Code is required') // Wrapper for a Bad Request (400) HTTP Error. Check others in https://github.com/vtex/node-vtex-api/blob/fd6139349de4e68825b1074f1959dd8d0c8f4d5b/src/errors/index.ts\n // }\n\n const codeNumber = parseInt(code as string, 10)\n\n ctx.state.code = codeNumber\n // @ts-ignore\n ctx.state.userId = userId\n // @ts-ignore\n ctx.state.warehouse = warehouse\n\n await next()\n}\n\n```" } ]
code_product-availability-gallery_09089799
[ { "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 product-availability-gallery/node/middlewares/user.ts from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport async function user(ctx: Context, next: () => Promise<any>) {\n const {\n state: { userId },\n clients: { additionalData: additionalDataClient },\n } = ctx\n\n // console.info('Received userId:', userId)\n\n const userResponse = await additionalDataClient.get(userId)\n\n // console.info('user response:', userResponse)\n\n // const {\n // headers,\n // data,\n // status: responseStatus,\n // } = await statusClient.getStatusWithHeaders(code)\n\n\n ctx.body = userResponse\n // ctx.set('Cache-Control', headers['cache-control'])\n\n await next()\n}\n\n```" } ]
code_product-availability-gallery_64146e2e
[ { "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 product-availability-gallery/react/typings/css.d.ts from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: Record<string, string>\n export default css\n}\n\n```" } ]
code_product-availability-gallery_34a7aad9
[ { "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 product-availability-gallery/react/queries/clientAgent.graphql from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery clientAgent($mail: String){\n documents(acronym:\"CL\", fields:\"approved\", where:$mail) @context(provider: \"vtex.store-graphql\"){\n id\n fields {\n key\n value\n }\n }\n}\n```" } ]
code_product-availability-gallery_97f3034a
[ { "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 product-availability-gallery/react/queries/getBrand.graphql from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery Brand($id: Int) {\n brand(id: $id) @context(provider: \"vtex.store-graphql\") {\n slug\n imageUrl\n }\n}\n```" } ]
code_product-availability-gallery_a74fd8b1
[ { "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 product-availability-gallery/react/components/ProductAvailabilityWrapper.tsx from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, {useEffect, useState} from 'react'\nimport {useProduct} from 'vtex.product-context'\nimport type {ProductTypes} from 'vtex.product-context'\nimport {useCssHandles} from 'vtex.css-handles'\nimport type {CssHandlesTypes} from 'vtex.css-handles'\nimport {defineMessages} from 'react-intl'\nimport {useFullSession} from 'vtex.session-client'\nimport ProductAvailability from './ProductAvailability'\nimport {CssHandlesProvider} from './CssHandlesContext'\n\nconst messages = defineMessages({\n title: {\n defaultMessage: 'Product Availability',\n id: 'admin/editor.product-availability.title',\n },\n description: {\n defaultMessage: 'Component that shows the remaining available quantity',\n id: 'admin/editor.product-availability.description',\n },\n thresholdTitle: {\n defaultMessage: 'Threshold quantity',\n id: 'admin/editor.product-availability.threshold.title',\n },\n thresholdDescription: {\n defaultMessage:\n 'Minimum quantity that makes low stock message appear (if message is set)',\n id: 'admin/editor.product-availability.threshold.description',\n },\n lowStockMessageTitle: {\n defaultMessage: 'Low stock message',\n id: 'admin/editor.product-availability.lowStockMessage.title',\n },\n lowStockMessageDescription: {\n defaultMessage:\n 'String to be shown to user when stock is lower than threshold. Should have {quantity} inside the given string, to be replaced for the threshold property. Example: \"Only {quantity} left!\". Leave empty to not show.',\n id: 'admin/editor.product-availability.lowStockMessage.description',\n },\n highStockMessageTitle: {\n defaultMessage: 'High stock message',\n id: 'admin/editor.product-availability.highStockMessage.title',\n },\n highStockMessageDescription: {\n defaultMessage:\n \"String to be shown when stock is higher or equal than threshold. If left empty, won't show\",\n id: 'admin/editor.product-availability.highStockMessage.description',\n },\n showAvailabilityMessageTitle: {\n defaultMessage: 'Show available Message',\n id: 'admin/editor.product-availability.showAvailabilityMessage.title',\n },\n showAvailabilityMessageDescription: {\n defaultMessage: 'String to be shown when show available option is true',\n id: 'admin/editor.product-availability.showAvailabilityMessage.description',\n },\n})\nconst CONTAINER_CSS_HANDLES = ['container'] as const\nconst LOW_STOCK_CSS_HANDLES = ['lowStockText', 'lowStockHighlight'] as const\nconst HIGH_STOCK_CSS_HANDLES = ['highStockText'] as const\nconst SHOW_AVAILABLE_CSS_HANDLES = ['showAvailableText'] as const\nexport const CSS_HANDLES = [\n ...CONTAINER_CSS_HANDLES,\n ...LOW_STOCK_CSS_HANDLES,\n ...HIGH_STOCK_CSS_HANDLES,\n ...SHOW_AVAILABLE_CSS_HANDLES,\n] as const\nexport function getFirstAvailableSeller(sellers?: ProductTypes.Seller[]) {\n if (!sellers || sellers.length === 0) {\n return\n }\n const availableSeller = sellers.find(\n seller => seller.commertialOffer.AvailableQuantity !== 0\n )\n return availableSeller\n}\ninterface Props {\n threshold: number\n lowStockMessage?: string\n highStockMessage?: string\n showAvailability?: boolean\n showAvailabilityMessage?: string\n classes?: CssHandlesTypes.CustomClasses<typeof CONTAINER_CSS_HANDLES &\n (\n | typeof LOW_STOCK_CSS_HANDLES\n | typeof HIGH_STOCK_CSS_HANDLES\n | typeof SHOW_AVAILABLE_CSS_HANDLES\n )>\n}\ninterface Balance {\n totalQuantity: number;\n reservedQuantity: number;\n}\nfunction ProductAvailabilityWrapper({\n threshold = 0,\n lowStockMessage,\n highStockMessage,\n showAvailability,\n showAvailabilityMessage,\n classes,\n }: Props) {\n const {handles, withModifiers} = useCssHandles(CSS_HANDLES, {classes})\n const productContextValue = useProduct()\n const session = useFullSession()\n const [userId, setUserId] = useState<string>('');\n const [warehouse, setWarehouse] = useState<string>('');\n const [isSeller, setIsSeller] = useState<boolean>(false);\n const [clientId, setClientId] = useState<string>('');\n const seller = getFirstAvailableSeller(\n productContextValue?.selectedItem?.sellers\n )\n const prodId = productContextValue?.selectedItem?.itemId;\n const [balance, setBalance] = useState<Balance>({totalQuantity: 0, reservedQuantity: 0})\n const getData = () => {\n fetch(`https://${window.location.hostname}/_v/status/${prodId}/${warehouse}`,\n {\n credentials: 'include'\n })\n .then(response => response.json())\n .then(json => {\n setBalance(json.balance[0])\n })\n }\n const getUser = () => {\n fetch(`https://${window.location.hostname}/_v/user/${userId}`,\n {\n credentials: 'include'\n })\n .then(response => response.json())\n // eslint-disable-next-line no-console\n .then(user => {\n if (user[0].agente === \"VE\" || user[0].agente === \"VC\" || user[0].agente === \"CO\") {\n fetch(`https://${window.location.hostname}/_v/user/${clientId}`,\n {\n credentials: 'include'\n })\n .then(response => {\n return response.json()\n })\n .then(client => {\n setWarehouse(client[0].sucursal)\n setIsSeller(true);\n })\n }\n })\n }\n useEffect(() => {\n if (typeof window !== \"undefined\") {\n setClientId(session?.data?.session?.namespaces?.profile?.id?.value)\n setUserId(session?.data?.session?.namespaces?.authentication?.storeUserId?.value)\n }\n }, [session])\n useEffect(() => {\n if(userId) {\n getUser()\n }\n }, [userId])\n useEffect(() => {\n if(userId) {\n getData()\n }\n }, [warehouse, productContextValue])\n if (!productContextValue) {\n return null\n }\n return (\n <div>\n <CssHandlesProvider handles={handles} withModifiers={withModifiers}>\n <ProductAvailability\n threshold={threshold}\n lowStockMessage={lowStockMessage}\n highStockMessage={highStockMessage}\n showAvailability={isSeller ? showAvailability : false}\n showAvailabilityMessage={showAvailabilityMessage}\n balance={balance}\n />\n </CssHandlesProvider>\n </div>\n )\n}\nProductAvailabilityWrapper.schema = {\n title: messages.title.id,\n description: messages.description.id,\n type: 'object',\n properties: {\n threshold: {\n title: messages.thresholdTitle.id,\n description: messages.thresholdDescription.id,\n type: 'number',\n default: 0,\n isLayout: true,\n },\n lowStockMessage: {\n title: messages.lowStockMessageTitle.id,\n description: messages.lowStockMessageDescription.id,\n type: 'string',\n },\n highStockMessage: {\n title: messages.highStockMessageTitle.id,\n description: messages.highStockMessageDescription.id,\n type: 'string',\n },\n showAvailabilityMessage: {\n title: messages.showAvailabilityMessageTitle.id,\n description: messages.showAvailabilityMessageDescription.id,\n type: 'string',\n },\n },\n}\nexport default ProductAvailabilityWrapper\n```" } ]
code_product-availability-gallery_9725b75c
[ { "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 product-availability-gallery/react/components/LowStock.tsx from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\n\nimport { useContextCssHandles } from './CssHandlesContext'\n\ninterface Props {\n text: string\n availableQuantity: number\n}\n\nfunction LowStock({ text, availableQuantity }: Props) {\n const { handles } = useContextCssHandles()\n const [before, after] = text.split('{quantity}')\n\n return (\n <Fragment>\n {before && (\n <span className={`${handles.lowStockText} c-muted-2 t-body`}>\n {before}\n </span>\n )}\n {availableQuantity && (\n <span className={`${handles.lowStockHighlight} c-muted-2 t-body b mh1`}>\n {availableQuantity}\n </span>\n )}\n {after && (\n <span className={`${handles.lowStockText} c-muted-2 t-body`}>\n {after}\n </span>\n )}\n </Fragment>\n )\n}\n\nexport default LowStock\n\n```" } ]
code_product-availability-gallery_a0f1aea7
[ { "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 product-availability-gallery/react/components/CssHandlesContext.tsx from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { createCssHandlesContext } from 'vtex.css-handles'\n\nimport { CSS_HANDLES } from './ProductAvailabilityWrapper'\n\nconst { CssHandlesProvider, useContextCssHandles } = createCssHandlesContext(\n CSS_HANDLES\n)\n\nexport { CssHandlesProvider, useContextCssHandles }\n\n```" } ]
code_product-availability-gallery_886264cd
[ { "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 product-availability-gallery/react/components/Container.tsx from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport type { PropsWithChildren } from 'react'\n\nimport { useContextCssHandles } from './CssHandlesContext'\n\nfunction Container({ children }: PropsWithChildren<unknown>) {\n const { handles } = useContextCssHandles()\n\n return <div className={`${handles.container} flex pv2`}>{children}</div>\n}\n\nexport default Container\n\n```" } ]
code_product-availability-gallery_0c730860
[ { "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 product-availability-gallery/react/components/ShowAvailable.tsx from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { useContextCssHandles } from './CssHandlesContext'\n\ninterface Props {\n showAvailabilityMessage?: string\n availableQuantity: number\n}\n\nfunction HighStock({ showAvailabilityMessage, availableQuantity }: Props) {\n const { handles } = useContextCssHandles()\n\n return (\n <span className={`${handles.showAvailableText} c-muted-2 t-body b mh1`}>\n {showAvailabilityMessage} {availableQuantity}\n </span>\n )\n}\n\nexport default HighStock\n\n```" } ]
code_product-availability-gallery_545f7bd1
[ { "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 product-availability-gallery/react/components/HighStock.tsx from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { useContextCssHandles } from './CssHandlesContext'\n\ninterface Props {\n text: string\n}\n\nfunction HighStock({ text }: Props) {\n const { handles } = useContextCssHandles()\n\n return (\n <span className={`${handles.highStockText} c-muted-2 t-body`}>{text}</span>\n )\n}\n\nexport default HighStock\n\n```" } ]
code_product-availability-gallery_e0b34756
[ { "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 product-availability-gallery/react/components/ProductAvailability.tsx from the product-availability-gallery VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { memo } from 'react'\n\nimport LowStock from './LowStock'\nimport HighStock from './HighStock'\nimport ShowAvailable from './ShowAvailable'\nimport Container from './Container'\n\ninterface Props {\n threshold: number\n lowStockMessage?: string\n highStockMessage?: string\n showAvailability?: boolean\n showAvailabilityMessage?: string\n balance?: any\n}\n\nfunction ProductAvailability({\n threshold,\n lowStockMessage,\n highStockMessage,\n showAvailability,\n showAvailabilityMessage,\n balance,\n}: Props) {\n const availableQuantity = balance.totalQuantity - balance.reservedQuantity ?? 0\n if (!availableQuantity || availableQuantity < 1) {\n return null\n }\n\n const isLowStock = availableQuantity < threshold\n\n if (!showAvailability) {\n if (isLowStock && lowStockMessage) {\n return (\n <Container>\n <LowStock\n text={lowStockMessage}\n availableQuantity={availableQuantity}\n />\n </Container>\n )\n }\n\n if (!isLowStock && highStockMessage) {\n return <HighStock text={highStockMessage} />\n }\n\n return null\n }\n\n return (\n <Container>\n <ShowAvailable\n showAvailabilityMessage={showAvailabilityMessage}\n availableQuantity={availableQuantity}\n />\n </Container>\n )\n}\n\nexport default memo(ProductAvailability)\n\n```" } ]
code_livestreaming-utils_2ce97924
[ { "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 livestreaming-utils/react/useLivestreaming.tsx from the livestreaming-utils VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useContext } from 'react'\n\nimport { LivestreamingContext } from './LivestreamingContextProvider'\n\nexport const useLivestreaming = () => {\n return useContext(LivestreamingContext)\n}\n\nexport default useLivestreaming\n\n```" } ]
code_livestreaming-utils_d5d35cb6
[ { "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 livestreaming-utils/react/package.json from the livestreaming-utils VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"version\": \"0.0.1\",\n \"private\": true,\n \"scripts\": {\n \"lint\": \"tsc --noEmit && eslint --quiet --fix --ext ts,tsx .\"\n },\n \"resolutions\": {\n \"@types/react\": \"17.0.48\",\n \"@types/react-dom\": \"17.0.17\"\n },\n \"dependencies\": {\n \"@nizza/player\": \"3.0.0-alpha.0\",\n \"@types/react\": \"17.0.48\",\n \"@types/react-dom\": \"17.0.17\",\n \"react\": \"^17.x\",\n \"react-dom\": \"^17.x\"\n },\n \"devDependencies\": {\n \"@types/node\": \"18.11.10\",\n \"@vtex/tsconfig\": \"^0.6.0\",\n \"typescript\": \"3.9.7\"\n }\n}\n\n```" } ]
code_livestreaming-utils_add53cf5
[ { "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 livestreaming-utils/react/LivestreamingContextProvider.tsx from the livestreaming-utils VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { AddToCartConfig } from '@nizza/player'\nimport type { FC } from 'react'\nimport React, { createContext, useMemo } from 'react'\n\nexport interface LivestreamingProps {\n addToCartConfig?: AddToCartConfig\n}\n\nexport const LivestreamingContext = createContext<LivestreamingProps>({\n addToCartConfig: {},\n})\n\nLivestreamingContext.displayName = 'LivestreamingContext'\n\nexport interface LivestreamingProviderProps {\n value: LivestreamingProps\n}\n\nconst LivestreamingProvider: FC<LivestreamingProviderProps> = ({\n value = {},\n children,\n}) => {\n const context = useMemo(() => value, [value])\n\n return (\n <LivestreamingContext.Provider value={context}>\n {children}\n </LivestreamingContext.Provider>\n )\n}\n\nLivestreamingProvider.displayName = 'LivestreamingConfigProvider'\n\nexport default LivestreamingProvider\n\n```" } ]
code_livestreaming-utils_781f199b
[ { "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 livestreaming-utils/store/interfaces.json from the livestreaming-utils VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"livestreaming-context\": {\n \"component\": \"LivestreamingContextProvider\",\n \"composition\": \"children\",\n \"allowed\": \"*\"\n }\n}\n\n```" } ]
code_zopim_bd35cb72
[ { "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 zopim/docs/README.md from the zopim VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Zopim\n\nVTEX Zopim first-party app\n\n## How to install\n\nOpen the VTEX App Store and install this app on your store.\n\nNow, open the app settings on your admin and fill in your Zopim's Account Key.\n\n```" } ]
code_b2b-approved-message_7ca0e4f6
[ { "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 b2b-approved-message/messages/pt.json from the b2b-approved-message VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/b2b-approved-message.message\": \"Sua organização não foi aprovada para fazer pedidos nesta loja no momento. Se já está assim há algum tempo e você acha que isso é um erro, entre em contato conosco.\"\n}\n\n```" } ]
code_b2b-approved-message_81302847
[ { "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 b2b-approved-message/messages/en.json from the b2b-approved-message VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/b2b-approved-message.message\": \"Your organization is not approved to place orders on this store right now. If it’s been like this for a while and you think this is a mistake, please contact us.\"\n}\n\n```" } ]
code_b2b-approved-message_6ff740d5
[ { "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 b2b-approved-message/messages/es.json from the b2b-approved-message VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/b2b-approved-message.message\": \"Su organización no está aprobada para realizar pedidos en esta tienda en este momento. Si ha sido así por un tiempo y cree que es un error, comuníquese con nosotros.\"\n}\n\n```" } ]
code_b2b-approved-message_e88aeaa9
[ { "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 b2b-approved-message/docs/README.md from the b2b-approved-message VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/{OrganizationName}/{AppName}) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# B2B Approved Message\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nApp responsible for display a message if user is not approved in supplier\n\n## Configuration \n\nIn this section, you first must **add the primary instructions** that will allow users to use the app's blocks in their store, such as:\n\n1. Adding the app as a theme dependency in the `manifest.json` file;\n2. Declaring the app's main block in a given theme template or inside another block from the theme.\n\n## Customization\n\nNo CSS Handles are available yet for the app customization.\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<!-- 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---- \n\nCheck out some documentation models that are already live: \n- [Breadcrumb](https://github.com/vtex-apps/breadcrumb)\n- [Image](https://vtex.io/docs/components/general/vtex.store-components/image)\n- [Condition Layout](https://vtex.io/docs/components/all/vtex.condition-layout@1.1.6/)\n- [Add To Cart Button](https://vtex.io/docs/components/content-blocks/vtex.add-to-cart-button@0.9.0/)\n- [Store Form](https://vtex.io/docs/components/all/vtex.store-form@0.3.4/)\n\n```" } ]
code_b2b-approved-message_26ec5af4
[ { "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 b2b-approved-message/react/ApprovedMessage.test.tsx from the b2b-approved-message VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport ApprovedMessage from './Greeting'\n\ntest('greets Fred', () => {\n const { queryByText } = render(<ApprovedMessage name=\"Fred\" />)\n\n expect(queryByText('Hey, Fred')).toBeInTheDocument()\n})\n\n```" } ]
code_b2b-approved-message_14ca1036
[ { "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 b2b-approved-message/react/ApprovedMessage.tsx from the b2b-approved-message VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Alert } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\n\nimport { isApproved, isLoggedIn, useSession } from './session'\n\nconst ApprovedMessage = () => {\n const [show, setShow] = React.useState(true)\n const session = useSession()\n\n if (!show) return null\n\n if (!isLoggedIn(session)) return null\n\n if (isApproved(session)) return null\n\n return (\n <div className=\"relative\">\n <div className=\"mw8 tc absolute center top-0 left-0 right-0 z-1\">\n <Alert type=\"warning\" onClose={() => setShow(false)}>\n <FormattedMessage id=\"store/b2b-approved-message.message\" />\n <span />\n </Alert>\n </div>\n </div>\n )\n}\n\nexport default ApprovedMessage\n\n```" } ]
code_b2b-approved-message_2d69f609
[ { "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 b2b-approved-message/react/session.ts from the b2b-approved-message VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n Session,\n SessionPromise,\n SessionResponse,\n} from 'vtex.render-runtime'\nimport React from 'react'\n\nconst NOT_APPROVED_TRADE_POLICY = '5'\n\ndeclare global {\n interface Window {\n __RENDER_8_SESSION__?: {\n sessionPromise?: Promise<SessionPromise>\n }\n }\n}\n\nexport function getSession() {\n return window?.__RENDER_8_SESSION__?.sessionPromise ?? null\n}\n\nexport const useSession = () => {\n const [session, setSession] = React.useState<SessionResponse>()\n\n React.useEffect(() => {\n ;(async () => {\n const sessionPromise = getSession()\n\n if (!sessionPromise) return\n\n const { response } = await sessionPromise\n\n setSession(response)\n })()\n }, [])\n\n return session\n}\n\nexport const isLoggedIn = (session: SessionResponse | undefined): boolean =>\n !!(session as Session)?.namespaces?.profile?.email\n\nexport const isApproved = (session: SessionResponse | undefined): boolean => {\n const tradePolicy = (session as Session)?.namespaces?.store?.channel?.value\n \n if (!tradePolicy) return false\n\n return tradePolicy !== NOT_APPROVED_TRADE_POLICY\n}\n\n```" } ]
code_b2b-approved-message_b6421919
[ { "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 b2b-approved-message/react/package.json from the b2b-approved-message VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"CHANGE_ME\",\n \"version\": \"0.1.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 },\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.b2b-approved-message\": \"https://gsasouza--b2bstore.myvtex.com/_v/private/typings/linked/v1/vtex.b2b-approved-message@0.0.0+build1626376459/public/@types/vtex.b2b-approved-message\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.130.0/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.0/public/@types/vtex.styleguide\"\n }\n}\n\n```" } ]
code_b2b-approved-message_eef1a1d3
[ { "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 b2b-approved-message/store/interfaces.json from the b2b-approved-message VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"b2b-approved-message\": {\n \"component\": \"ApprovedMessage\"\n }\n}\n\n```" } ]
code_b2b-approved-message_32c7d12b
[ { "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 b2b-approved-message/react/typings/vtex.render-runtime.d.ts from the b2b-approved-message VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import type { ComponentType, ReactElement, ReactType } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: unknown\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n interface ExtensionPointProps {\n id: string\n\n [key: string]: any\n }\n\n interface ChildBlock<BlockProps> {\n props: BlockProps\n }\n\n export const ExtensionPoint: ComponentType<ExtensionPointProps>\n export const useChildBlock: <BlockProps>({\n id,\n }: {\n id: string\n }) => ChildBlock<BlockProps> | null\n export const Helmet: ReactElement\n export const Link: ReactType\n export const NoSSR: ReactElement\n export const RenderContextConsumer: unknown\n export const TreePathContextConsumer: unknown\n export const useTreePath: unknown\n export const useRuntime: unknown\n export const canUseDOM: boolean\n export const withRuntimeContext: <\n TOriginalProps extends Record<string, unknown>\n >(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n export const withSession: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n interface KeyValue {\n value: string\n }\n\n interface Session {\n id: string\n namespaces: {\n store: {\n channel: KeyValue\n }\n profile: {\n isAuthenticated: KeyValue\n email: string\n }\n }\n }\n\n interface SessionUnauthorized {\n type: 'Unauthorized'\n message: string\n }\n\n interface SessionForbidden {\n type: 'Forbidden'\n message: string\n }\n\n type SessionResponse = Session | SessionUnauthorized | SessionForbidden\n\n export interface RenderSession {\n sessionPromise: Promise<SessionPromise>\n }\n\n export interface SessionPromise {\n response: Session | SessionUnauthorized | SessionForbidden\n }\n}\n\n```" } ]
code_b2b-approved-message_7c7cd52c
[ { "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 b2b-approved-message/react/typings/gql.d.ts from the b2b-approved-message 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_b2b-approved-message_aa32afdf
[ { "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 b2b-approved-message/react/typings/css.d.ts from the b2b-approved-message 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_shipment-tracker_012aaf2e
[ { "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 shipment-tracker/messages/pt.json from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/tracking.title\": \"\",\n \"admin/tracking.last-schedule.label\": \"\",\n \"admin/tracking.next-schedule.label\": \"\",\n \"admin/tracking.settings.tab.label\": \"\",\n \"admin/tracking.schedule.label\": \"\",\n \"admin/tracking.active.label\": \"\",\n \"admin/tracking.inactive.label\": \"\",\n \"admin/carrier.title\": \"\",\n \"admin/carrier.save.label\": \"\",\n \"admin/carrier.canadapost.label\": \"\",\n \"admin/carrier.canadapost.id.label\": \"\",\n \"admin/carrier.canadapost.password.label\": \"\",\n \"admin/carrier.fedex.label\": \"\",\n \"admin/carrier.fedex.key.label\": \"\",\n \"admin/carrier.fedex.account-number.label\": \"\",\n \"admin/carrier.fedex.meter-number.label\": \"\",\n \"admin/carrier.fedex.password.label\": \"\",\n \"admin/carrier.ups.label\": \"\",\n \"admin/carrier.ups.key.label\": \"\",\n \"admin/carrier.usps.label\": \"\",\n \"admin/carrier.usps.userID.label\": \"\"\n}\n\n```" } ]
code_shipment-tracker_ae4d8a86
[ { "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 shipment-tracker/messages/en.json from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/tracking.title\": \"Shipment Tracker\",\n \"admin/tracking.last-schedule.label\": \"Last Schedule Run:\",\n \"admin/tracking.next-schedule.label\": \"Next Schedule Run:\",\n \"admin/tracking.settings.tab.label\": \"Settings\",\n \"admin/tracking.schedule.label\": \"Update Schedule\",\n \"admin/tracking.active.label\": \"Active\",\n \"admin/tracking.inactive.label\": \"Inactive\",\n \"admin/carrier.title\": \"Carrier\",\n \"admin/carrier.save.label\": \"Save\",\n \"admin/carrier.canadapost.label\": \"Canada Post\",\n \"admin/carrier.canadapost.id.label\": \"User Id\",\n \"admin/carrier.canadapost.password.label\": \"Account Password\",\n \"admin/carrier.fedex.label\": \"Fedex\",\n \"admin/carrier.fedex.key.label\": \"Key\",\n \"admin/carrier.fedex.account-number.label\": \"Account Number\",\n \"admin/carrier.fedex.meter-number.label\": \"Meter Number\",\n \"admin/carrier.fedex.password.label\": \"Password\",\n \"admin/carrier.ups.label\": \"UPS\",\n \"admin/carrier.ups.key.label\": \"Key\",\n \"admin/carrier.usps.label\": \"USPS\",\n \"admin/carrier.usps.userID.label\": \"User ID\"\n}\n\n```" } ]
code_shipment-tracker_fa66f76f
[ { "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 shipment-tracker/messages/context.json from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/tracking.title\": \"admin/tracking.title\",\n \"admin/tracking.last-schedule.label\": \"admin/tracking.last-schedule.label\",\n \"admin/tracking.next-schedule.label\": \"admin/tracking.next-schedule.label\",\n \"admin/tracking.settings.tab.label\": \"admin/tracking.settings.tab.label\",\n \"admin/tracking.schedule.label\": \"admin/tracking.schedule.label\",\n \"admin/tracking.active.label\": \"admin/tracking.active.label\",\n \"admin/tracking.inactive.label\": \"admin/tracking.inactive.label\",\n \"admin/carrier.title\": \"admin/carrier.title\",\n \"admin/carrier.save.label\": \"admin/carrier.save.label\",\n \"admin/carrier.canadapost.label\": \"admin/carrier.canadapost.label\",\n \"admin/carrier.canadapost.id.label\": \"admin/carrier.canadapost.id.label\",\n \"admin/carrier.canadapost.password.label\": \"admin/carrier.canadapost.password.label\",\n \"admin/carrier.fedex.label\": \"admin/carrier.fedex.label\",\n \"admin/carrier.fedex.key.label\": \"admin/carrier.fedex.key.label\",\n \"admin/carrier.fedex.account-number.label\": \"admin/carrier.fedex.account-number.label\",\n \"admin/carrier.fedex.meter-number.label\": \"admin/carrier.fedex.meter-number.label\",\n \"admin/carrier.fedex.password.label\": \"admin/carrier.fedex.password.label\",\n \"admin/carrier.ups.label\": \"admin/carrier.ups.label\",\n \"admin/carrier.ups.key.label\": \"admin/carrier.ups.key.label\",\n \"admin/carrier.usps.label\": \"admin/carrier.usps.label\",\n \"admin/carrier.usps.userID.label\": \"admin/carrier.usps.userID.label\"\n}\n\n```" } ]
code_shipment-tracker_6f762f7f
[ { "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 shipment-tracker/messages/es.json from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/tracking.title\": \"\",\n \"admin/tracking.last-schedule.label\": \"\",\n \"admin/tracking.next-schedule.label\": \"\",\n \"admin/tracking.settings.tab.label\": \"\",\n \"admin/tracking.schedule.label\": \"\",\n \"admin/tracking.active.label\": \"\",\n \"admin/tracking.inactive.label\": \"\",\n \"admin/carrier.title\": \"\",\n \"admin/carrier.save.label\": \"\",\n \"admin/carrier.canadapost.label\": \"\",\n \"admin/carrier.canadapost.id.label\": \"\",\n \"admin/carrier.canadapost.password.label\": \"\",\n \"admin/carrier.fedex.label\": \"\",\n \"admin/carrier.fedex.key.label\": \"\",\n \"admin/carrier.fedex.account-number.label\": \"\",\n \"admin/carrier.fedex.meter-number.label\": \"\",\n \"admin/carrier.fedex.password.label\": \"\",\n \"admin/carrier.ups.label\": \"\",\n \"admin/carrier.ups.key.label\": \"\",\n \"admin/carrier.usps.label\": \"\",\n \"admin/carrier.usps.userID.label\": \"\"\n}\n\n```" } ]
code_shipment-tracker_265e403d
[ { "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 shipment-tracker/admin/navigation.json from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"section\": \"orders\",\n \"titleId\": \"admin-example.navigation.label-group\",\n \"path\": \"/admin/shipping-tracker\"\n}\n\n```" } ]
code_shipment-tracker_707f4f8c
[ { "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 shipment-tracker/admin/routes.json from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin.app.shipping-tracker\": {\n \"component\": \"Admin\",\n \"path\": \"/admin/app/shipping-tracker\"\n }\n}\n\n```" } ]
code_shipment-tracker_d781c483
[ { "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 shipment-tracker/docs/README.md from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/shipment-tracker) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\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\n# Shipment Tracker\n\nShipment Tracker is a VTEX IO native solution that allows stores to provide built in shipment tracking for their customers. The carriers supported currently are USPS, UPS, Fedex, and Canada Post. Updates can be seen in the orders page, along with email updates being sent out to the customer.\n\n## Configuration\n### Step 1 Installing the Shipment Tracker app\n\nUsing your terminal, log in to the desired VTEX account and run the following command:\n\n`vtex install vtex.shipment-tracker@0.x`\n\n### Step 2 - Adding in Carriers \n\n1. In the admin page, scroll down to the carriers section. Currently, the app is configured to provide tracking information for USPS, UPS, FedEx, and Canada Post\n2. For the carrier(s) you would like to use, fill in the required fields such as user ID, password, etc. This can be found on the carrier websites, after creating an account and requesting developer access.\n\n## Modus Operandi\n\nThe app may be configured to use a **scheduler** where an administrator is responsible for activating regular database updates.\n\nTo activate the scheduler, simply toggle the switch in the admin panel.\n\n## Customization\n\nIn order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).\n\n```" } ]
code_shipment-tracker_576b9b21
[ { "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 shipment-tracker/graphql/schema.graphql from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Query {\n config: Config @cacheControl(scope: PRIVATE)\n allShipments: [Shipment] @cacheControl(scope: PRIVATE, maxAge: Short)\n shipmentsByCarrier(carrier: String): [Shipment]\n @cacheControl(scope: PRIVATE, maxAge: Short)\n interactions(shipmentId: String): [Interaction]\n @cacheControl(scope: PRIVATE, maxAge: Medium)\n shipment(id: String): Shipment @cacheControl(scope: PRIVATE, maxAge: Medium)\n viewSchedule: ViewSchedule @cacheControl(scope: PRIVATE)\n}\n\ntype Mutation {\n addShipment(\n trackingNumber: String\n carrier: String\n delivered: Boolean\n orderId: String\n invoiceId: String\n externalLink: String\n ): String\n updateShipment(\n id: String\n trackingNumber: String\n carrier: String\n delivered: Boolean\n orderId: String\n invoiceId: String\n externalLink: String\n lastInteractionDate: String\n ): String\n addInteraction(\n shipmentId: String\n interaction: String\n delivered: Boolean\n ): String\n createSchedule: Schedule\n deleteSchedule: Boolean\n}\n\ntype Config {\n schema: Boolean\n title: String\n}\n\ntype Shipment {\n id: String\n trackingNumber: String\n carrier: String\n delivered: Boolean\n orderId: String\n invoiceId: String\n externalLink: String\n createdIn: String\n lastInteractionDate: String\n}\n\ntype Interaction {\n id: String\n shipmentId: String\n interaction: String\n delivered: Boolean\n createdIn: String\n updatedIn: String\n}\n\ntype Schedule {\n nextExecution: String\n}\n\ntype ViewSchedule {\n lastInteractionIn: String\n nextExecution: String\n}\n\n```" } ]
code_shipment-tracker_61db4d03
[ { "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 shipment-tracker/node/service.json from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 1536,\n \"ttl\": 30,\n \"timeout\": 12,\n \"minReplicas\": 15,\n \"maxReplicas\": 100,\n \"workers\": 1,\n \"routes\": {\n \"updateTracking\": {\n \"path\": \"/_v/api/tracking/update\",\n \"public\": true\n }\n },\n \"events\": {\n \"orderStatusChange\": {\n \"sender\": \"vtex.orders-broadcast\",\n \"topics\": [\"invoiced\"]\n }\n }\n}\n\n```" } ]
code_shipment-tracker_b80be65c
[ { "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 shipment-tracker/node/featureFlags.ts from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const flags = {\n VTEX_ASSETS_URL: false,\n}\n\n```" } ]
code_shipment-tracker_4c21ace1
[ { "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 shipment-tracker/node/package.json from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.search-graphql\",\n \"scripts\": {\n \"lint\": \"tsc --noEmit && eslint --ext ts .\",\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"@gocommerce/utils\": \"^0.6.11\",\n \"atob\": \"^2.1.2\",\n \"axios\": \"^0.19.0\",\n \"camelcase\": \"^5.0.0\",\n \"cookie\": \"^0.3.1\",\n \"graphql\": \"^14.5.8\",\n \"graphql-tools\": \"^4.0.6\",\n \"qs\": \"^6.6.0\",\n \"querystring\": \"^0.2.0\",\n \"ramda\": \"^0.26.1\",\n \"slugify\": \"^1.2.6\",\n \"typescript\": \"3.9.7\",\n \"xml2js\": \"^0.4.23\"\n },\n \"devDependencies\": {\n \"@types/atob\": \"^2.1.2\",\n \"@types/camelcase\": \"^4.1.0\",\n \"@types/cookie\": \"^0.3.2\",\n \"@types/es6-shim\": \"^0.31.32\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/koa\": \"^2.0.46\",\n \"@types/node\": \"^12.0.0\",\n \"@types/qs\": \"^6.5.1\",\n \"@types/ramda\": \"^0.26.21\",\n \"@types/xml2js\": \"^0.4.8\",\n \"@vtex/api\": \"6.39.1\",\n \"@vtex/test-tools\": \"^1.2.0\",\n \"@vtex/tsconfig\": \"^0.2.0\",\n \"eslint\": \"^6.8.0\",\n \"eslint-config-vtex\": \"^12.1.1\",\n \"prettier\": \"^1.16.4\",\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.product-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.9.7/public/@types/vtex.product-context\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@7.42.0/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.134.1/public/@types/vtex.styleguide\"\n },\n \"version\": \"3.1.2\"\n}\n\n```" } ]
code_shipment-tracker_6e329279
[ { "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 shipment-tracker/node/constants.ts from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const CARRIERS = {\n UPS: 'UPS',\n USPS: 'USPS',\n FEDEX: 'FEDEX',\n CANADAPOST: 'CANADAPOST',\n} as const\n\nexport type Carrier = typeof CARRIERS[keyof typeof CARRIERS]\n\n```" } ]
code_shipment-tracker_ccb5d00c
[ { "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 shipment-tracker/node/index.ts from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n Service,\n ClientsConfig,\n ParamsContext,\n RecorderState,\n ServiceContext,\n EventContext,\n} from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { resolvers } from './resolvers'\nimport { orderStatusChange } from './events/orderStatusChange'\nimport { updateTracking } from './routes/updateTracking'\n\nconst TIMEOUT_MS = 800\n\nconst clients: ClientsConfig<Clients> = {\n implementation: Clients,\n options: {\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n },\n}\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\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 }\n }\n type State = RecorderState\n}\n\nexport default new Service<Clients, RecorderState, ParamsContext>({\n clients,\n graphql: {\n resolvers,\n },\n events: {\n orderStatusChange,\n },\n routes: {\n updateTracking,\n },\n})\n\n```" } ]
code_shipment-tracker_ed699cc3
[ { "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 shipment-tracker/react/package.json from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.admin-example\",\n \"version\": \"0.0.1\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^11.12.1\",\n \"@types/react\": \"^16.8.10\",\n \"@types/react-intl\": \"^2.3.17\",\n \"apollo-client\": \"^2.4.7\",\n \"graphql\": \"^14.0.2\",\n \"prop-types\": \"^15.7.2\",\n \"react\": \"^16.8.6\",\n \"react-dom\": \"^16.8.6\",\n \"react-intl\": \"^2.7.2\",\n \"typescript\": \"3.9.7\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.126.11/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.135.1/public/@types/vtex.styleguide\"\n },\n \"dependencies\": {\n \"react-apollo\": \"^3.1.5\"\n }\n}\n\n```" } ]
code_shipment-tracker_a580180c
[ { "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 shipment-tracker/react/styles.global.css from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\nhtml,\nbody,\n#render-container,\n#render-provider,\n.render-container,\n.render-provider {\n height: 100%;\n}\n\n```" } ]
code_shipment-tracker_631e8c7e
[ { "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 shipment-tracker/react/Admin.tsx from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useEffect, useState } from 'react'\nimport { useMutation, useQuery } from 'react-apollo'\nimport { injectIntl, defineMessages } from 'react-intl'\nimport {\n Layout,\n PageBlock,\n PageHeader,\n Toggle,\n Tabs,\n Tab,\n} from 'vtex.styleguide'\n\nimport ViewSchedule from './queries/viewSchedule.gql'\nimport DeleteSchedule from './queries/deleteSchedule.gql'\nimport CreateSchedule from './queries/createSchedule.gql'\nimport Carriers from './components/Carriers'\n\nimport './styles.global.css'\n\nconst AdminExample: FC<any> = ({ intl }) => {\n const messages = defineMessages({\n title: {\n id: 'admin/tracking.title',\n defaultMessage: 'Shipment Tracker',\n },\n settingsTab: {\n id: 'admin/tracking.settings.tab.label',\n defaultMessage: 'Settings',\n },\n scheduleLabel: {\n id: 'admin/tracking.schedule.label',\n defaultMessage: 'Update Schedule',\n },\n lastSchedule: {\n id: 'admin/tracking.last-schedule.label',\n defaultMessage: 'Last Schedule Run:',\n },\n nextSchedule: {\n id: 'admin/tracking.next-schedule.label',\n defaultMessage: 'Next Schedule Run:',\n },\n active: {\n id: 'admin/tracking.active.label',\n defaultMessage: 'Active',\n },\n inactive: {\n id: 'admin/tracking.inactive.label',\n defaultMessage: 'Inactive',\n },\n })\n const [activeTab, setActiveTab] = useState<number>(1)\n const [schedule, setSchedule] = useState<null | Schedule>(null)\n const [\n deleteSchedule,\n { loading: deleteLoading, data: deleteResponse },\n ] = useMutation(DeleteSchedule)\n const [\n createSchedule,\n { loading: createLoading, data: createResponse },\n ] = useMutation<ScheduleCreateResponse>(CreateSchedule)\n const {\n data: scheduleData,\n loading: viewLoading,\n called: viewCalled,\n } = useQuery<ScheduleViewResponse>(ViewSchedule)\n\n useEffect(() => {\n if (scheduleData?.viewSchedule) {\n setSchedule(scheduleData.viewSchedule)\n } else {\n setSchedule(null)\n }\n }, [scheduleData])\n\n useEffect(() => {\n if (deleteResponse) {\n setSchedule(null)\n }\n }, [deleteResponse])\n\n useEffect(() => {\n if (createResponse?.createSchedule) {\n setSchedule(createResponse.createSchedule)\n }\n }, [createResponse])\n\n const handleChange = () => {\n if (schedule) {\n return deleteSchedule()\n }\n\n return createSchedule()\n }\n\n if (!viewCalled || viewLoading) {\n return null\n }\n\n return (\n <Layout\n pageHeader={<PageHeader title={intl.formatMessage(messages.title)} />}\n >\n <Tabs fullWidth>\n <Tab\n label={intl.formatMessage(messages.settingsTab)}\n active={activeTab === 1}\n onClick={() => setActiveTab(1)}\n >\n <div className=\"mt5\" />\n <PageBlock\n title={intl.formatMessage(messages.scheduleLabel)}\n variation=\"full\"\n >\n <div className=\"flex justify-between\">\n <div>\n <div className=\"flex\">\n <div className=\"mr4\">\n {intl.formatMessage(messages.lastSchedule)}\n </div>\n {`${\n schedule?.lastInteractionIn\n ? schedule.lastInteractionIn\n : '-'\n }`}\n </div>\n <div className=\"flex mt3\">\n <div className=\"mr4\">\n {intl.formatMessage(messages.nextSchedule)}\n </div>\n {`${schedule ? schedule.nextExecution : '-'}`}\n </div>\n </div>\n <div className=\"flex items-center\">\n <div className={'w4'}>\n <Toggle\n label={\n schedule\n ? intl.formatMessage(messages.active)\n : intl.formatMessage(messages.inactive)\n }\n semantic\n size=\"large\"\n checked={schedule?.nextExecution}\n onChange={() => handleChange()}\n />\n </div>\n </div>\n </div>\n </PageBlock>\n <Carriers />\n </Tab>\n </Tabs>\n </Layout>\n )\n}\n\nexport default injectIntl(AdminExample)\n\n```" } ]
code_shipment-tracker_5adf45bd
[ { "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 shipment-tracker/store/interfaces.json from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"shipping-tracker\": {\n \"component\": \"Admin\"\n }\n}\n\n```" } ]
code_shipment-tracker_7fc76906
[ { "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 shipment-tracker/node/clients/canadaPost.ts from the shipment-tracker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\n\nexport default class CanadaPostClient extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n // production - soa-gw.canadapost.ca\n super('http://soa-gw.canadapost.ca', context, {\n ...options,\n headers: {\n 'X-Vtex-Use-Https': 'true',\n 'Proxy-Authorization': context.authToken,\n },\n })\n }\n\n public async getTracking(\n trackingNumber: string,\n key: string\n // vtexAppKey: string,\n // vtexAppToken: string\n ): Promise<string> {\n return this.http.get(`/vis/track/pin/${trackingNumber}/detail`, {\n headers: {\n // 'X-VTEX-API-AppKey': vtexAppKey,\n // 'X-VTEX-API-AppToken': vtexAppToken,\n 'Authorization': `Basic ${key}`,\n 'Accept-language': 'en-CA',\n 'Accept': 'application/vnd.cpc.track-v2+xml'\n },\n })\n }\n}\n\n```" } ]