id
stringlengths
12
53
messages
listlengths
3
3
code_minicart-freeshipping-bar_f2b58123
[ { "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 minicart-freeshipping-bar/react/typings/css.d.ts from the minicart-freeshipping-bar 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_minicart-freeshipping-bar_11e2cbee
[ { "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 minicart-freeshipping-bar/react/typings/graphql.d.ts from the minicart-freeshipping-bar VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_minicart-freeshipping-bar_c94f5837
[ { "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 minicart-freeshipping-bar/react/components/minicartbarSettings.graphql from the minicart-freeshipping-bar VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery AppSettings {\n publicSettingsForApp(app: \"vtexeurope.minicart-freeshipping-bar\", version: \"2.x\")\n @context(provider: \"vtex.apps-graphql\") {\n message\n }\n}\n\n```" } ]
code_minicart-freeshipping-bar_cbbe5f04
[ { "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 minicart-freeshipping-bar/react/components/MinicartFreeshipping.css from the minicart-freeshipping-bar VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.freigthScaleContainer {\n width: 100%;\n padding: 10px 35px;\n box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);\n}\n\n.freigthScaleContainer span {\n font-size: 14px;\n}\n.sliderContainer {\n background-color: #ffffff;\n border: 1px solid #e2d6d1;\n border-radius: 5px;\n height: 10px;\n margin: 10px 0;\n}\n.barContainer {\n border-radius: 5px;\n background:blue;\n height: 10px;\n transition: width 1s;\n}\n\n.sliderText {\n text-align: center;\n font-size: 14px;\n}\n.text0{\n color:black;\n}\n.text1{\n color: black;\n}\n.text2{\n color: black;\n font-weight: bold;\n}\n.text3{\n color: black;\n}\n.text4{\n font-weight:bold;\n text-align:center;\n}\n.currencyText{\n font-size: 14px;\n font-weight: bold;\n}\n\n```" } ]
code_minicart-freeshipping-bar_87d5bc9c
[ { "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 minicart-freeshipping-bar/react/components/MinicartFreeshipping.tsx from the minicart-freeshipping-bar VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React, { useEffect, useCallback, useState } from 'react'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { useQuery } from 'react-apollo'\nimport { FormattedMessage } from 'react-intl'\nimport { FormattedCurrency } from 'vtex.format-currency'\nimport { useRenderSession } from 'vtex.session-client'\n\nimport styles from './MinicartFreeshipping.css'\nimport AppSettings from './minicartbarSettings.graphql'\n\ninterface SettingsProps {\n settings: BindingBoundedSettings\n}\n\ninterface BindingBoundedSettings extends Settings {\n bindingBounded?: boolean\n settings?: [Settings]\n}\ninterface FreeShippingProps {\n freeShippingAmount: number\n tradePolicy: string\n}\ninterface Settings {\n bindingId: string\n freeShippingTradePolicies: [FreeShippingProps]\n}\n\ntype ValueTypes = 'Discounts' | 'Items'\n\nconst MinimumFreightValue: FunctionComponent<SettingsProps> = ({\n settings,\n}) => {\n const { binding } = useRuntime()\n const { session } = useRenderSession()\n const [shippingFreePercentage, setShippingFreePercentage] = useState(0)\n const [differenceBetwenValues, setDifferenceBetwenValues] = useState(0)\n const [freeShippingAmount, setFreeShippingAmount] = useState(0)\n const [freeShippingIndex, setFreeShippingIndex] = useState(0)\n const {\n orderForm: { totalizers },\n } = useOrderForm()\n\n const getChannel = async salesChannel => {\n settings.freeShippingTradePolicies.forEach(\n ({ freeShippingAmount: freeShippingValue, tradePolicy }, index) => {\n if (salesChannel === tradePolicy) {\n setFreeShippingAmount(freeShippingValue)\n setFreeShippingIndex(index)\n }\n }\n )\n }\n\n useEffect(() => {\n if (settings.bindingBounded) {\n const findAmountForBinding = settings.settings?.find(\n item => item.bindingId === binding?.id\n )?.freeShippingTradePolicies[freeShippingIndex].freeShippingAmount\n\n if (findAmountForBinding) setFreeShippingAmount(findAmountForBinding)\n } else if (session?.namespaces) {\n getChannel(session?.namespaces?.store?.channel?.value)\n }\n }, [binding, session])\n\n const handleUpdateMinicartValue = useCallback(\n val => {\n setShippingFreePercentage(Math.round(val / freeShippingAmount))\n setDifferenceBetwenValues(freeShippingAmount - val / 100)\n },\n [freeShippingAmount]\n )\n\n const getValues = (idValue: ValueTypes): number =>\n totalizers?.find(({ id }) => id === idValue)?.value ?? 0\n\n const finalValue = getValues('Items') + getValues('Discounts')\n\n useEffect(() => {\n handleUpdateMinicartValue(finalValue)\n }, [handleUpdateMinicartValue, finalValue])\n\n return (\n <div className={styles.freigthScaleContainer}>\n {differenceBetwenValues === freeShippingAmount ? (\n <div className={styles.text0}>\n <FormattedMessage id=\"store/minicartbar.text0\" />\n <FormattedCurrency value={Math.max(0, differenceBetwenValues)} />!\n </div>\n ) : (\n <>\n {differenceBetwenValues > 0 ? (\n <span>\n <div className={styles.text1}>\n <FormattedMessage id=\"store/minicartbar.text1\" />\n <span className={styles.text2}>\n <FormattedMessage id=\"store/minicartbar.text2\" />\n </span>\n </div>\n </span>\n ) : null}\n <div className={styles.sliderContainer}>\n <div\n className={styles.barContainer}\n style={{\n width: `${\n shippingFreePercentage < 100 ? shippingFreePercentage : 100\n }%`,\n }}\n />\n </div>\n {differenceBetwenValues > 0 ? (\n <p className={styles.sliderText}>\n <span className={styles.text3}>\n <FormattedMessage id=\"store/minicartbar.text3\" />{' '}\n </span>\n\n <span className={styles.currencyText}>\n <FormattedCurrency\n value={Math.max(0, differenceBetwenValues)}\n />\n !\n </span>\n </p>\n ) : (\n <p className={styles.text4}>\n <FormattedMessage id=\"store/minicartbar.text4\" />\n </p>\n )}\n </>\n )}\n </div>\n )\n}\n\nconst MinicartFreeshipping: FunctionComponent = () => {\n const { data } = useQuery(AppSettings, {\n ssr: false,\n fetchPolicy: 'no-cache',\n })\n\n const { binding } = useRuntime()\n\n if (!data?.publicSettingsForApp?.message) return null\n const settings = JSON.parse(data.publicSettingsForApp.message)\n\n if (\n !settings.bindingBounded &&\n !settings.freeShippingTradePolicies[0].freeShippingAmount\n ) {\n console.warn('No Free Shipping amount set')\n\n return null\n }\n\n const isAmountSetForBinding = settings.settings?.find(\n item => item.bindingId === binding?.id\n )?.freeShippingTradePolicies[0].freeShippingAmount\n\n if (settings.bindingBounded && !isAmountSetForBinding) {\n console.warn('No Free Shipping amounts for multi binding store set')\n\n return null\n }\n\n return <MinimumFreightValue settings={settings} />\n}\n\nexport default MinicartFreeshipping\n\n```" } ]
code_google-adwords_2c9a9636
[ { "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 google-adwords/docs/README.md from the google-adwords VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Google Adwords\n\nVTEX Google Adwords first-party app\n\n## How to install\n\nOpen the VTEX App Store and install this app on your store, or run the following command on VTEX toolbelt:\n\n> vtex install vtex.google-adwords@1.x\n\nNow, open the app settings on your admin - https://your-store-name.myvtex.com/admin/apps - click on google adwords app, and fill in the Google Adwords id.\n\n\n```" } ]
code_google-adwords_27af744f
[ { "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 google-adwords/react/index.tsx from the google-adwords VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { getSkuPrice } from './utils'\n\nconst conversionId = window.__SETTINGS__.conversionId\nconst conversionLabel = window.__SETTINGS__.conversionLabel\n\nif (!conversionId) {\n throw new Error('Warning: No Google Adwords ID is defined. To setup the app, go to your admin.')\n}\n\nconst script = document.createElement('script')\n\nscript.src = `https://www.googletagmanager.com/gtag/js?id=${conversionId}`\nscript.async = true\n\ndocument.head!.prepend(script)\n\nwindow.dataLayer = window.dataLayer || []\n\nfunction gtag(...args: any[]) {\n window.dataLayer.push(args)\n}\n\ngtag('js', new Date())\ngtag('config', conversionId)\n\nwindow.addEventListener('message', e => {\n switch (e.data.eventName) {\n case 'vtex:productView': {\n const { product } = e.data\n const productId = product.id || product.productId\n const skuId = product.selectedSku || null\n const productPrice = skuId ? getSkuPrice(product, skuId) : null\n const productDetails = {\n 'ecomm_prodid': skuId ? `${productId}_${skuId}`: productId,\n 'ecomm_pagetype': 'product',\n 'send_to': conversionId,\n 'ecomm_totalvalue': +productPrice,\n 'ecomm_category': product.categories[0] || '',\n }\n gtag(productDetails)\n return\n }\n\n case 'vtex:orderPlaced': {\n const conversionObject = {\n event: 'conversion',\n send_to: conversionLabel ? `${conversionId}/${conversionLabel}`: conversionId,\n value: e.data.transactionTotal || 0,\n currency: e.data.transactionCurrency || 'BRL',\n transaction_id: e.data.transactionId || '',\n }\n gtag(conversionObject)\n return\n }\n\n default: {\n return\n }\n }\n})\n\n```" } ]
code_google-adwords_f4d95a51
[ { "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 google-adwords/react/tests-setup.js from the google-adwords VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable */\nwindow.matchMedia = window.matchMedia || function() {\n return {\n matches: false,\n addListener: function() {},\n removeListener: function() {},\n }\n}\n\n```" } ]
code_google-adwords_7b074a05
[ { "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 google-adwords/react/package.json from the google-adwords VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.google-adwords\",\n \"version\": \"1.3.2\",\n \"description\": \"Google Adwords pixel app\",\n \"scripts\": {\n \"test\": \"jest\",\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json './**/*.ts'\"\n },\n \"author\": \"VTEX\",\n \"license\": \"ISC\",\n \"devDependencies\": {\n \"@types/node\": \"^10.12.18\",\n \"@types/prop-types\": \"^15.5.6\",\n \"@types/react\": \"^16.4.14\",\n \"@types/react-helmet\": \"^5.0.7\",\n \"babel-jest\": \"^22.4.3\",\n \"babel-preset-env\": \"^1.6.1\",\n \"babel-preset-react-app\": \"^3.1.1\",\n \"identity-obj-proxy\": \"^3.0.0\",\n \"jest\": \"^22.4.3\",\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.3.1\",\n \"react-dom\": \"^16.3.1\",\n \"react-intl\": \"^2.4.0\",\n \"react-testing-library\": \"^2.1.1\",\n \"tslint\": \"^5.11.0\",\n \"tslint-config-vtex\": \"^2.0.0\",\n \"tslint-eslint-rules\": \"^5.4.0\",\n \"typescript\": \"^3.1.1\"\n },\n \"jest\": {\n \"verbose\": true,\n \"transform\": {\n \"^.+\\\\.(js|jsx|mjs)$\": \"<rootDir>/node_modules/babel-jest\"\n },\n \"transformIgnorePatterns\": [\n \"[/\\\\\\\\]node_modules[/\\\\\\\\].+\\\\.(js|jsx|mjs)$\"\n ],\n \"setupFiles\": [\n \"./tests-setup.js\"\n ],\n \"moduleNameMapper\": {\n \"\\\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$\": \"<rootDir>/__test__/fileMock.js\",\n \"\\\\.(css|less|scss)$\": \"identity-obj-proxy\"\n }\n },\n \"dependencies\": {\n \"@types/ramda\": \"^0.26.8\"\n }\n}\n\n```" } ]
code_google-adwords_222df275
[ { "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 google-adwords/react/utils.tsx from the google-adwords VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { path } from 'ramda'\n\nexport const getSkuPrice = (product: any, skuId: string) => {\n const selectedItem = product.items.find((item: any) => item.itemId === skuId)\n const commertialOffer: any = path(['sellers', 0, 'commertialOffer'], selectedItem)\n return commertialOffer ? commertialOffer.Price || commertialOffer.ListPrice || commertialOffer.PriceWithoutDiscount || null : null\n}\n```" } ]
code_google-adwords_adcf8d86
[ { "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 google-adwords/react/typings/render.d.ts from the google-adwords VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'render' {\n import Helmet from 'react-helmet'\n\n export {Helmet}\n}\n\n```" } ]
code_google-adwords_7a3faa9b
[ { "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 google-adwords/react/typings/global.d.ts from the google-adwords VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Window extends Window {\n dataLayer: any[]\n __SETTINGS__: {\n conversionId: string\n conversionLabel: string\n }\n}\n\n```" } ]
code_availability-notify-worker_5f4c18c5
[ { "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 availability-notify-worker/docs/README.md from the availability-notify-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n\n\n# Service Example\n\nA reference app implementing a VTEX IO service with HTTP route handlers.\n\n![Service Example Architecture](https://user-images.githubusercontent.com/18706156/77381360-72489680-6d5c-11ea-9da8-f4f03b6c5f4c.jpg)\n\nWe use [**KoaJS**](https://koajs.com/) as the web framework, so you might want to get into that\n\nWe also use the [**node-vtex-api**](https://github.com/vtex/node-vtex-api), a VTEX set of utilities for Node services. You can import this package using NPM from `@vtex/api` (already imported on this project)\n\n- Start from `node/index.ts` and follow the comments and imports :)\n\n## Recipes\n\n### Defining routes on _service.json_ \n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 2,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"routes\": {\n \"status\": {\n \"path\": \"/_v/status/:code\",\n \"public\": true\n }\n }\n}\n```\n\nThe `service.json` file that sits on the root of the `node` folder holds informations about this service, like the maximum timeout and number of replicas, what might be discontinued on the future, but also **sets its routes**. \n\nKoa uses the [path-to-regexp](https://github.com/pillarjs/path-to-regexp) format for defining routes and, as seen on the example, we use the `:code` notation for declaring a **route param** named code, in this case. A HTTP request for `https://{{workspace}}--{{account}}.myvtex.com/_v/status/500` will match the route we've defined. \n\nFor cach _key_ on the `routes` object, there should be a **corresponding entry** on the exported Service object on `node/index.ts`, this will hook your code to a specific route.\n\n### Access Control\nYou can also provide a `public` option for each route. If `true`, that resource will be reachable for everyone on the internet. If `false`, VTEX credentials will be requested as well.\n\nAnother way of controlling access to specific routes is using **ReBACs (Resource-based access)**, that supports more robust configuration. You can read more [on this document](https://docs.google.com/document/d/1ZxNHMFIXfXz3BgTN9xyrHL3V5dYz14wivYgQjRBZ6J8/edit#heading=h.z7pad3qd2qw7) (VTEX only).\n\n#### Query String\nFor `?accepting=query-string`, you **don't need to declare anything**, as any query provided to the URL will already be available for you to use on the code as `ctx.query`, already parsed as an object, or `ctx.queryString`, taken directly from the URL as a string.\n\n#### Route Params\nRoute Params will be available for you to use on the code as `ctx.vtex.params`, already parsed as an object.\nFor a path like `/_v/status/:code`, if you receive the request `/_v/status/200`, `ctx.vtex.params` will return `{ code: '200' }`\n\n#### HTTP methods\nWhen you define a route on the `service.json`, your NodeJS handlers for that route will be triggered **on every HTTP method** (GET, POST, PUT...), so, if you need to handle them separately you need to implement a \"sub-router\". Fortunately, the _node-vtex-api_ provides a helper function `method`, exported from `@vtex/api`, to accomplish that behaviour. Instead of passing your handlers directly to the corresponding route on `index.ts`, you pass a `method` call passing **an object with the desired method as key and one handler as its corresponding value**. Check this example:\n```typescript\nimport { method } from '@vtex/api'\n...\n\nexport default new Service<Clients, State>({\n clients,\n routes: {\n status: method({\n GET: statusGetHandler,\n POST: statusPostHandler,\n }),\n },\n})\n```\n\n### Throwing errors\n\nWhen building a HTTP service, we should follow HTTP rules regarding data types, cache, authorization, and status code. Our example app sets a `ctx.status` value that will be used as a HTTP status code return value, but often we also want to give proper information about errors as well.\n\nThe **node-vtex-api** already exports a handful of **custom error classes** that can be used for that purpose, like the `NotFoundError`. You just need to throw them inside one of the the route handlers that the appropriate response will be sent to the server.\n\n```typescript\nimport { UserInputError } from '@vtex/api'\n\nexport async function validate(ctx: Context, next: () => Promise<any>) {\n const { code } = ctx.vtex.route.params\n if (isNaN(code) || code < 100 || code > 600) {\n throw new UserInputError('Code must be a number between 100 and 600')\n }\n...\n```\n\nYou can check all the available errors [here](https://github.com/vtex/node-vtex-api/tree/fd6139349de4e68825b1074f1959dd8d0c8f4d5b/src/errors), but some are not useful for just-HTTP services. Check the most useful ones:\n\n|Error Class | HTTP Code |\n|--|:--:|\n| `UserInputError` | 400 |\n| `AuthenticationError` | 401 |\n| `ForbiddenError` | 403 |\n| `NotFoundError` | 404 |\n\nYou can also **create your custom error**, just see how it's done above ;)\n\n### Reading a JSON body\n\nWhen writing POST or PUT handlers, for example, often you need to have access to the **request body** that comes as a JSON format, which is not provided directly by the handler function.\n\nFor this, you have to use the [co-body](https://www.npmjs.com/package/co-body) package that will parse the request into a readable JSON object, used as below: \n```typescript\nimport { json } from 'co-body'\nexport async function method(ctx: Context, next: () => Promise<any>) {\n const body = await json(ctx.req)\n```\n\n### Other example apps\n\nWe use Node services across all VTEX, and there are a lot inspiring examples. If you want to dive deeper on learning about this subject, don't miss those internal apps: [builder-hub](https://github.com/vtex/builder-hub) or [store-sitemap](https://github.com/vtex-apps/store-sitemap)\n\n\n## Testing\n\n`@vtex/test-tools` and `@types/jest` should be installed on `./node` package as `devDependencies`.\n\nRun `vtex test` and [Jest](https://jestjs.io/) will do its thing.\n\nCheck the `node/__tests__/simple.test.ts` test case and also [Jest's Documentation](https://jestjs.io/docs/en/getting-started).\n\n## Splunk Dashboard\n\nWe have an (for now, VTEX-only, internal) Splunk dashboard to show all metrics related to your app. You can find it [here](https://splunk7.vtex.com/en-US/app/vtex_colossus/node_app_metrics).\n\nAfter linking this app and making some requests, you can select `vtex.service-example` and see the metrics for your app. **Don't forget to check the box Development, as you are linking your app in a development workspace**.\n\nFor convenience, the link for the current version: https://splunk7.vtex.com/en-US/app/vtex_colossus/node_app_metrics?form.time.earliest=-30m%40m&form.time.latest=%40m&form.picked_context=false&form.picked_region=aws-us-east-*&form.picked_service=vtex.service-example\n\n```" } ]
code_availability-notify-worker_7dd4bc53
[ { "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 availability-notify-worker/node/service.json from the availability-notify-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 60,\n \"timeout\": 2,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"workers\": 1,\n \"routes\": {\n \"forwardNotification\": {\n \"path\": \"/forward-notification\",\n \"public\": false\n }\n }\n}\n\n```" } ]
code_availability-notify-worker_8091b8dd
[ { "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 availability-notify-worker/node/package.json from the availability-notify-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.1.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.6\",\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_availability-notify-worker_d3c7ea0a
[ { "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 availability-notify-worker/node/index.ts from the availability-notify-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ClientsConfig, ServiceContext } from '@vtex/api'\nimport { LRUCache, method, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { forward } from './middlewares/forward'\n\nconst TIMEOUT_MS = 800\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>\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 forwardNotification: method({\n POST: [forward],\n }),\n },\n})\n\n```" } ]
code_availability-notify-worker_514afb3d
[ { "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 availability-notify-worker/node/clients/availability.ts from the availability-notify-worker 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 Availability extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(\n `http://${context.account}.vtexcommercestable.com.br`,\n context,\n options\n )\n }\n\n public async forwardNotification(body: any): Promise<any> {\n return this.http.post(`/_v/availability-notify/notify`, body, {\n headers: {\n VtexIdclientAutCookie: `${this.context.authToken}`,\n },\n metric: 'forward-notification-post',\n })\n }\n}\n\n```" } ]
code_availability-notify-worker_7e8e4b46
[ { "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 availability-notify-worker/node/clients/index.ts from the availability-notify-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport Availability from './availability'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get availability() {\n return this.getOrSet('availability', Availability)\n }\n}\n\n```" } ]
code_availability-notify-worker_bbdfa137
[ { "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 availability-notify-worker/node/middlewares/forward.ts from the availability-notify-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nexport async function forward(ctx: Context, next: () => Promise<any>) {\n const {\n clients: { availability },\n req,\n } = ctx\n\n const request = (await json(req)) as any\n\n try {\n await availability.forwardNotification(request)\n } catch (error) {\n throw new Error(error)\n }\n\n ctx.status = 200\n\n await next()\n}\n\n```" } ]
code_availability-notify-worker_168efba0
[ { "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 availability-notify-worker/node/__tests__/simple.test.ts from the availability-notify-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n// You can import your files here for testing them\n//\n// More info: https://github.com/sapegin/jest-cheat-sheet\n\ndescribe('simpleTest', () => {\n it('one test case', async () => {\n expect(0.2 + 0.1).not.toBe(0.3)\n })\n})\n\n```" } ]
code_store-graphql_1acdf432
[ { "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/graphql/schema.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ndirective @withAuthMetrics on FIELD_DEFINITION\n\ndirective @withOwnerId on FIELD_DEFINITION\n\ntype Query {\n \"\"\"\n Returns a specified product\n \"\"\"\n product(\n \"\"\"\n Product slug\n \"\"\"\n slug: String\n \"\"\"\n Product identifier\n \"\"\"\n identifier: ProductUniqueIdentifier\n ): Product\n @cacheControl(scope: SEGMENT, maxAge: SHORT)\n @withSegment\n @deprecated(reason: \"Use the query defined in the search-graphql app\")\n\n \"\"\"\n Returns products list filtered and ordered\n \"\"\"\n productSearch(\n \"\"\"\n Terms that is used in search e.g.: eletronics/samsung\n \"\"\"\n query: String = \"\"\n \"\"\"\n Defines terms types: Brand, Category, Department e.g.: c,b\n \"\"\"\n map: String = \"\"\n \"\"\"\n Filter by category. {a}/{b} - {a} and {b} are categoryIds\n \"\"\"\n category: String = \"\"\n \"\"\"\n Array of product specification. specificationFilter_{a}:{b} - {a} is the specificationId, {b} = specification value\n \"\"\"\n specificationFilters: [String]\n \"\"\"\n Filter by price range. e.g.: {a} TO {b} - {a} is the minimum price \"from\" and {b} is the highest price \"to\"\n \"\"\"\n priceRange: String = \"\"\n \"\"\"\n Filter by collection. where collection also know as productClusterId\n \"\"\"\n collection: String = \"\"\n \"\"\"\n Filter by availability at a specific sales channel. e.g.: salesChannel:4 if want filter by available products for the sales channel 4\n \"\"\"\n salesChannel: String = \"\"\n \"\"\"\n Order by a criteria. OrderByPriceDESC/OrderByPriceASC, OrderByTopSaleDESC, OrderByReviewRateDESC, OrderByNameASC/OrderByNameDESC, OrderByReleaseDateDESC, OrderByBestDiscountDESC, OrderByScoreDESC\n \"\"\"\n orderBy: String = \"OrderByScoreDESC\"\n \"\"\"\n Pagination item start\n \"\"\"\n from: Int = 0\n \"\"\"\n Pagination item end\n \"\"\"\n to: Int = 9\n \"\"\"\n If true, uses isAvailablePerSalesChannel_ parameter on query with segment's sales channel. Will override any given salesChannel arg\n \"\"\"\n hideUnavailableItems: Boolean = false\n ): ProductSearch\n @cacheControl(scope: SEGMENT, maxAge: SHORT)\n @withSegment\n @deprecated(reason: \"Use the query defined in the search-graphql app\")\n\n searchMetadata(\n \"\"\"\n Terms that is used in search e.g.: eletronics/samsung\n \"\"\"\n query: String = \"\"\n \"\"\"\n Defines terms types: Brand, Category, Department e.g.: c,b\n \"\"\"\n map: String = \"\"\n ): SearchMetadata\n @cacheControl(scope: SEGMENT, maxAge: SHORT)\n @withSegment\n @deprecated(reason: \"Use the query defined in the search-graphql app\")\n\n \"\"\"\n Returns products list filtered and ordered\n \"\"\"\n products(\n \"\"\"\n Terms that is used in search e.g.: eletronics/samsung\n \"\"\"\n query: String = \"\"\n \"\"\"\n Defines terms types: Brand, Category, Department e.g.: c,b\n \"\"\"\n map: String = \"\"\n \"\"\"\n Filter by category. {a}/{b} - {a} and {b} are categoryIds\n \"\"\"\n category: String = \"\"\n \"\"\"\n Array of product specification. specificationFilter_{a}:{b} - {a} is the specificationId, {b} = specification value\n \"\"\"\n specificationFilters: [String]\n \"\"\"\n Filter by price range. e.g.: {a} TO {b} - {a} is the minimum price \"from\" and {b} is the highest price \"to\"\n \"\"\"\n priceRange: String = \"\"\n \"\"\"\n Filter by collection. where collection also know as productClusterId\n \"\"\"\n collection: String = \"\"\n \"\"\"\n Filter by availability at a specific sales channel. e.g.: salesChannel:4 if want filter by available products for the sales channel 4\n \"\"\"\n salesChannel: String = \"\"\n \"\"\"\n Order by a criteria. OrderByPriceDESC/OrderByPriceASC, OrderByTopSaleDESC, OrderByReviewRateDESC, OrderByNameASC/OrderByNameDESC, OrderByReleaseDateDESC, OrderByBestDiscountDESC, OrderByScoreDESC\n \"\"\"\n orderBy: String = \"OrderByScoreDESC\"\n \"\"\"\n Pagination item start\n \"\"\"\n from: Int = 0\n \"\"\"\n Pagination item end\n \"\"\"\n to: Int = 9\n \"\"\"\n If true, uses isAvailablePerSalesChannel_ parameter on query with segment's sales channel. Will override any given salesChannel arg\n \"\"\"\n hideUnavailableItems: Boolean = false\n ): [Product]\n @cacheControl(scope: SEGMENT, maxAge: SHORT)\n @withSegment\n @deprecated(reason: \"Use the query defined in the search-graphql app\")\n\n productRecommendations(\n identifier: ProductUniqueIdentifier\n type: CrossSelingInputEnum\n ): [Product]\n @cacheControl(scope: SEGMENT, maxAge: SHORT)\n @withSegment\n @deprecated(reason: \"Use the query defined in the search-graphql app\")\n\n productsByIdentifier(\n field: ProductUniqueIdentifierField!\n values: [ID!]\n ): [Product]\n @cacheControl(scope: SEGMENT, maxAge: SHORT)\n @withSegment\n @deprecated(reason: \"Use the query defined in the search-graphql app\")\n\n \"\"\"\n Returns facets category\n \"\"\"\n facets(\n \"\"\"\n Categories separated by / followed by map. e.g.: /eletronics/tvs?map=c,c\n \"\"\"\n facets: String = \"\"\n @deprecated(reason: \"Use 'query' and 'map' field instead\")\n \"\"\"\n Terms that is used in search e.g.: eletronics/samsung\n \"\"\"\n query: String = \"\"\n \"\"\"\n Defines terms types: Brand, Category, Department e.g.: c,b\n \"\"\"\n map: String = \"\"\n \"\"\"\n If true, uses isAvailablePerSalesChannel_ parameter on query with segment's sales channel.\n \"\"\"\n hideUnavailableItems: Boolean = false\n ): Facets\n @cacheControl(scope: SEGMENT, maxAge: MEDIUM)\n @withSegment\n @deprecated(reason: \"Use the query defined in the search-graphql app\")\n\n \"\"\"\n Search for products. e.g.: search(query: 'eletronics', rest: 'lg', map: 'c,b')\n \"\"\"\n search(\n \"\"\"\n Terms that is used in search e.g.: eletronics/samsung\n \"\"\"\n query: String = \"\"\n \"\"\"\n Defines terms types: Brand, Category, Department e.g.: c,b\n \"\"\"\n map: String = \"\"\n \"\"\"\n Rest terms that is used in search e.g.: samsung,Android7\n \"\"\"\n rest: String = \"\"\n \"\"\"\n Filter by category. {a}/{b} - {a} and {b} are categoryIds\n \"\"\"\n category: String = \"\"\n \"\"\"\n Array of product specification. specificationFilter_{a}:{b} - {a} is the specificationId, {b} = specification value\n \"\"\"\n specificationFilters: [String]\n \"\"\"\n Filter by price range. e.g.: {a} TO {b} - {a} is the minimum price \"from\" and {b} is the highest price \"to\"\n \"\"\"\n priceRange: String = \"\"\n \"\"\"\n Filter by collection. where collection also know as productClusterId\n \"\"\"\n collection: String = \"\"\n \"\"\"\n Filter by availability at a specific sales channel. e.g.: salesChannel:4 if want filter by available products for the sales channel 4\n \"\"\"\n salesChannel: String = \"\"\n \"\"\"\n Order by a criteria. OrderByPriceDESC/OrderByPriceASC, OrderByTopSaleDESC, OrderByReviewRateDESC, OrderByNameASC/OrderByNameDESC, OrderByReleaseDateDESC, OrderByBestDiscountDESC\n \"\"\"\n orderBy: String = \"OrderByPriceDESC\"\n \"\"\"\n Pagination item start\n \"\"\"\n from: Int = 0\n \"\"\"\n Pagination item end\n \"\"\"\n to: Int = 9\n ): Search\n @cacheControl(scope: SEGMENT, maxAge: SHORT)\n @withSegment\n @deprecated(reason: \"Use the 'products' and 'facets' queries separately\")\n\n \"\"\"\n Returns a specified category\n \"\"\"\n category(\n \"\"\"\n Category id\n \"\"\"\n id: Int\n ): Category @cacheControl(scope: SEGMENT, maxAge: MEDIUM)\n\n \"\"\"\n Returns categories tree\n \"\"\"\n categories(\n \"\"\"\n Category tree level. Default: 3\n \"\"\"\n treeLevel: Int = 3\n ): [Category] @cacheControl(scope: SEGMENT, maxAge: MEDIUM)\n\n \"\"\"\n Returns a specified brand\n \"\"\"\n brand(\n \"\"\"\n Brand id\n \"\"\"\n id: Int\n ): Brand @cacheControl(scope: PUBLIC, maxAge: MEDIUM)\n\n \"\"\"\n Returns brands list\n \"\"\"\n brands: [Brand] @cacheControl(scope: PUBLIC, maxAge: MEDIUM)\n\n \"\"\"\n Returns orderForm shipping simulation\n \"\"\"\n shipping(\n \"\"\"\n List of SKU products\n \"\"\"\n items: [ShippingItem]\n \"\"\"\n Postal code to freight calculator\n \"\"\"\n postalCode: String\n \"\"\"\n geoCoordinates for freight calculator\n \"\"\"\n geoCoordinates: [String]\n \"\"\"\n Country of postal code\n \"\"\"\n country: String\n ): ShippingData\n @cacheControl(scope: SEGMENT, maxAge: MEDIUM)\n @withSegment\n @withOrderFormId\n @withOwnerId\n\n \"\"\"\n Returns checkout cart details\n \"\"\"\n orderForm: OrderForm\n @cacheControl(maxAge: ZERO, scope: PRIVATE)\n @withOrderFormId\n @withOwnerId\n @withSegment\n\n \"\"\"\n returns a certain checkout cart details\n \"\"\"\n searchOrderForm(orderFormId: String!): OrderForm\n @cacheControl(scope: PRIVATE)\n @withOwnerId\n\n \"\"\"\n DEPRECATED\n \"\"\"\n orders: [Order]\n @cacheControl(scope: PRIVATE)\n @withOrderFormId\n @deprecated(reason: \"Use orders endpoint of vtex.orders-graphql instead\")\n\n \"\"\"\n Returns a specified user order\n \"\"\"\n order(id: String!): Order @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Returns the specified store configurations\n \"\"\"\n storeConfigs: StoreConfigs\n\n \"\"\"\n Returns user profile details\n \"\"\"\n profile(\n \"\"\"\n Comma separated fields\n \"\"\"\n customFields: String\n ): Profile @cacheControl(scope: PRIVATE) @withCurrentProfile\n\n \"\"\"\n Get auto complete suggestions in search\n \"\"\"\n autocomplete(\n \"\"\"\n Number of items that is returned\n \"\"\"\n maxRows: Int = 12\n \"\"\"\n Terms that is used in search e.g.: iphone\n \"\"\"\n searchTerm: String\n ): Suggestions\n @cacheControl(scope: SEGMENT, maxAge: MEDIUM)\n @withSegment\n @deprecated(reason: \"Use the query defined in the search-graphql app\")\n\n \"\"\"\n Search documents\n \"\"\"\n documents(\n \"\"\"\n Schema name. e.g.: CL, AD\n \"\"\"\n acronym: String\n \"\"\"\n Fields that will be returned by document. e.g.: _fields=email,firstName,document\n \"\"\"\n fields: [String]\n \"\"\"\n Pagination. Default: 1\n \"\"\"\n page: Int = 1\n \"\"\"\n Items returned in the page. Default: 15\n \"\"\"\n pageSize: Int = 15\n \"\"\"\n Filters the results. eg.: _where=email=my@email.com\n \"\"\"\n where: String\n \"\"\"\n Sorts the results. eg.: _sort=firstName ASC\n \"\"\"\n sort: String\n \"\"\"\n Defines the Master Data schema to be used\n \"\"\"\n schema: String\n \"\"\"\n Defines which account will be required\n \"\"\"\n account: String\n ): [Document] @cacheControl(scope: PUBLIC, maxAge: SHORT)\n\n \"\"\"\n Get document\n \"\"\"\n document(\n \"\"\"\n Schema name. e.g.: CL, AD\n \"\"\"\n acronym: String\n \"\"\"\n Fields that will be returned in document. e.g.: _fields=email,firstName,document\n \"\"\"\n fields: [String]\n \"\"\"\n Document id\n \"\"\"\n id: String\n \"\"\"\n Defines in which account the request will be made\n \"\"\"\n account: String\n ): Document @cacheControl(scope: PUBLIC, maxAge: SHORT)\n\n \"\"\"\n Get a document schema\n \"\"\"\n documentSchema(\n \"\"\"\n Data entity name. e.g.: CL, AD\n \"\"\"\n dataEntity: String\n \"\"\"\n MasterData schema name.\n \"\"\"\n schema: String\n ): DocumentSchema\n\n documentPublicSchema(\n \"\"\"\n Data entity name.\n \"\"\"\n dataEntity: String!\n \"\"\"\n MasterData schema name.\n \"\"\"\n schema: String!\n ): DocumentSchemaV2 @cacheControl(scope: PUBLIC)\n\n \"\"\"\n Get the benefits associated with a list of products\n \"\"\"\n benefits(\n \"\"\"\n List of Products\n \"\"\"\n items: [ShippingItem]\n ): [Benefit] @cacheControl(scope: SEGMENT, maxAge: SHORT) @withSegment\n\n \"\"\"\n Get the options available to authenticate users\n \"\"\"\n loginOptions: LoginOptions @cacheControl(scope: PUBLIC, maxAge: MEDIUM)\n\n \"\"\"\n Get an object containing the list of the user's loginSessions\n \"\"\"\n loginSessionsInfo: LoginSessionsInfo @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Get the IDs for the provided search context slugs\n \"\"\"\n searchContextFromParams(\n brand: String\n department: String\n category: String\n subcategory: String\n ): SearchContext @deprecated(reason: \"Use the 'pageType' query\")\n\n \"\"\"\n Get search page type\n \"\"\"\n pageType(\n \"\"\"\n URL's pathname\n \"\"\"\n path: String!\n \"\"\"\n URL's querystring including '?'\n \"\"\"\n query: String\n ): PageType @cacheControl(scope: PUBLIC, maxAge: MEDIUM)\n\n \"\"\"\n Get logistics information about the store\n \"\"\"\n logistics: LogisticsData @cacheControl(scope: PUBLIC, maxAge: MEDIUM)\n\n \"\"\"\n Get a list of pickup points near specified lat and long\n \"\"\"\n nearPickupPoints(\n \"\"\"\n Desired latitude coordinate, for example: -22.944370\n \"\"\"\n lat: String!\n \"\"\"\n Desired longitude coordinate, for example: -43.182553\n \"\"\"\n long: String!\n \"\"\"\n max distance of pickup points from given coordinates, in kilometers, default value 50\n \"\"\"\n maxDistance: Int = 50\n ): NearPickupPointQueryResponse\n\n skuPickupSLAs(\n itemId: String\n seller: String\n lat: String\n long: String\n country: String\n ): [CheckoutSLA]\n\n skuPickupSLA(\n itemId: String\n seller: String\n lat: String\n long: String\n country: String\n pickupId: String\n ): CheckoutSLA\n\n \"\"\"\n Get pickup point by its id\n \"\"\"\n pickupPoint(id: String!): PickupPoint\n\n \"\"\"\n Get profile information to session users\n \"\"\"\n getSession: Session @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Get the Wish List informations by the received id\n \"\"\"\n list(\n \"\"\"\n The list document id\n \"\"\"\n id: ID\n ): List\n\n \"\"\"\n Get all lists from the received owner\n \"\"\"\n listsByOwner(\n \"\"\"\n The list's owner id\n \"\"\"\n owner: ID!\n \"\"\"\n The page that will be fetched\n \"\"\"\n page: Int = 1\n \"\"\"\n The page size\n \"\"\"\n pageSize: Int = 15\n ): [List]\n\n \"\"\"\n Get logged in user's last order\n \"\"\"\n userLastOrder: Order @cacheControl(scope: PRIVATE)\n\n checkProfileAllowed: UserCondition @cacheControl(scope: PRIVATE) @withSegment\n\n itemsWithSimulation(\n items: [ItemInput]\n regionId: String\n salesChannel: String\n postalCode: String\n ): [SKU] @cacheControl(scope: SEGMENT, maxAge: SHORT) @withSegment\n}\n\ntype Mutation {\n \"\"\"\n Cart\n \"\"\"\n addItem(\n \"\"\"\n Id of orderForm you want to mutate\n \"\"\"\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n \"\"\"\n List of items you want to add and their properties\n \"\"\"\n items: [OrderFormItemInput]\n \"\"\"\n Optional marketing UTM Params to add them to order form\n \"\"\"\n utmParams: OrderFormInputUTMParams\n \"\"\"\n Optional marketing UTMi Params to add them to order form\n \"\"\"\n utmiParams: OrderFormInputUTMIParams\n ): OrderForm @withSegment @withOrderFormId @withOwnerId\n cancelOrder(\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n reason: String\n ): Boolean @withOrderFormId @withOwnerId\n updateItems(\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n items: [OrderFormItemInput]\n ): OrderForm\n @withSegment\n @withOrderFormId\n @withOwnerId\n @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Used to update the CL entity on masterData.\n This mutation is mostly used on the MyAccount app to update the customer's profile.\n The user needs to be signed in or impersonated to perform this mutation.\n \"\"\"\n updateProfile(\n \"\"\"\n The default fields on the CL.\n \"\"\"\n fields: ProfileInput\n \"\"\"\n Extra fields that can be added to the CL.\n \"\"\"\n customFields: [ProfileCustomFieldInput]\n ): Profile @withCurrentProfile @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Updates one address related to a customer profile. This is the AD entity on MasterData.\n The user needs to be signed in or impersonated to perform this mutation.\n \"\"\"\n updateAddress(\n \"\"\"\n Address's id.\n \"\"\"\n id: String\n \"\"\"\n Address's field.\n \"\"\"\n fields: AddressInput\n ): Profile @withCurrentProfile @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Creates one address related to a customer profile. This is the AD entity on MasterData.\n The user needs to be signed in or impersonated to perform this mutation.\n \"\"\"\n createAddress(fields: AddressInput): Profile\n @withCurrentProfile\n @cacheControl(scope: PRIVATE)\n @deprecated(reason: \"Prefer the saveAddress mutation instead.\")\n\n \"\"\"\n Add a new address to a customer profile. This is the AD entity on MasterData.\n The user needs to be signed in or impersonated to perform this mutation.\n \"\"\"\n saveAddress(address: AddressInput!): Address!\n @withCurrentProfile\n @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Deletes an address related to a customer profile. This is the AD entity on MasterData.\n The user needs to be signed in or impersonated to perform this mutation.\n \"\"\"\n deleteAddress(\n \"\"\"\n Address's id.\n \"\"\"\n id: String\n ): Profile @withCurrentProfile @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Updates the Profile Picture by erasing the old ones DEPRECATED\n \"\"\"\n updateProfilePicture(\n \"\"\"\n File being uploaded\n \"\"\"\n file: Upload!\n \"\"\"\n Attachment's field name (default: profilePicture)\n \"\"\"\n field: String @deprecated\n ): Profile @withCurrentProfile @deprecated @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Uploads the Profile Picture by appending to the existing ones DEPRECATED\n \"\"\"\n uploadProfilePicture(\n \"\"\"\n File being uploaded\n \"\"\"\n file: Upload!\n \"\"\"\n Attachment's field name (default: profilePicture)\n \"\"\"\n field: String\n ): Profile @withCurrentProfile @deprecated @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Subscribe to newsletter\n \"\"\"\n subscribeNewsletter(\n email: String\n isNewsletterOptIn: Boolean\n fields: NewsletterFieldsInput\n ): Boolean @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Order Form\n \"\"\"\n updateOrderFormProfile(\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n fields: OrderFormProfileInput\n ): OrderForm @withOrderFormId @withOwnerId\n updateOrderFormShipping(\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n address: OrderFormAddressInput\n ): OrderForm @withOrderFormId @withOwnerId\n updateOrderFormPayment(\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n payments: [OrderFormPaymentInput]\n ): OrderForm @withOrderFormId @withOwnerId\n updateOrderFormIgnoreProfile(\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n ignoreProfileData: Boolean\n ): OrderForm @withOrderFormId @withOwnerId\n addOrderFormPaymentToken(\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n paymentToken: OrderFormPaymentTokenInput\n ): OrderForm @withOrderFormId @withOwnerId\n setOrderFormCustomData(\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n appId: String\n field: String\n value: String\n ): OrderForm @withOrderFormId @withOwnerId\n addAssemblyOptions(\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n itemId: String\n assemblyOptionsId: String\n options: [AssemblyOptionInput]\n ): OrderForm @withOrderFormId @withOwnerId\n updateOrderFormCheckin(\n orderFormId: String\n @deprecated(\n reason: \"Field is no longer needed. Checkout cookie is automatically taken into account now\"\n )\n checkin: OrderFormCheckinInput\n ): OrderForm @withOrderFormId @withOwnerId @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Payment\n \"\"\"\n createPaymentSession: PaymentSession\n createPaymentTokens(\n sessionId: String\n payments: [PaymentInput]\n ): [PaymentToken]\n setPlaceholder(fields: PlaceholderInput): Boolean\n @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Send access key to user email\n \"\"\"\n sendEmailVerification(\n \"\"\"\n User email\n \"\"\"\n email: String!\n ): Boolean @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Access key sign in mode\n \"\"\"\n accessKeySignIn(\n \"\"\"\n User email\n \"\"\"\n email: String!\n \"\"\"\n Access key that was received\n \"\"\"\n code: String!\n ): String @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Classic sign in mode\n \"\"\"\n classicSignIn(\n \"\"\"\n User email\n \"\"\"\n email: String!\n \"\"\"\n User password\n \"\"\"\n password: String!\n ): String @cacheControl(scope: PRIVATE)\n\n \"\"\"\n OAuth to login with Social Account\n \"\"\"\n oAuth(\n \"\"\"\n The OAuth Provider, e.g: Google, Facebook\n \"\"\"\n provider: String\n \"\"\"\n The URL to be redirected after authentication\n \"\"\"\n redirectUrl: String\n ): String @cacheControl(scope: PRIVATE)\n\n \"\"\"\n To recovery password you need to get your email, password and access code\n \"\"\"\n recoveryPassword(\n \"\"\"\n User email\n \"\"\"\n email: String!\n \"\"\"\n User password\n \"\"\"\n newPassword: String!\n \"\"\"\n Access Code\n \"\"\"\n code: String!\n ): String @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Change password using email and old password\n \"\"\"\n redefinePassword(\n \"\"\"\n User's email\n \"\"\"\n email: String!\n \"\"\"\n User's current password\n \"\"\"\n currentPassword: String!\n \"\"\"\n User's new password\n \"\"\"\n newPassword: String!\n \"\"\"\n Your app's identification to help VTEX ID track requests\n \"\"\"\n vtexIdVersion: String\n ): String @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Invalidate VtexIdclientAutCookie\n \"\"\"\n logout: Boolean\n @cacheControl(scope: PRIVATE)\n @deprecated(\n reason: \"See https://github.com/vtex-apps/store-graphql/issues/182\"\n )\n\n \"\"\"\n Logs out from a specific login session\n \"\"\"\n logOutFromSession(sessionId: ID): ID @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Impersonate a customer\n \"\"\"\n impersonate(\n \"\"\"\n The email which will be used to impersonate a user\n \"\"\"\n email: String!\n ): Session @withOrderFormId @withOwnerId @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Depersonify a customer\n \"\"\"\n depersonify: Boolean\n @withOrderFormId\n @withOwnerId\n @withSegment\n @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Document\n \"\"\"\n createDocument(\n acronym: String!\n document: DocumentInput\n account: String\n schema: String\n ): DocumentResponse @withAuthMetrics\n updateDocument(\n acronym: String!\n document: DocumentInput\n account: String\n schema: String\n ): DocumentResponse @withAuthMetrics\n deleteDocument(acronym: String!, documentId: String!): DocumentResponse\n @withAuthMetrics\n uploadAttachment(\n acronym: String!\n documentId: String!\n field: String!\n file: Upload!\n ): AttachmentResponse @withAuthMetrics\n createDocumentV2(\n dataEntity: String!\n document: DocumentInputV2\n account: String\n schema: String\n ): DocumentResponseV2 @cacheControl(scope: PRIVATE) @withAuthMetrics\n\n \"\"\"\n List\n \"\"\"\n createList(list: ListInput): List\n @cacheControl(scope: PRIVATE)\n @withAuthMetrics\n \"\"\"\n Update the list informations and its items.\n If the item given does not have the itemId, add it as a new item in the list.\n If the item given has got an itemId, but its quantity is 0, remove it from the list.\n Otherwise, update it.\n \"\"\"\n updateList(id: ID!, list: ListInput): List\n @cacheControl(scope: PRIVATE)\n @withAuthMetrics\n deleteList(id: ID!): List @cacheControl(scope: PRIVATE) @withAuthMetrics\n\n savePickupInSession(address: OrderFormAddressInput, name: String): Session\n @cacheControl(scope: PRIVATE)\n\n \"\"\"\n Set new orderForm.\n \"\"\"\n newOrderForm(orderFormId: String): OrderForm\n @cacheControl(scope: PRIVATE)\n @withOrderFormId\n @withOwnerId\n}\n\n```" } ]
code_store-graphql_bbfc7707
[ { "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/service.json from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 1536,\n \"ttl\": 30,\n \"timeout\": 40,\n \"minReplicas\": 50,\n \"maxReplicas\": 200,\n \"cpu\": 30,\n \"routes\": {\n \"rectification-config\": {\n \"path\": \"/_v/private/rectification-config\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_store-graphql_d6ee9ac7
[ { "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/package.json from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.store-graphql\",\n \"dependencies\": {\n \"@gocommerce/utils\": \"^0.6.11\",\n \"apollo-datasource-rest\": \"^0.1.5\",\n \"apollo-server-errors\": \"^2.0.2\",\n \"atob\": \"^2.1.2\",\n \"axios\": \"^0.21.2\",\n \"camelcase\": \"^5.0.0\",\n \"cookie\": \"^0.3.1\",\n \"form-data\": \"^2.3.2\",\n \"graphql\": \"^0.13.2\",\n \"graphql-tools\": \"^3.1.1\",\n \"jwt-decode\": \"^2.2.0\",\n \"node-fetch\": \"^2.6.7\",\n \"p-map-series\": \"^2.1.0\",\n \"qs\": \"^6.6.0\",\n \"querystring\": \"^0.2.0\",\n \"ramda\": \"^0.26.1\",\n \"set-cookie-parser\": \"^2.5.1\",\n \"slugify\": \"^1.2.6\",\n \"typescript\": \"3.9.7\",\n \"ua-parser-js\": \"^1.0.2\",\n \"unorm\": \"^1.5.0\",\n \"url-parse\": \"^1.5.9\",\n \"validator\": \"^13.7.0\"\n },\n \"devDependencies\": {\n \"@types/atob\": \"^2.1.2\",\n \"@types/camelcase\": \"^4.1.0\",\n \"@types/cookie\": \"^0.3.2\",\n \"@types/form-data\": \"^2.2.1\",\n \"@types/graphql\": \"0.13.x\",\n \"@types/jwt-decode\": \"^2.2.1\",\n \"@types/koa\": \"^2.0.46\",\n \"@types/node\": \"10.x\",\n \"@types/qs\": \"^6.5.1\",\n \"@types/ramda\": \"0.26.39\",\n \"@types/set-cookie-parser\": \"^2.4.2\",\n \"@types/ua-parser-js\": \"^0.7.36\",\n \"@types/unorm\": \"^1.3.27\",\n \"@types/url-parse\": \"^1.4.3\",\n \"@types/validator\": \"^13.1.4\",\n \"@vtex/api\": \"^3.0.0\",\n \"@vtex/test-tools\": \"2.1.1\",\n \"@vtex/tsconfig\": \"^0.2.0\",\n \"http2\": \"^3.3.7\",\n \"vtex.catalog-api-proxy\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.catalog-api-proxy@0.10.4/public/_types/react\",\n \"vtex.file-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.file-manager@0.11.0/public/_types/react\",\n \"vtex.messages\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.messages@1.68.0/public/@types/vtex.messages\",\n \"vtex.rewriter\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.rewriter@1.61.0/public/@types/vtex.rewriter\",\n \"vtex.store-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.167.0/public/@types/vtex.store-graphql\"\n },\n \"scripts\": {\n \"test\": \"vtex-test-tools test\",\n \"lint\": \"tsc --noEmit && eslint --ext ts .\"\n },\n \"resolutions\": {\n \"json-schema\": \"^0.4.0\",\n \"jsdom\": \"^16.5.0\",\n \"jest-environment-jsdom\": \"^26.0.0\",\n \"node-notifier\": \"^8.0.1\",\n \"follow-redirects\": \"^1.14.8\",\n \"busboy\": \"^1.6.0\"\n },\n \"version\": \"2.173.2\"\n}\n\n```" } ]
code_store-graphql_a7656db2
[ { "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/globals.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n IOContext,\n MetricsAccumulator,\n SegmentData,\n ServiceContext,\n} from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { IdentityDataSource } from './dataSources/identity'\n\nif (!global.metrics) {\n console.error('No global.metrics at require time')\n global.metrics = new MetricsAccumulator()\n}\n\ndeclare global {\n type Context = ServiceContext<Clients, void, CustomContext>\n\n interface CustomContext {\n cookie: string\n dataSources: StoreGraphQLDataSources\n originalPath: string\n vtex: CustomIOContext\n }\n\n interface CustomIOContext extends IOContext {\n currentProfile: CurrentProfile\n segment?: SegmentData\n orderFormId?: string\n ownerId?: string\n }\n\n interface StoreGraphQLDataSources {\n identity: IdentityDataSource\n }\n\n interface UserAddress {\n id: string\n addressName: string\n }\n\n interface UserProfile {\n id: string\n }\n\n interface CurrentProfile {\n email: string\n userId: string\n }\n\n interface Item {\n thumb: string\n name: string\n href: string\n criteria: string\n slug: string\n }\n\n interface Address {\n name?: string\n addressName?: string\n addressType?: string\n city?: string\n complement?: string\n country?: string\n geoCoordinates?: string[]\n id: string\n neighborhood?: string\n number?: string\n postalCode?: string\n receiverName?: string\n reference?: string\n state?: string\n street?: string\n userId: string\n }\n\n interface AddressV2 {\n id: string\n document: {\n administrativeAreaLevel1?: string\n addressName?: string\n addressType?: string\n complement?: string\n countryCode?: string\n extend?: string\n geoCoordinates?: string[]\n locality?: string\n localityAreaLevel1?: string\n name?: string\n nearly?: string\n postalCode?: string\n profileId?: string\n route?: string\n streetNumber?: string\n receiverName?: string\n neighborhood?: string\n }\n meta?: {\n version: string\n author: string\n creationDate: string\n lastUpdateDate: string\n }\n }\n\n interface ProfileV2 {\n id: string\n document: Profile\n meta: {\n version: string\n author: string\n creationDate: string\n lastUpdateDate: string\n }\n }\n\n interface Profile {\n firstName?: string\n lastName?: string\n profilePicture?: string\n email: string\n document?: string\n userId: string\n birthDate?: string\n gender?: string\n homePhone?: string\n businessPhone?: string\n isCorporate?: boolean\n corporateName?: string\n corporateDocument?: string\n stateRegistration?: string\n addresses?: Address[]\n tradeName?: string\n payments?: PaymentProfile[]\n customFields?: ProfileCustomField[]\n id: string\n pii: boolean\n isNewsletterOptIn?: boolean\n }\n\n interface PurchaseInfo {\n id: string\n document: {\n clientPreferences: {\n userId: string\n localeDefault: string\n isNewsletterOptIn?: boolean\n }\n }\n }\n\n interface Account {\n HostName: string\n MainAccountName: string\n IsPersisted: boolean\n IsRemoved: boolean\n Id: string\n Cnpj: string\n CompanyName: string\n TradingName: string\n AccountName: string\n DefaultUrl: string\n Address: string\n Number: string\n Complement: string\n District: string\n City: string\n State: string\n PostalCode: string\n Country: string\n Telephone: string\n IsActive: boolean\n Sponsor: string\n Logo: string\n AppId: string\n IsOperating: boolean\n LV: string\n Sigla: string\n AppKeys: string\n CreationDate: string\n OperationDate: string\n InactivationDate: string\n ParentAccountId: string\n ParentAccountName: string\n ChildAccounts: string[]\n Platform: string\n Licenses: number[]\n Workspace: string\n Stores: string[]\n Privacy: {\n PII: string\n } | null\n Infra: {\n Provider: string\n Region: string\n } | null\n PIIEnabled: boolean\n }\n\n interface PersonalPreferences {\n [key: string]: string | number | boolean | undefined\n firstName?: string\n homePhone?: string\n isNewsletterOptIn?: 'True' | 'False'\n }\n\n interface ProfileCustomField {\n key: string\n value: string\n }\n\n interface PaymentProfile {\n id: string\n paymentSystem: string\n paymentSystemName: string\n carNumber: string\n address: Address\n }\n\n interface DocumentResponse {\n Id: string\n Href: string\n DocumentId: string\n }\n\n interface DocumentResponseV2 {\n Id: string\n Href: string\n DocumentId: string\n }\n\n interface DocumentArgs {\n acronym: string\n fields: string[]\n id: string\n account?: string\n }\n\n interface DocumentSchemaArgs {\n dataEntity: string\n schema: string\n }\n\n interface DocumentsArgs {\n acronym: string\n fields: string[]\n page: number\n pageSize: number\n where: string\n sort: string\n schema?: string\n account?: string\n }\n\n interface CreateDocumentArgs {\n acronym: string\n document: { fields: KeyValue[] }\n account?: string\n schema?: string\n }\n\n interface CreateDocumentV2Args {\n dataEntity: string\n document: { document: any }\n account?: string\n schema?: string\n }\n\n interface UpdateDocumentArgs {\n acronym: string\n document: { fields: KeyValue[] }\n account?: string\n schema?: string\n }\n\n interface DeleteDocumentArgs {\n acronym: string\n documentId: string\n }\n\n interface KeyValue {\n key: string\n value: string\n }\n\n interface IncomingFile {\n filename: string\n mimetype: string\n encoding: string\n }\n\n interface SKU {\n itemId: string\n name: string\n nameComplete: string\n productName: string\n productDescription: string\n brandName: string\n variations: [Property]\n skuSpecifications: [SkuSpecification]\n productSpecifications: [ProductSpecification]\n }\n\n interface Property {\n name: string\n values: [string]\n }\n\n interface SkuSpecification {\n fieldName: string\n fieldValues: string[]\n }\n\n interface ProductSpecification {\n fieldName: string\n fieldValues: string[]\n }\n\n interface Reference {\n Key: string\n Value: string\n }\n\n interface PIIRequest {\n useCase: string\n onBehalfOf: string\n }\n}\n\n```" } ]
code_store-graphql_015d0b9d
[ { "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/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport './globals'\n\nimport { LRUCache, method, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { dataSources } from './dataSources'\nimport { schemaDirectives } from './directives'\nimport { resolvers } from './resolvers'\nimport { getEmailRetificationConfig } from './routes'\n\nconst TWO_SECONDS_MS = 2 * 1000\nconst THREE_SECONDS_MS = 3 * 1000\nconst SIX_SECONDS_MS = 6 * 1000\nconst TEN_SECONDS_MS = 10 * 1000\nconst THIRTY_SECONDS_MS = 30 * 1000\n\n// Segments are small and immutable.\nconst MAX_SEGMENT_CACHE = 10000\nconst segmentCache = new LRUCache<string, any>({ max: MAX_SEGMENT_CACHE })\nconst catalogCache = new LRUCache<string, any>({ max: 3000 })\nconst messagesCache = new LRUCache<string, any>({ max: 3000 })\n\nmetrics.trackCache('segment', segmentCache)\nmetrics.trackCache('catalog', catalogCache)\nmetrics.trackCache('messages', messagesCache)\n\nexport default new Service<Clients, void, CustomContext>({\n clients: {\n implementation: Clients,\n options: {\n checkout: {\n concurrency: 10,\n timeout: THIRTY_SECONDS_MS,\n },\n default: {\n retries: 2,\n timeout: THREE_SECONDS_MS,\n },\n messagesGraphQL: {\n concurrency: 5,\n memoryCache: messagesCache,\n timeout: TWO_SECONDS_MS,\n },\n session: {\n concurrency: 10,\n timeout: TEN_SECONDS_MS,\n },\n segment: {\n concurrency: 10,\n memoryCache: segmentCache,\n timeout: THREE_SECONDS_MS,\n },\n catalog: {\n concurrency: 10,\n memoryCache: catalogCache,\n metrics,\n timeout: SIX_SECONDS_MS,\n },\n },\n },\n graphql: {\n dataSources,\n resolvers,\n schemaDirectives,\n },\n routes: {\n 'rectification-config': method({\n GET: [getEmailRetificationConfig],\n }),\n },\n})\n\n```" } ]
code_store-graphql_0ab4dc4d
[ { "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/graphql/types/ProductSearch.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype ProductSearch {\n products: [Product]\n recordsFiltered: Int\n titleTag: String\n metaTagDescription: String\n breadcrumb: [SearchBreadcrumb]\n}\n\ntype SearchBreadcrumb {\n name: String @translatableV2\n href: String\n}\n\ntype SearchMetadata {\n titleTag: String\n metaTagDescription: String\n}\n\n```" } ]
code_store-graphql_cc3202da
[ { "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/graphql/types/PageType.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype PageType {\n id: String\n type: PageEntityIdentifier\n}\n\nenum PageEntityIdentifier {\n brand\n department\n category\n subcategory\n search\n}\n\n```" } ]
code_store-graphql_b212c77e
[ { "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/graphql/types/Profile.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Profile {\n \"\"\"\n email is used as cacheId\n \"\"\"\n cacheId: ID\n \"\"\"\n DEPRECATED\n \"\"\"\n id: ID @deprecated\n \"\"\"\n User's first name\n \"\"\"\n firstName: String\n \"\"\"\n User's last name\n \"\"\"\n lastName: String\n \"\"\"\n User's profile picture (only fetched if saved as 'profilePicture')\n \"\"\"\n profilePicture: String\n \"\"\"\n User's email\n \"\"\"\n email: String\n \"\"\"\n Document identification. E.g. CPF, SSN, Driver License\n \"\"\"\n document: String\n \"\"\"\n DEPRECATED\n \"\"\"\n phone: String @deprecated\n \"\"\"\n User's ID\n \"\"\"\n userId: ID\n \"\"\"\n User's birth date\n \"\"\"\n birthDate: String\n \"\"\"\n User's gender (plain unvalidated string)\n \"\"\"\n gender: String\n \"\"\"\n User' personal phone\n \"\"\"\n homePhone: String\n \"\"\"\n User's business phone\n \"\"\"\n businessPhone: String\n \"\"\"\n Collection of user's address\n \"\"\"\n address: [Address] @deprecated\n \"\"\"\n Collection of user's address\n \"\"\"\n addresses: [Address]\n \"\"\"\n Whether the user is a corporation or not\n \"\"\"\n isCorporate: Boolean\n \"\"\"\n DEPRECATED\n \"\"\"\n tradeName: String @deprecated\n \"\"\"\n User's company name\n \"\"\"\n corporateName: String\n \"\"\"\n User's company document (e.g. CNPJ)\n \"\"\"\n corporateDocument: String\n \"\"\"\n User's company state registration\n \"\"\"\n stateRegistration: String\n \"\"\"\n Collection of user's payment data\n \"\"\"\n payments: [PaymentProfile]\n \"\"\"\n Other fields to query\n \"\"\"\n customFields: [ProfileCustomField]\n \"\"\"\n User's last password update time\n \"\"\"\n passwordLastUpdate: String\n \"\"\"\n Shows if PII is being audited\n \"\"\"\n pii: Boolean\n}\n\n\"\"\"\nCustom fields to add to query\n\"\"\"\ntype ProfileCustomField {\n \"\"\"\n Id used for caching\n \"\"\"\n cacheId: ID\n \"\"\"\n Name of the custom field\n \"\"\"\n key: String\n \"\"\"\n Value of the custom field\n \"\"\"\n value: String\n}\n\ninput NewsletterFieldsInput {\n name: String\n phone: String\n bindingId: String\n bindingUrl: String\n}\n\n\"\"\"\nProfile information that is receive in session\n\"\"\"\ntype SessionProfile {\n \"\"\"\n profile ID\n \"\"\"\n id: ID\n \"\"\"\n User first name\n \"\"\"\n firstName: String\n \"\"\"\n User last name\n \"\"\"\n lastName: String\n \"\"\"\n User email\n \"\"\"\n email: String\n \"\"\"\n Document identification. E.g. CPF, SSN, Driver License\n \"\"\"\n document: String\n \"\"\"\n User phone number\n \"\"\"\n phone: String\n \"\"\"\n Price tables\n \"\"\"\n priceTables: [String]\n}\n\ntype Address {\n addressId: String\n cacheId: ID\n id: String\n userId: String\n receiverName: String\n complement: String\n neighborhood: String\n country: String\n state: String\n number: String\n street: String\n geoCoordinates: [Float]\n postalCode: String\n city: String\n reference: String\n name: String\n addressName: String\n addressType: String\n}\n\ninput ProfileCustomFieldInput {\n key: String\n value: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n}\n\ninput ProfileInput {\n \"\"\"\n User's email\n \"\"\"\n email: String! @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n User's first name\n \"\"\"\n firstName: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n User's last name\n \"\"\"\n lastName: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n Document identification. E.g. CPF, SSN, Driver License\n \"\"\"\n document: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n DEPRECATED\n \"\"\"\n phone: String\n @deprecated\n @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n User's birth date\n \"\"\"\n birthDate: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n User's gender (plain unvalidated string)\n \"\"\"\n gender: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n User' personal phone\n \"\"\"\n homePhone: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n User's business phone\n \"\"\"\n businessPhone: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n DEPRECATED\n \"\"\"\n tradeName: String\n @deprecated\n @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n User's company corporate name\n \"\"\"\n corporateName: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n User's company corporate document (e.g. CNPJ)\n \"\"\"\n corporateDocument: String\n @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n User's company state registration\n \"\"\"\n stateRegistration: String\n @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n \"\"\"\n Whether the user is a corporation or not\n \"\"\"\n isCorporate: Boolean\n}\n\ntype UserCondition {\n condition: UserConditionType\n allowed: Boolean @deprecated(reason: \"Use condition field instead\")\n}\n\nenum UserConditionType {\n authorized\n unauthorized\n forbidden\n}\n\ninput AddressInput {\n receiverName: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n complement: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n neighborhood: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n country: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n state: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n number: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n street: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n geoCoordinates: [Float]\n postalCode: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n city: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n reference: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n addressName: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n addressType: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n name: String @sanitize(allowHTMLTags: false, stripIgnoreTag: true)\n}\n\n```" } ]
code_store-graphql_9e31babc
[ { "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/graphql/types/Document.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nscalar JSONSchema\nscalar DocumentV2\n\ntype Document {\n \"\"\"\n id is used as cacheId\n \"\"\"\n cacheId: ID\n id: String\n fields: [Field]\n}\n\ntype Field {\n key: String\n value: String\n}\n\ntype DocumentResponse {\n \"\"\"\n documentId is used as cacheId\n \"\"\"\n cacheId: ID\n id: String\n href: String\n documentId: String\n}\n\ntype DocumentResponseV2 {\n \"\"\"\n documentId is used as cacheId\n \"\"\"\n cacheId: ID\n id: String\n href: String\n documentId: String\n}\n\ntype AttachmentResponse {\n filename: String\n mimetype: String\n}\n\ninput FieldInput {\n key: String\n value: String\n}\n\ninput DocumentInput {\n fields: [FieldInput]\n}\n\ninput DocumentInputV2 {\n document: DocumentV2\n}\n\ntype DocProperty {\n name: String\n type: String\n optional: Boolean\n}\n\ntype VSecurity {\n allowGetAll: Boolean\n publicRead: [String]\n publicWrite: [String]\n publicFilter: [String]\n}\n\ntype DocumentSchema {\n name: String\n properties: [DocProperty]\n indexed: [String]\n security: VSecurity\n cache: Boolean\n}\n\ntype DocumentSchemaV2 {\n schema: JSONSchema\n}\n\n```" } ]
code_store-graphql_cb8bf9b8
[ { "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/graphql/types/StoreConfigs.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype StoreConfigs {\n tagManagerId: String\n siteTitle: String\n kiosk: Boolean\n timeout: Int\n url: String\n googleMapsApiKey: String\n ioExtensions: Boolean\n geolocation: Boolean\n leanShipping: Boolean\n invoiceAddress: Boolean\n}\n\n```" } ]
code_store-graphql_f7eff22c
[ { "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/graphql/types/Order.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Order {\n allowCancellation: Boolean\n orderId: String\n orderGroup: String\n state: String\n status: String\n statusDescription: String\n value: Float\n salesChannel: String\n creationDate: String\n customData: CustomData\n lastChange: String\n timeZoneCreationDate: String\n timeZoneLastChange: String\n invoicedDate: String\n isCompleted: Boolean\n items: [OrderItem]\n sellers: [OrderItemSeller]\n totals: [OrderItemTotal]\n paymentData: OrderItemPaymentData\n shippingData: OrderItemShippingData\n storePreferencesData: StorePreferencesData\n}\n\ntype OrderItem {\n uniqueId: String\n id: String\n productId: String\n refId: String\n productRefId: String\n name: String\n skuName: String\n tax: Float\n price: Float\n listPrice: Float\n sellingPrice: Float\n rewardValue: Float\n additionalInfo: OrderItemAdditionalInfo\n preSaleDate: String\n productCategoryIds: String\n handling: Boolean\n isGift: Boolean\n quantity: Int\n seller: String\n imageUrl: String @toVtexAssets\n detailUrl: String\n availability: String\n measurementUnit: String\n unitMultiplier: Float\n parentItemIndex: Int\n parentAssemblyBinding: String\n bundleItems: [OrderItem]\n attachments: [OrderItemAttachment!]!\n}\n\nscalar AttachmentContent\n\ntype OrderItemAttachment {\n name: String\n content: AttachmentContent\n}\n\ntype OrderItemAdditionalInfo {\n brandName: String\n brandId: String\n}\n\ntype OrderItemSeller {\n id: String\n name: String\n logo: String\n}\n\ntype OrderItemTotal {\n id: String\n name: String\n value: Float\n}\n\ntype OrderItemPaymentData {\n transactions: [OrderItemTransactions]\n}\n\ntype OrderItemTransactions {\n isActive: Boolean\n merchantName: String\n payments: [OrderItemPayment]\n transactionId: String\n}\n\ntype OrderItemPayment {\n paymentSystem: String\n paymentSystemName: String\n value: Float\n installments: Int\n connectorResponses: OrderItemPaymentConnectorResponse\n firstDigits: String\n lastDigits: String\n group: String\n url: String\n}\n\ntype OrderItemPaymentConnectorResponse {\n tid: String\n returnCode: String\n message: String\n \"\"\"\n Payment Connector Additional Data Response\n \"\"\"\n additionalData: ConnectorAdditionalData\n}\n\nscalar ConnectorAdditionalData\n\ntype OrderItemShippingData {\n logisticsInfo: [LogisticsInfo]\n address: OrderItemShippingDataAddress\n}\n\ntype OrderItemShippingDataAddress {\n receiverName: String\n postalCode: String\n city: String\n state: String\n country: String\n street: String\n number: String\n neighborhood: String\n complement: String\n reference: String\n}\n\n```" } ]
code_store-graphql_ffaff040
[ { "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/graphql/types/OrderForm.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype OrderForm {\n \"\"\"\n orderFormId is used as cacheId\n \"\"\"\n cacheId: ID\n orderFormId: String\n customData: CustomData\n value: Float\n items: [OrderFormItem]\n salesChannel: String\n loggedIn: Boolean\n isCheckedIn: Boolean\n storeId: String\n allowManualPrice: Boolean\n canEditData: Boolean\n userProfileId: String\n userType: String\n ignoreProfileData: Boolean\n totalizers: [Totalizer]\n clientProfileData: ClientProfile\n sellers: [OrderFormSeller]\n shippingData: OrderFormShippingData\n storePreferencesData: StorePreferencesData\n itemMetadata: ItemMetadata\n checkedInPickupPointId: String\n pickupPointCheckedIn: PickupPoint\n}\n\ntype OrderFormSeller {\n id: String\n name: String\n}\n\ntype CustomData {\n customApps: [CustomApp]\n}\n\nscalar CustomFields\ntype CustomApp {\n fields: CustomFields\n id: String\n major: Int\n}\n\ntype StorePreferencesData {\n countryCode: String\n currencyCode: String\n timeZone: String\n currencyFormatInfo: CurrencyFormatInfo\n currencySymbol: String\n}\n\ntype CurrencyFormatInfo {\n currencyDecimalDigits: Int\n currencyDecimalSeparator: String\n currencyGroupSeparator: String\n startsWithCurrencySymbol: Boolean\n}\n\nscalar ProductCategories\n\ntype OrderFormItem {\n id: ID\n name: String @translatableV2\n detailUrl: String\n imageUrl: String @toVtexAssets\n skuName: String @translatableV2\n productRefId: String\n quantity: Float\n uniqueId: String\n productId: String\n refId: String\n ean: String\n priceValidUntil: String\n price: Float\n tax: Int\n listPrice: Float\n sellingPrice: Float\n rewardValue: Int\n isGift: Boolean\n parentItemIndex: Int\n parentAssemblyBinding: String\n additionalInfo: ItemAdditionalInfo\n \"\"\"\n Informations related to assembly options children of this item\n \"\"\"\n assemblyOptions: AssemblyOptionItem\n \"\"\"\n ID of item's seller\n \"\"\"\n seller: String\n \"\"\"\n Item index on cart\n \"\"\"\n cartIndex: Int\n \"\"\"\n Category ids on orderFormItem\n \"\"\"\n productCategoryIds: String\n productCategories: ProductCategories\n \"\"\"\n Price tags on orderFormItem\n \"\"\"\n priceTags: [PriceTags]\n \"\"\"\n measurementUnit on orderFormItem\n \"\"\"\n measurementUnit: String\n \"\"\"\n Selling price of item summing with all of its children items selling prices.\n \"\"\"\n sellingPriceWithAssemblies: Float\n \"\"\"\n unitMultiplier on orderFormItem\n \"\"\"\n unitMultiplier: Float\n canHaveAttachment: Boolean\n priceDefinition: PriceDefinition\n}\n\ntype PriceDefinition {\n calculatedSellingPrice: Float\n sellingPrices: [SellingPrice]\n total: Float\n}\n\ntype SellingPrice {\n quantity: Float\n value: Float\n}\n\ntype ItemAdditionalInfo {\n brandName: String\n}\n\ntype PriceTags {\n identifier: String\n isPercentual: Boolean\n name: String\n rawValue: Float\n value: Int\n}\n\ntype AssemblyOptionItem {\n \"\"\"\n Assembly options added to parent OrderFormItem\n \"\"\"\n added: [AddedOptionItem]!\n \"\"\"\n Assembly options removed from parent OrderFormItem\n \"\"\"\n removed: [RemovedOptionItem]!\n \"\"\"\n Selling price of parent item\n \"\"\"\n parentPrice: Float\n}\n\ntype Totalizer {\n id: ID\n name: String\n value: Float\n}\n\ntype ClientProfile {\n email: String\n firstName: String\n lastName: String\n phone: String\n isCorporate: Boolean\n corporateDocument: String\n corporateName: String\n corporatePhone: String\n document: String\n documentType: String\n stateInscription: String\n tradeName: String\n}\n\ntype OrderFormShippingData {\n address: Address\n availableAddresses: [Address]!\n selectedAddresses: [Address]!\n}\n\nscalar InputValues\n\ninput OrderFormItemInput {\n id: Int\n index: Int\n quantity: Int\n seller: ID\n inputValues: InputValues\n options: [AssemblyOptionInput]\n}\n\ninput OrderFormAddressInput {\n addressId: String\n addressType: String\n postalCode: String\n country: String\n receiverName: String\n city: String\n state: String\n street: String\n number: String\n complement: String\n neighborhood: String\n geoCoordinates: [Float]\n isDisposable: Boolean\n}\n\ninput OrderFormPaymentInput {\n paymentSystem: Int\n referenceValue: Float\n bin: Int\n tokenId: String\n}\n\ninput OrderFormProfileInput {\n email: String\n isCorporate: Boolean\n corporateDocument: String\n corporateName: String\n corporatePhone: String\n document: String\n documentType: String\n firstName: String\n lastName: String\n phone: String\n stateInscription: String\n tradeName: String\n}\n\ninput OrderFormPaymentTokenInput {\n tokenId: String\n cardNumber: String\n bin: String\n paymentSystem: String\n paymentSystemName: String\n}\n\ninput OrderFormCheckinInput {\n isCheckedIn: Boolean\n pickupPointId: String\n}\n\ninput OrderFormInputUTMParams {\n campaign: String\n medium: String\n source: String\n}\n\ninput OrderFormInputUTMIParams {\n campaign: String\n part: String\n page: String\n}\n\ntype RemovedOptionItem {\n \"\"\"\n The initialQuantity of the assembly option CompositionItem\n \"\"\"\n initialQuantity: Int\n \"\"\"\n The amount that the user removed of this assembly option\n \"\"\"\n removedQuantity: Int\n \"\"\"\n The name of this assembly option\n \"\"\"\n name: String\n}\n\ntype AddedOptionItem {\n \"\"\"\n The OrderFormItem of this assembly options, as appering on cart\n \"\"\"\n item: OrderFormItem\n \"\"\"\n Composition item of assembly option, as it appears on ItemMetadata of OrderForm\n \"\"\"\n compositionItem: CompositionItem\n \"\"\"\n The quantity of this assembly option per parent unit, so childQuantity / parentQuantity\n \"\"\"\n normalizedQuantity: Int\n \"\"\"\n The choice type of this assembly option (MULTIPLE, SINGLE or TOGGLE)\n \"\"\"\n choiceType: String\n \"\"\"\n The real quantity added by user, so quantity in cart minus the item's initialQuantity\n \"\"\"\n extraQuantity: Int\n}\n\ntype CheckoutSLA {\n cacheId: ID\n id: String\n deliveryChannel: String\n name: String\n shippingEstimate: String\n pickupStoreInfo: PickupStoreInfo\n pickupPointId: String\n pickupDistance: Float\n}\n\ntype PickupStoreInfo {\n friendlyName: String\n address: Address\n}\n\n```" } ]
code_store-graphql_dd6a50c3
[ { "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/graphql/types/Brand.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Brand {\n \"\"\" slug is used as cacheId \"\"\"\n cacheId: ID\n \"\"\" Brand id \"\"\"\n id: Int\n \"\"\" Brand logo \"\"\"\n imageUrl: String @toVtexAssets\n \"\"\" Text link\"\"\"\n slug: String\n \"\"\" Name of brand \"\"\"\n name: String @translatableV2\n \"\"\" Title used by html tag\"\"\"\n titleTag: String @translatableV2\n \"\"\" Description used by html tag\"\"\"\n metaTagDescription: String @translatableV2\n \"\"\" Brand is active \"\"\"\n active: Boolean\n}\n\n```" } ]
code_store-graphql_f1cdc59a
[ { "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/graphql/types/Facets.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Facets {\n Departments: [DepartmentFacet] @deprecated(reason: \"Use 'departments' field instead\")\n Brands: [BrandFacet] @deprecated(reason: \"Use 'brands' field instead\")\n SpecificationFilters: [FilterFacets] @deprecated(reason: \"Use 'specificationFilters' field instead\")\n CategoriesTrees: [CategoriesTreeFacet] @deprecated(reason: \"Use 'categoriesTrees' field instead\")\n PriceRanges: [PriceRangesFacet] @deprecated(reason: \"Use 'priceRanges' field instead\")\n departments: [DepartmentFacet]\n brands: [BrandFacet]\n specificationFilters: [FilterFacets]\n categoriesTrees: [CategoriesTreeFacet]\n priceRanges: [PriceRangesFacet]\n recordsFiltered: Int\n}\n\ntype DepartmentFacet {\n Id: Int @deprecated(reason: \"Use 'id' field instead\")\n Name: String @translatableV2 @deprecated(reason: \"Use 'name' field instead\")\n Quantity: Int! @deprecated(reason: \"Use 'quantity' field instead\")\n Link: String! @deprecated(reason: \"Use 'link' field instead\")\n Slug: String @deprecated(reason: \"Use 'slug' field instead\")\n Children: [DepartmentFacet] @deprecated(reason: \"Use 'children' field instead\")\n id: ID!\n quantity: Int!\n name: String @translatableV2\n link: String!\n linkEncoded: String!\n map: String\n value: String!\n selected: Boolean!\n}\n\ntype BrandFacet {\n Id: Int @deprecated(reason: \"Use 'id' field instead\")\n Name: String @translatableV2 @deprecated(reason: \"Use 'name' field instead\")\n Quantity: Int! @deprecated(reason: \"Use 'quantity' field instead\")\n Link: String! @deprecated(reason: \"Use 'link' field instead\")\n Slug: String @deprecated(reason: \"Use 'slug' field instead\")\n Children: [BrandFacet] @deprecated(reason: \"Use 'children' field instead\")\n id: ID!\n quantity: Int!\n name: String!\n link: String!\n linkEncoded: String!\n map: String\n value: String!\n selected: Boolean!\n}\n\ntype PriceRangesFacet {\n Id: Int @deprecated(reason: \"Use 'id' field instead\")\n Name: String @translatableV2 @deprecated(reason: \"Use 'name' field instead\")\n Quantity: Int! @deprecated(reason: \"Use 'quantity' field instead\")\n Link: String! @deprecated(reason: \"Use 'link' field instead\")\n Slug: String @deprecated(reason: \"Use 'slug' field instead\")\n Children: [PriceRangesFacet] @deprecated(reason: \"Use 'children' field instead\")\n quantity: Int!\n name: String @translatableV2\n link: String!\n linkEncoded: String!\n map: String\n value: String!\n selected: Boolean!\n slug: String\n}\n\ntype CategoriesTreeFacet {\n Id: Int @deprecated(reason: \"Use 'id' field instead\")\n Name: String @translatableV2 @deprecated(reason: \"Use 'name' field instead\")\n Quantity: Int! @deprecated(reason: \"Use 'quantity' field instead\")\n Link: String! @deprecated(reason: \"Use 'link' field instead\")\n Slug: String @deprecated(reason: \"Use 'slug' field instead\")\n Children: [CategoriesTreeFacet] @deprecated(reason: \"Use 'children' field instead\")\n id: ID!\n quantity: Int!\n name: String @translatableV2\n link: String!\n linkEncoded: String!\n \"\"\" Contains slugified links according to the store structure. /:department/d, /:category/:subcategory, etc \"\"\"\n href: String!\n map: String\n value: String!\n children: [CategoriesTreeFacet]\n selected: Boolean!\n}\n\ntype FilterFacet {\n Id: Int @deprecated(reason: \"Use 'id' field instead\")\n Name: String @translatableV2 @deprecated(reason: \"Use 'name' field instead\")\n Quantity: Int! @deprecated(reason: \"Use 'quantity' field instead\")\n Link: String! @deprecated(reason: \"Use 'link' field instead\")\n Slug: String @deprecated(reason: \"Use 'slug' field instead\")\n Children: [FilterFacet] @deprecated(reason: \"Use 'children' field instead\")\n quantity: Int!\n name: String @translatableV2\n link: String!\n linkEncoded: String!\n map: String\n value: String!\n selected: Boolean!\n}\n\ntype FilterFacets {\n name: String\n facets: [FilterFacet]\n}\n\n```" } ]
code_store-graphql_eed87e02
[ { "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/graphql/types/Payment.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype PaymentSession {\n id: String\n name: String\n expiresAt: String\n}\n\ntype PaymentToken {\n token: String\n bin: String\n lastDigits: String\n expiresAt: String\n paymentSystem: String\n paymentSystemName: String\n}\n\n\"\"\" Payment data used by profile resolvers \"\"\"\ntype PaymentProfile {\n \"\"\" Id representing this payment form used as reference for the cache\"\"\"\n cacheId: ID\n \"\"\" Id representing this payment form\"\"\"\n id: String\n \"\"\" Id for the payment system related to this payment form\"\"\"\n paymentSystem: String\n \"\"\" The name of the payment system \"\"\"\n paymentSystemName: String\n \"\"\" Last digits of the card this type represents (in the form ************9999)\"\"\"\n cardNumber: String\n \"\"\" Billing address for this payment form (type definition in the Profile file)\"\"\"\n address: Address\n \"\"\" Boolean informing whether the card is expired or not \"\"\"\n isExpired: Boolean\n \"\"\" String representing the expiration date in the form dd/yyyy \"\"\"\n expirationDate: String\n \"\"\" Flag indicating if the card was registered in Profile System as 'notFound' or 'billingAddressEmpty' on the Gateway side \"\"\"\n accountStatus: String\n}\n\ninput PaymentInput {\n paymentSystem: String\n cardHolder: String\n cardNumber: String\n expiryDate: String\n csc: String\n document: String\n documentType: String\n partnerId: String\n address: PaymentAddress\n}\n\ninput PaymentAddress {\n postalCode: String\n street: String\n neighborhood: String\n city: String\n receiverName: String\n state: String\n country: String\n number: String\n complement: String\n }\n\n```" } ]
code_store-graphql_07c2923e
[ { "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/graphql/types/PlaceholderInput.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ninput PlaceholderInput {\n name: String\n component: String\n settings: String\n}\n\n```" } ]
code_store-graphql_ea21c78b
[ { "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/graphql/types/Benefits.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\n\"\"\" Benefit of a Product \"\"\"\ntype Benefit {\n \"\"\" Flag which indicates if the benefit is featured or not \"\"\"\n featured: Boolean\n \"\"\" Id of the product which the benefit is associated \"\"\"\n id: String\n \"\"\" Name of the benefit \"\"\"\n name: String\n \"\"\" Items of the benefit \"\"\"\n items: [BenefitItem]\n \"\"\" Type of benefit \"\"\"\n teaserType: String\n}\n\ntype BenefitItem {\n \"\"\" Product itself \"\"\"\n benefitProduct: Product\n \"\"\" IDs of the SKU Items that are taking part in the benefit \"\"\"\n benefitSKUIds: [String]\n \"\"\" Discount applied to the benefit product \"\"\"\n discount: Float\n \"\"\" Minimum quantity of the benefit product that is required to validate the benefit \"\"\"\n minQuantity: Int\n}\n```" } ]
code_store-graphql_4603697e
[ { "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/graphql/types/Search.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Search {\n facets: Facets\n products: [Product]\n recordsFiltered: Int\n titleTag: String\n metaTagDescription: String\n}\n\n```" } ]
code_store-graphql_d85ee07b
[ { "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/graphql/types/SearchContext.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype SearchContext {\n contextKey: String\n brand: String\n category: String\n}\n\n```" } ]
code_store-graphql_c386e948
[ { "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/graphql/types/ItemMetadata.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype ItemMetadata {\n items: [ItemMetadataUnit]\n priceTable: [ItemPriceTable]\n}\n\ntype ItemPriceTable {\n type: String\n values: [PriceTableItem]\n}\n\ntype PriceTableItem {\n id: String\n assemblyId: String\n price: Int\n}\n\ntype ItemMetadataUnit {\n id: ID\n name: String @translatableV2\n skuName: String @translatableV2\n productId: String\n refId: String\n ean: String\n imageUrl: String @toVtexAssets\n detailUrl: String\n seller: String\n assemblyOptions: [AssemblyOption]\n}\n\ntype AssemblyOption {\n id: ID\n name: String @translatableV2\n required: Boolean\n composition: CompositionType\n}\n\ntype CompositionType {\n minQuantity: Int\n maxQuantity: Int\n items: [CompositionItem]\n}\n\ntype CompositionItem {\n id: ID\n minQuantity: Int\n maxQuantity: Int\n initialQuantity: Int\n priceTable: String\n seller: String\n}\n\ninput AssemblyOptionInput {\n assemblyId: String!\n id: ID\n quantity: Int\n seller: String\n inputValues: InputValues\n options: [AssemblyOptionInput!]\n}\n\n```" } ]
code_store-graphql_3559939d
[ { "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/graphql/types/Suggestions.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Suggestions {\n \"\"\" searchTerm from Query autocomplete is used as cacheId \"\"\"\n cacheId: ID\n itemsReturned: [Items]\n}\n\ntype Items {\n thumb: String\n name: String @translatableV2\n href: String\n criteria: String\n slug: String\n productId: String\n}\n\n```" } ]
code_store-graphql_f426d09a
[ { "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/graphql/types/LoginOptions.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype LoginOptions {\n \"\"\" List of Social providers \"\"\"\n providers: [Provider],\n \"\"\" Email and Password authentication \"\"\"\n classicAuthentication: Boolean,\n \"\"\" Access key through email Code verification \"\"\"\n accessKeyAuthentication: Boolean\n}\n\n\"\"\" Describes an OAuth provider type. e.g.: Google, Facebook\"\"\"\ntype Provider {\n \"\"\" Provider Name. e.g.: Google, Facebook \"\"\"\n providerName: String,\n \"\"\" The provider class. e.g.: google-plus, facebook \"\"\"\n className: String\n}\n```" } ]
code_store-graphql_f5b61e47
[ { "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/graphql/types/Category.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Category {\n \"\"\" id is used as cacheId \"\"\"\n cacheId: ID\n \"\"\" URI of category \"\"\"\n href: String\n \"\"\" Category text link \"\"\"\n slug: String\n \"\"\" Category ID \"\"\"\n id: Int\n \"\"\" Category name \"\"\"\n name: String @translatableV2\n \"\"\" Title used by html tag\"\"\"\n titleTag: String @translatableV2\n \"\"\" Description used by html tag\"\"\"\n hasChildren: Boolean\n \"\"\" Has children categories \"\"\"\n metaTagDescription: String @translatableV2\n \"\"\" Categories children \"\"\"\n children: [Category]\n}\n\n```" } ]
code_store-graphql_8200aeb3
[ { "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/graphql/types/Product.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Product {\n \"\"\"\n Brand of the product\n \"\"\"\n brand: String @translatableV2\n \"\"\"\n Id of the brand of the product\n \"\"\"\n brandId: Int\n \"\"\"\n linkText is used as cacheId\n \"\"\"\n cacheId: ID\n categoryId: ID\n \"\"\"\n Categories of the product\n \"\"\"\n categories: [String]\n @deprecated(\n reason: \"Use 'categoryTree' field for internationalization support\"\n )\n \"\"\"\n Categories ids of the product\n \"\"\"\n categoriesIds: [String]\n @deprecated(\n reason: \"Use 'categoryTree' field for internationalization support\"\n )\n \"\"\"\n Product's categories\n \"\"\"\n categoryTree: [Category]\n \"\"\"\n List of related products\n \"\"\"\n clusterHighlights: [ClusterHighlight]\n productClusters: [ProductClusters]\n \"\"\"\n Product description\n \"\"\"\n description: String @translatableV2\n \"\"\"\n SKU objects of the product\n \"\"\"\n items: [SKU]\n \"\"\"\n Product URL\n \"\"\"\n link: String\n \"\"\"\n Product slug\n \"\"\"\n linkText: String\n \"\"\"\n Product ID\n \"\"\"\n productId: ID\n \"\"\"\n Product name\n \"\"\"\n productName: String @translatableV2\n \"\"\"\n Array of product properties\n \"\"\"\n properties: [Property]\n \"\"\"\n Array of product properties\n \"\"\"\n propertyGroups: [PropertyGroup]\n \"\"\"\n Product reference\n \"\"\"\n productReference: String\n \"\"\"\n Title used by html tag\n \"\"\"\n titleTag: String @translatableV2\n \"\"\"\n Description used by html tag\n \"\"\"\n metaTagDescription: String @translatableV2\n \"\"\"\n Related Products\n \"\"\"\n recommendations: Recommendation\n \"\"\"\n JSON specification of the product\n \"\"\"\n jsonSpecifications: String\n \"\"\"\n List of benefits associated with this product\n \"\"\"\n benefits: [Benefit]\n itemMetadata: ItemMetadata\n \"\"\"\n Array of product SpecificationGroup\n \"\"\"\n specificationGroups: [SpecificationGroup]\n}\n\ntype OnlyProduct {\n brand: String\n categoryId: ID\n categories: [String]\n @deprecated(\n reason: \"Use 'categoryTree' field for internationalization support\"\n )\n categoriesIds: [String]\n @deprecated(\n reason: \"Use 'categoryTree' field for internationalization support\"\n )\n categoryTree: [Category]\n clusterHighlights: [ClusterHighlight]\n productClusters: [ProductClusters]\n description: String\n link: String\n linkText: String\n productId: ID\n productName: String\n properties: [Property]\n propertyGroups: [PropertyGroup]\n productReference: String\n recommendations: Recommendation\n jsonSpecifications: String\n}\n\ntype ProductClusters {\n id: ID\n name: String\n}\n\ntype ClusterHighlight {\n id: ID\n name: String\n}\n\ntype Seller {\n sellerId: ID\n sellerName: String\n addToCartLink: String\n sellerDefault: Boolean\n commertialOffer: Offer\n error: String\n}\n\ntype Recommendation {\n buy: [Product]\n view: [Product]\n similars: [Product]\n}\n\ntype SKU {\n itemId: ID\n name: String @translatableV2\n nameComplete: String @translatableV2\n complementName: String\n ean: String\n referenceId: [Reference]\n measurementUnit: String\n unitMultiplier: Float\n kitItems: [KitItem]\n images(quantity: Int = 10): [Image]\n videos: [Video]\n sellers: [Seller]\n variations: [Property]\n attachments: [Attachment]\n calculatedAttachments: String\n productName: String @translatableV2\n productDescription: String @translatableV2\n brandName: String @translatableV2\n skuSpecifications: [skuSpecification]\n productSpecifications: [productSpecification]\n}\n\ntype skuSpecification {\n fieldName: String @translatableV2\n fieldValues: [String] @translatableV2\n}\n\ntype productSpecification {\n fieldName: String @translatableV2\n fieldValues: [String] @translatableV2\n}\n\ninput ProductUniqueIdentifier {\n field: ProductUniqueIdentifierField!\n value: ID!\n}\n\nenum ProductUniqueIdentifierField {\n id\n slug\n ean\n reference\n sku\n}\n\ntype KitItem {\n itemId: ID\n amount: Int\n product: OnlyProduct\n sku: SKU\n}\n\ntype Attachment {\n id: ID\n name: String\n required: Boolean\n domainValues: [DomainValues]\n}\n\ntype DomainValues {\n FieldName: String\n MaxCaracters: String\n DomainValues: String\n}\n\nenum InstallmentsCriteria {\n MAX\n MIN\n ALL\n}\n\ntype Offer {\n Installments(\n criteria: InstallmentsCriteria = ALL\n rates: Boolean = true\n ): [Installment]\n Price: Float\n ListPrice: Float\n spotPrice: Float\n PriceWithoutDiscount: Float\n RewardValue: Float\n PriceValidUntil: String\n AvailableQuantity: Float\n Tax: Float\n CacheVersionUsedToCallCheckout: String\n DeliverySlaSamples: [DeliverySlaSamples]\n \"\"\"\n List of discount highlights\n \"\"\"\n discountHighlights: [Discount!]\n teasers: [Teaser!]\n \"\"\"\n List of gifts associated with the product\n \"\"\"\n giftSkuIds: [String]\n}\n\ntype Parameter {\n name: String\n value: String\n}\n\ntype TeaserCondition {\n minimumQuantity: Int\n parameters: [Parameter]\n}\n\ntype TeaserEffect {\n parameters: [Parameter]\n}\n\ntype GeneralValueTeaser {\n key: String\n value: String\n}\n\ntype AdditionalInfo {\n key: String\n value: String\n}\n\ntype Teaser {\n name: String\n generalValues: [GeneralValueTeaser]\n conditions: TeaserCondition\n effects: TeaserEffect\n}\n\n\"\"\"\nDiscount object\n\"\"\"\ntype Discount {\n \"\"\"\n Discount name\n \"\"\"\n name: String\n \"\"\"\n Additional Info\n \"\"\"\n additionalInfo: [AdditionalInfo]\n}\n\ntype DeliverySlaSamples {\n DeliverySlaPerTypes: [DeliverySlaPerTypes]\n Region: Region\n}\n\ntype DeliverySlaPerTypes {\n TypeName: String\n Price: Float\n EstimatedTimeSpanToDelivery: String\n}\n\ntype Region {\n IsPersisted: Boolean\n IsRemoved: Boolean\n Id: ID\n Name: String\n CountryCode: String\n ZipCode: String\n CultureInfoName: String\n}\n\ntype Image {\n cacheId: ID\n imageId: ID\n imageLabel: String\n imageTag: String\n imageUrl: String @toVtexAssets\n imageText: String\n}\n\ntype Video {\n videoUrl: String\n}\n\ntype SpecificationGroup {\n name: String @translatableV2\n specifications: [SpecificationGroupProperty]\n}\n\ntype SpecificationGroupProperty {\n name: String @translatableV2\n values: [String] @translatableV2\n}\n\ntype Property {\n name: String\n values: [String]\n}\n\ntype PropertyGroup {\n name: String\n properties: [String]\n}\n\ntype Installment {\n Value: Float\n InterestRate: Float\n TotalValuePlusInterestRate: Float\n NumberOfInstallments: Int\n PaymentSystemName: String\n PaymentSystemGroupName: String\n Name: String\n}\n\ntype Reference {\n Key: String\n Value: String\n}\n\nenum CrossSelingInputEnum {\n buy\n similars\n view\n viewAndBought\n accessories\n suggestions\n}\n\ninput ItemInput {\n itemId: ID\n sellers: [SellerInput]\n}\n\ninput SellerInput {\n sellerId: ID\n}\n\n```" } ]
code_store-graphql_d0bcf21b
[ { "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/graphql/types/List.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\n\"\"\" List of Products \"\"\"\ntype List {\n \"\"\" List's id \"\"\"\n id: ID\n \"\"\" The list's name \"\"\"\n name: String\n \"\"\" Flag that indicates if the list is public or not \"\"\"\n isPublic: Boolean\n \"\"\" Flag that indicates if the list is editable or not \"\"\"\n isEditable: Boolean\n \"\"\" List's owner \"\"\"\n owner: String\n \"\"\" Creation date \"\"\"\n createdIn: String\n \"\"\" Update date \"\"\"\n updatedIn: String\n \"\"\" List items \"\"\"\n items: [ListItem]\n}\ntype ListItem {\n \"\"\" Item id \"\"\"\n id: ID\n \"\"\" Product id \"\"\"\n productId: ID\n \"\"\" Sku id \"\"\"\n skuId: ID\n \"\"\" The quantity of the item \"\"\"\n quantity: Int\n \"\"\" The product's informations \"\"\"\n product: Product\n \"\"\" Date when it was added \"\"\"\n createdIn: String\n}\n\ninput ListInput {\n \"\"\" The list's name \"\"\"\n name: String!\n \"\"\" Flag that indicates if the list is public or not \"\"\"\n isPublic: Boolean\n \"\"\" Flag that indicates if the list is editable or not \"\"\"\n isEditable: Boolean\n \"\"\" List's owner \"\"\"\n owner: String\n \"\"\" List items \"\"\"\n items: [ListItemInput]\n}\n\ninput ListItemInput {\n \"\"\" List item id \"\"\"\n id: ID\n \"\"\" Product id \"\"\"\n productId: ID!\n \"\"\" Sku id \"\"\"\n skuId: ID!\n \"\"\" The quantity of the item \"\"\"\n quantity: Int\n}\n```" } ]
code_store-graphql_f5550486
[ { "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/graphql/types/Session.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\n\"\"\"\nInformations about user Session\n\"\"\"\ntype Session {\n cacheId: ID\n \"\"\"\n Session ID\n \"\"\"\n id: ID\n \"\"\"\n Id of admin logged in session\n \"\"\"\n adminUserId: String\n \"\"\"\n Email of Admin logged in session\n \"\"\"\n adminUserEmail: String\n \"\"\"\n Check if this admin can impersonate a user\n \"\"\"\n impersonable: Boolean\n \"\"\"\n Object with information about impersonate user\n \"\"\"\n impersonate: ImpersonatedUser\n \"\"\"\n Customer address\n \"\"\"\n address: Address\n \"\"\"\n Profile information of session user\n \"\"\"\n profile: SessionProfile\n \"\"\"\n UTM Params\n \"\"\"\n utmParams: UTMParams\n \"\"\"\n UTMI Params\n \"\"\"\n utmiParams: UTMIParams\n favoritePickup: SessionPickup\n}\n\n\"\"\"\nBasic information that is displayed when is a impersonated session\n\"\"\"\ntype ImpersonatedUser {\n \"\"\"\n Profile information of impersonated user\n \"\"\"\n profile: SessionProfile\n}\n\ntype UTMParams {\n source: String\n medium: String\n campaign: String\n term: String\n content: String\n}\n\ntype UTMIParams {\n campaign: String\n page: String\n part: String\n}\n\ntype SessionPickup {\n cacheId: ID\n name: String\n address: Address\n}\n\n```" } ]
code_store-graphql_bd9f1afd
[ { "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/graphql/types/Shipping.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype ShippingData {\n items: [LogisticsItem]\n logisticsInfo: [LogisticsInfo]\n messages: [MessageInfo]\n}\n\ntype MessageInfo {\n code: String\n text: String\n status: String\n fields: MessageFields\n}\n\ntype MessageFields {\n itemIndex: String\n ean: String\n skuName: String\n}\n\ntype LogisticsInfo {\n itemIndex: String\n selectedSla: String\n slas: [ShippingSLA]\n}\n\ntype ShippingSLA {\n id: String\n name: String\n price: Float\n shippingEstimate: String\n shippingEstimateDate: String\n deliveryIds: [DeliveryIds]\n deliveryChannel: String\n friendlyName: String\n pickupPointId: String\n pickupStoreInfo: pickupStoreInfo\n pickupDistance: Float\n}\n\ntype pickupStoreInfo {\n friendlyName: String\n address: PickupAddress\n additionalInfo: String\n dockId: String\n isPickupStore: Boolean\n}\n\ntype PickupAddress {\n addressType: String\n receiverName: String\n addressId: String\n postalCode: String\n city: String\n state: String\n country: String\n street: String\n number: String\n neighborhood: String\n complement: String\n reference: String\n geoCoordinates: [Float]\n}\n\ntype DeliveryIds {\n courierId: String\n warehouseId: String\n dockId: String\n courierName: String\n quantity: Int\n}\n\ntype LogisticsItem {\n id: String\n requestIndex: Int\n quantity: Int\n seller: String\n sellerChain: [String]\n tax: Int\n priceValidUntil: String\n price: Int\n listPrice: Int\n rewardValue: Int\n sellingPrice: Int\n measurementUnit: String\n unitMultiplier: Float\n availability: String\n}\n\ninput ShippingItem {\n id: String\n quantity: String\n seller: String\n}\n\n```" } ]
code_store-graphql_26ebc218
[ { "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/graphql/types/LoginSessionsInfo.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nenum DeviceType {\n MOBILE\n TABLET\n DESKTOP\n}\n\ntype LoginSession {\n id: ID!\n cacheId: ID!\n deviceType: DeviceType!\n city: String\n lastAccess: String!\n browser: String\n os: String\n ip: String\n fullAddress: String\n firstAccess: String!\n}\n\ntype LoginSessionsInfo {\n currentLoginSessionId: ID\n loginSessions: [LoginSession!]\n}\n\n```" } ]
code_store-graphql_a0d5712a
[ { "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/graphql/types/Logistics.graphql from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype LogisticsData {\n \"\"\"\n Countries this store ships to\n \"\"\"\n shipsTo: [String]\n \"\"\"\n Google Maps Geolocation API key\n \"\"\"\n googleMapsKey: String\n}\n\ntype PickupPoint {\n \"\"\"\n Working hours of given pickup point\n \"\"\"\n businessHours: [BusinessHours]\n \"\"\"\n If false, it means pickup point is currently disabled\n \"\"\"\n isActive: Boolean\n \"\"\"\n Pickup point restrictions\n \"\"\"\n pickupHolidays: [HolidayHours]\n \"\"\"\n Distance in kilometers if this is a search result\n \"\"\"\n distance: Float\n friendlyName: String\n id: String\n \"\"\"\n AdditionalInfo from pickup point\n \"\"\"\n instructions: String\n \"\"\"\n Seller account name\n \"\"\"\n seller: String\n address: Address\n}\n\ntype BusinessHours {\n \"\"\"\n Opening time in format HH:MM:SS\n \"\"\"\n openingTime: String\n \"\"\"\n Day of the week representation, 0 for Sunday, 1 for Monday...\n \"\"\"\n dayOfWeek: Int\n \"\"\"\n Closing time in format HH:MM:SS\n \"\"\"\n closingTime: String\n}\n\ntype HolidayHours {\n \"\"\"\n date time in format HH:MM:SS\n \"\"\"\n date: String\n \"\"\"\n hourBegin time in format HH:MM:SS\n \"\"\"\n hourBegin: String\n \"\"\"\n hourEnd time in format HH:MM:SS\n \"\"\"\n hourEnd: String\n}\n\ntype NearPickupPointQueryResponse {\n \"\"\"\n List of pickup points found\n \"\"\"\n items: [PickupPoint]\n}\n\n```" } ]
code_store-graphql_7f14036c
[ { "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/directives/withOwnerId.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { defaultFieldResolver, GraphQLField } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nimport { getOwnerIdFromCookie } from '../utils'\n\nexport class WithOwnerId extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root: any, args: any, ctx: Context, info: any) => {\n const checkoutOwnerId = getOwnerIdFromCookie(ctx.cookies)\n\n ctx.vtex.ownerId = checkoutOwnerId\n\n return resolve(root, args, ctx, info)\n }\n }\n}\n\n```" } ]
code_store-graphql_a5ab29d8
[ { "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/directives/authorizationMetrics.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { defaultFieldResolver, GraphQLField, GraphQLResolveInfo } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nfunction checkForAuthorization(ctx: any, info: GraphQLResolveInfo) {\n const {\n request: {\n headers: {\n 'user-agent': userAgent,\n 'x-forwarded-for': forwardedFor,\n 'x-forwarded-host': forwardedHost,\n 'x-forwarded-path': forwardedPath,\n 'x-vtex-caller': vtexCaller,\n origin,\n Authorization,\n },\n },\n vtex: { logger, adminUserAuthToken, storeUserAuthToken },\n } = ctx\n\n const vtexIdToken =\n ctx.cookies.get('VtexIdclientAutCookie') ?? ctx.get('VtexIdclientAutCookie')\n\n if (!vtexIdToken && Math.floor(Math.random() * 100) === 0) {\n logger.warn({\n message: 'Private route being accessed by unauthorized user',\n userAgent,\n forwardedFor,\n forwardedHost,\n forwardedPath,\n origin,\n vtexCaller,\n Authorization,\n adminUserAuthToken,\n storeUserAuthToken,\n queryName: info?.fieldName,\n queryParentType: info?.parentType.name,\n queryReturnType: info?.returnType.toString(),\n })\n }\n}\n\nexport class AuthorizationMetrics extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root, args, ctx, info) => {\n checkForAuthorization(ctx, info)\n\n return resolve(root, args, ctx, info)\n }\n }\n}\n\n```" } ]
code_store-graphql_56e0ed36
[ { "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/directives/withSegment.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { defaultFieldResolver, GraphQLField } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\nimport atob from 'atob'\n\n/**\n * Warning: we stopped using the segment client to decode the segment token for us because it added unnecessary overhead for now.\n * If the getSegment API evolves to do more than a decode we must stop decoding it here and start calling the API once again.\n */\nexport class WithSegment extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root, args, ctx: Context, info) => {\n const {\n vtex: { segmentToken },\n clients: { segment },\n } = ctx\n\n ctx.vtex.segment = segmentToken\n ? JSON.parse(atob(segmentToken))\n : await segment.getSegment()\n\n return resolve(root, args, ctx, info)\n }\n }\n}\n\n```" } ]
code_store-graphql_dea0504c
[ { "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/directives/withCurrentProfile.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { parse as parseCookie } from 'cookie'\nimport { defaultFieldResolver, GraphQLField, GraphQLResolveInfo } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\nimport jwtDecode from 'jwt-decode'\nimport { AuthenticationError, ResolverError } from '@vtex/api'\n\nimport { getSession } from '../resolvers/session/service'\nimport { SessionFields } from '../resolvers/session/sessionResolver'\nimport { DefaultUser, User } from '../dataSources/identity'\n\ntype UserType = 'StoreUser' | 'CallCenterOperator'\ninterface ProfileInfos<ProfileType = CurrentProfile | null> {\n currentProfile: ProfileType\n userType?: UserType\n userData?: User | DefaultUser\n}\n\nexport class WithCurrentProfile extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root, args, context, info) => {\n const profileInfos: ProfileInfos = await getCurrentProfileFromSession(\n context\n )\n .catch(() => {\n if (context.vtex.storeUserAuthToken) {\n return getStoreUserProfileFromCookie(context)\n }\n\n return getCurrentProfileFromCookies(context)\n })\n .catch(() => ({\n currentProfile: null,\n }))\n\n const { currentProfile } = profileInfos\n\n if (!isLogged(currentProfile)) {\n return null\n }\n\n // If the current profile doesn't exist, a new profile will be created, there is no need to check it\n if (profileInfos.currentProfile !== null) {\n await checkUserAccount(\n context,\n profileInfos as ProfileInfos<CurrentProfile>,\n info\n )\n }\n\n context.vtex.currentProfile = await validatedProfile(\n context,\n currentProfile as CurrentProfile\n )\n\n return resolve(root, args, context, info)\n }\n }\n}\n\nasync function getCurrentProfileFromSession(\n context: Context\n): Promise<ProfileInfos> {\n return getSession(context).then((currentSession) => {\n const session = currentSession as SessionFields\n\n if (!session || !session.id) {\n throw new ResolverError('Error fetching session data')\n }\n\n const profile = session?.impersonate?.profile ?? session.profile\n\n return {\n currentProfile: profile\n ? ({ email: profile.email, userId: profile.id } as CurrentProfile)\n : null,\n // If is impersonate is a call center op\n userType:\n session?.impersonate?.profile || session?.public?.impersonate\n ? 'CallCenterOperator'\n : 'StoreUser',\n }\n })\n}\n\nasync function getStoreUserProfileFromCookie(\n context: Context\n): Promise<ProfileInfos> {\n const {\n vtex: { storeUserAuthToken: userToken },\n dataSources: { identity },\n } = context\n\n return identity.getUserWithToken(userToken!).then((data) => {\n if (data && 'id' in data) {\n return {\n currentProfile: { userId: data.id, email: data.user },\n userData: data,\n userType: 'StoreUser',\n }\n }\n\n return { currentProfile: null }\n })\n}\n\nasync function getCurrentProfileFromCookies(\n context: Context\n): Promise<ProfileInfos> {\n const {\n clients: { profile },\n vtex: { adminUserAuthToken, storeUserAuthToken },\n request: {\n headers: { cookie },\n },\n } = context\n\n const parsedCookies = parseCookie(cookie || '')\n\n const userToken = storeUserAuthToken\n const adminToken = adminUserAuthToken\n\n if (!userToken && !!adminToken) {\n const adminInfo = jwtDecode(adminToken) as any\n\n const callOpUserEmail = adminInfo?.sub\n const isValidCallOp =\n callOpUserEmail &&\n (await isValidCallcenterOperator(context, callOpUserEmail))\n\n if (!isValidCallOp) {\n throw new AuthenticationError('User is not a valid callcenter operator')\n }\n\n const customerEmail = parsedCookies['vtex-impersonated-customer-email']\n\n return profile\n .getProfileInfo({ email: customerEmail, userId: '' }, context, undefined)\n .then(({ email, userId }) => ({\n currentProfile: { email, userId },\n userType: 'CallCenterOperator',\n }))\n }\n\n return { currentProfile: null }\n}\n\nasync function validatedProfile(\n context: Context,\n currentProfile: CurrentProfile\n): Promise<CurrentProfile> {\n const {\n clients: { profile },\n } = context\n\n const { id, userId } = (await profile\n .getProfileInfo(currentProfile, context, 'id')\n .catch(() => {})) || { id: '', userId: '' } // 404 case.\n\n if (id) {\n return { userId, email: currentProfile.email }\n }\n\n return profile\n .createProfile(\n {\n email: currentProfile.email,\n userId,\n } as Profile,\n context\n )\n .then((newProfile: Profile) =>\n profile.getProfileInfo(\n { userId: newProfile.userId, email: '' },\n context,\n undefined\n )\n )\n}\n\nasync function isValidCallcenterOperator(context: Context, email: string) {\n const {\n clients: { callCenterOperator, licenseManager },\n vtex: { authToken },\n } = context\n\n return licenseManager\n .getAccountData(authToken)\n .then(({ id }: any) =>\n callCenterOperator.isValidCallcenterOperator({ email, accountId: id })\n )\n}\n\nfunction isLogged(currentProfile: CurrentProfile | null) {\n return currentProfile?.email\n}\n\nasync function checkUserAccount(\n context: Context,\n {\n currentProfile,\n userData: storeUser,\n userType,\n }: ProfileInfos<CurrentProfile>,\n resolverInfo: GraphQLResolveInfo\n) {\n const {\n dataSources: { identity },\n vtex: { adminUserAuthToken, storeUserAuthToken, account },\n } = context\n\n if (!adminUserAuthToken && !storeUserAuthToken) {\n throw new AuthenticationError('')\n }\n\n let tokenUser = storeUser\n\n if (!tokenUser) {\n tokenUser = await identity.getUserWithToken(\n storeUserAuthToken! ?? adminUserAuthToken!\n )\n }\n\n if (tokenUser && 'account' in tokenUser && tokenUser.account !== account) {\n const {\n fieldName,\n returnType,\n operation: { operation, name },\n } = resolverInfo\n\n const {\n vtex: { logger, host },\n req: {\n headers: { 'user-agent': userAgent, referer },\n },\n } = context\n\n const logData = {\n host,\n referer,\n userAgent,\n message: 'Type: CrossTokenAccount',\n account,\n tokenAccount: tokenUser.account ?? '',\n caller: tokenUser.user ?? '',\n fieldName,\n fieldType: (returnType as any).name,\n operation: name?.value ? `${operation} ${name?.value}` : operation,\n }\n\n logger.warn(logData)\n }\n\n // If has admin user auth token, off course is a call center operator\n const isUserCallCenterOperator = userType === 'CallCenterOperator'\n\n if (\n tokenUser &&\n 'id' in tokenUser &&\n !(\n tokenUser.account === account &&\n (isUserCallCenterOperator ||\n tokenUser.user.toLowerCase() === currentProfile?.email.toLowerCase() ||\n tokenUser.customerId === currentProfile?.userId)\n )\n ) {\n throw new AuthenticationError('Information conflict in tokenUser')\n }\n}\n\n```" } ]
code_store-graphql_b0a3ddbe
[ { "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/directives/toVtexAssets.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { defaultFieldResolver, GraphQLField } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nimport { flags } from '../utils/featureFlags'\n\nexport class ToVtexAssets extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root, args, ctx: Context, info) => {\n const result = resolve(root, args, ctx, info)\n\n return flags.VTEX_ASSETS_URL && result\n ? result.replace('vteximg.com.br', 'vtexassets.com')\n : result\n }\n }\n}\n\n```" } ]
code_store-graphql_2f5fc259
[ { "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/directives/withOrderFormId.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { defaultFieldResolver, GraphQLField } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nimport { getOrderFormIdFromCookie } from '../utils'\n\nexport class WithOrderFormId extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root, args, ctx: Context, info) => {\n const checkoutOrderFormId = getOrderFormIdFromCookie(ctx.cookies)\n\n ctx.vtex.orderFormId = checkoutOrderFormId\n\n return resolve(root, args, ctx, info)\n }\n }\n}\n\n```" } ]
code_store-graphql_a59b22a6
[ { "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/directives/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { WithCurrentProfile } from './withCurrentProfile'\nimport { WithSegment } from './withSegment'\nimport { WithOrderFormId } from './withOrderFormId'\nimport { ToVtexAssets } from './toVtexAssets'\nimport { AuthorizationMetrics } from './authorizationMetrics'\nimport { WithOwnerId } from './withOwnerId'\n\nexport const schemaDirectives = {\n toVtexAssets: ToVtexAssets,\n withCurrentProfile: WithCurrentProfile,\n withSegment: WithSegment,\n withOrderFormId: WithOrderFormId,\n withOwnerId: WithOwnerId,\n withAuthMetrics: AuthorizationMetrics,\n}\n\n```" } ]
code_store-graphql_3a103ee0
[ { "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/dataSources/identity.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { RequestOptions } from 'apollo-datasource-rest'\nimport { forEachObjIndexed } from 'ramda'\n\nimport { RESTDataSource } from './RESTDataSource'\n\nexport interface DefaultUser {\n authStatus: string\n}\n\nexport interface User extends DefaultUser {\n id: string\n user: string\n customerId: string\n account: string\n audience: string\n}\n\nexport class IdentityDataSource extends RESTDataSource {\n public getUserWithToken = (token: string) => {\n const {\n vtex: { account },\n } = this.context\n\n return this.post<DefaultUser | User>(\n `credential/validate?an=${account}`,\n {\n token,\n },\n { metric: 'vtexid-getUserWithToken' }\n )\n }\n\n public get baseURL() {\n return 'http://portal.vtexcommercestable.com.br/api/vtexid'\n }\n\n protected willSendRequest(request: RequestOptions) {\n const {\n vtex: { authToken },\n } = this.context\n\n forEachObjIndexed(\n (value: string, header) => request.headers.set(header, value),\n {\n 'Proxy-Authorization': authToken,\n VtexIdClientAutCookie: authToken,\n 'X-Vtex-Proxy-To': `http://portal.vtexcommercestable.com.br`,\n }\n )\n }\n}\n\n```" } ]
code_store-graphql_58c95713
[ { "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/dataSources/RESTDataSource.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ServiceContext } from '@vtex/api'\nimport { RESTDataSource as ApolloRESTDataSource } from 'apollo-datasource-rest'\nimport {\n BodyInit,\n RequestInit as ApolloRequestInit,\n URLSearchParamsInit,\n} from 'apollo-server-env'\n\ntype Body = BodyInit | Record<string, unknown>\n\ninterface RequestInit extends ApolloRequestInit {\n metric?: string\n}\n\nexport class RESTDataSource extends ApolloRESTDataSource<ServiceContext> {\n protected async get<TResult = any>(\n path: string,\n params?: URLSearchParamsInit,\n init?: RequestInit\n ): Promise<TResult> {\n return this.withMetrics(\n () => super.get<TResult>(path, params, init as any),\n init?.metric\n )\n }\n\n protected async post<TResult = any>(\n path: string,\n body?: Body,\n init?: RequestInit\n ): Promise<TResult> {\n return this.withMetrics(\n () => super.post<TResult>(path, body, init as any),\n init?.metric\n )\n }\n\n protected async patch<TResult = any>(\n path: string,\n body?: Body,\n init?: RequestInit\n ): Promise<TResult> {\n return this.withMetrics(\n () => super.patch<TResult>(path, body, init as any),\n init?.metric\n )\n }\n\n protected async put<TResult = any>(\n path: string,\n body?: Body,\n init?: RequestInit\n ): Promise<TResult> {\n return this.withMetrics(\n () => super.put<TResult>(path, body, init as any),\n init?.metric\n )\n }\n\n protected async delete<TResult = any>(\n path: string,\n params?: URLSearchParamsInit,\n init?: RequestInit\n ): Promise<TResult> {\n return this.withMetrics(\n () => super.delete<TResult>(path, params, init as any),\n init?.metric\n )\n }\n\n private withMetrics = async <TResult = any>(\n handler: () => Promise<TResult>,\n metric?: string\n ) => {\n const start = metric && process.hrtime()\n let status = 'APOLLO_NOT_ASSIGNED'\n\n try {\n status = 'APOLLO_REST_OK'\n\n return await handler()\n } catch (err) {\n status = 'APOLLO_REST_ERROR'\n throw err\n } finally {\n if (metric) {\n const label = `http-client-${status}-${metric}`\n\n metrics.batch(label, process.hrtime(start as [number, number]))\n }\n }\n }\n}\n\n```" } ]
code_store-graphql_f5160be4
[ { "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/dataSources/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IdentityDataSource } from './identity'\n\nexport const dataSources = () => ({\n identity: new IdentityDataSource(),\n})\n\n```" } ]
code_store-graphql_7b5d5013
[ { "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/clients/callCenterOperator.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n ExternalClient,\n RequestConfig,\n} from '@vtex/api'\n\nimport { statusToError } from '../utils'\n\nexport class CallCenterOperator extends ExternalClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super('http://licensemanager.vtex.com.br/api/pvt/accounts', ctx, {\n ...options,\n headers: {\n ...options?.headers,\n ...{ Accept: 'application/vnd.vtex.ds.v10+json' },\n ...(ctx.adminUserAuthToken\n ? { VtexIdclientAutCookie: ctx.adminUserAuthToken }\n : null),\n },\n })\n }\n\n public isValidCallcenterOperator = ({\n email,\n accountId,\n }: IsValidCallcenterOperatorArgs) =>\n this.get<boolean>(\n `${accountId}/products/2/logins/${email}/resources/Televendas/granted?ignoreIsAdmin=False`,\n { metric: 'callCenterOp-isValidCallcenterOperator' }\n )\n\n protected get = <T>(url: string, config?: RequestConfig) =>\n this.http.get<T>(url, config).catch(statusToError)\n}\n\ninterface IsValidCallcenterOperatorArgs {\n email: string\n accountId: string\n}\n\n```" } ]
code_store-graphql_0eb52206
[ { "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/clients/masterdata.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n ExternalClient,\n RequestConfig,\n UserInputError,\n} from '@vtex/api'\nimport FormData from 'form-data'\nimport validator from 'validator'\n\nimport { statusToError } from '../utils'\n\nconst DATAENTITIES_PREFIX = '/dataentities'\n\nexport class MasterData extends ExternalClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(`http://api.vtex.com/${ctx.account}`, ctx, {\n ...options,\n headers: {\n ...options?.headers,\n ...{ Accept: 'application/vnd.vtex.ds.v10+json' },\n ...(ctx.adminUserAuthToken\n ? { VtexIdclientAutCookie: ctx.adminUserAuthToken }\n : null),\n ...(ctx.storeUserAuthToken\n ? { VtexIdclientAutCookie: ctx.storeUserAuthToken }\n : null),\n },\n })\n }\n\n public getSchema = <T>(dataEntity: string, schema: string) =>\n this.get<T>(this.routes.schema(dataEntity, schema), {\n metric: 'masterdata-getSchema',\n })\n\n public getPublicSchema = <T>(dataEntity: string, schema: string) =>\n this.get<T>(this.routes.publicSchema(dataEntity, schema), {\n metric: 'masterdata-getPublicSchema',\n })\n\n public getDocument = <T>(\n acronym: string,\n id: string,\n fields: string[],\n account?: string\n ) =>\n this.get<T>(this.routes.document(acronym, id), {\n metric: 'masterdata-getDocument',\n params: {\n _fields: generateFieldsArg(fields),\n ...(account ? { an: account } : null),\n },\n })\n\n public createDocument = (\n acronym: string,\n // eslint-disable-next-line @typescript-eslint/ban-types\n fields: object,\n schema?: string,\n account?: string\n ) =>\n this.post<DocumentResponse>(this.routes.documents(acronym), fields, {\n metric: 'masterdata-createDocument',\n params: {\n ...(schema ? { _schema: schema } : null),\n ...(account ? { an: account } : null),\n },\n })\n\n public updateDocument = (\n acronym: string,\n id: string,\n // eslint-disable-next-line @typescript-eslint/ban-types\n fields: object,\n account?: string,\n schema?: string\n ) =>\n this.patch(this.routes.document(acronym, id), fields, {\n metric: 'masterdata-updateDocument',\n params: {\n ...(schema ? { _schema: schema } : null),\n ...(account ? { an: account } : null),\n },\n })\n\n public searchDocuments = <T>(\n acronym: string,\n fields: string[],\n where: string,\n pagination: PaginationArgs,\n schema?: string,\n sort?: string,\n account?: string\n ) => {\n return this.get<T[]>(this.routes.search(acronym), {\n headers: paginationArgsToHeaders(pagination),\n metric: 'masterdata-searchDocuments',\n params: {\n _fields: generateFieldsArg(fields),\n _where: where,\n _sort: sort,\n ...(schema ? { _schema: schema } : null),\n ...(account ? { an: account } : null),\n },\n })\n }\n\n public deleteDocument = (acronym: string, id: string) =>\n this.delete(this.routes.document(acronym, id), {\n metric: 'masterdata-deleteDocument',\n })\n\n public uploadAttachment = (\n acronym: string,\n id: string,\n fields: string,\n formData: FormData\n ) =>\n this.post<any>(this.routes.attachments(acronym, id, fields), formData, {\n headers: formData.getHeaders(),\n metric: 'masterdata-uploadAttachment',\n })\n\n protected get = <T>(url: string, config?: RequestConfig) => {\n return this.http.get<T>(url, config).catch(statusToError)\n }\n\n protected post = <T>(url: string, data?: any, config?: RequestConfig) => {\n return this.http.post<T>(url, data, config).catch(statusToError)\n }\n\n protected delete = <T>(url: string, config?: RequestConfig) => {\n return this.http.delete<T>(url, config).catch(statusToError)\n }\n\n protected patch = <T>(url: string, data?: any, config?: RequestConfig) => {\n return this.http.patch<T>(url, data, config).catch(statusToError)\n }\n\n private get routes() {\n return {\n attachments: (acronym: string, id: string, fields: string) => {\n checkForURLsInStringArguments(acronym, id, fields)\n\n return `${DATAENTITIES_PREFIX}/${acronym}/documents/${id}/${fields}/attachments`\n },\n document: (acronym: string, id: string) => {\n checkForURLsInStringArguments(acronym, id)\n\n return `${DATAENTITIES_PREFIX}/${acronym}/documents/${id}`\n },\n documents: (acronym: string) => {\n checkForURLsInStringArguments(acronym)\n\n return `${DATAENTITIES_PREFIX}/${acronym}/documents`\n },\n schema: (acronym: string, schema: string) => {\n checkForURLsInStringArguments(acronym, schema)\n\n return `${DATAENTITIES_PREFIX}/${acronym}/schemas/${schema}`\n },\n publicSchema: (acronym: string, schema: string) => {\n checkForURLsInStringArguments(acronym, schema)\n\n return `${DATAENTITIES_PREFIX}/${acronym}/schemas/${schema}/public`\n },\n search: (acronym: string) => {\n checkForURLsInStringArguments(acronym)\n\n return `${DATAENTITIES_PREFIX}/${acronym}/search`\n },\n }\n }\n}\n\nfunction paginationArgsToHeaders({ page, pageSize }: PaginationArgs) {\n if (page < 1) {\n throw new UserInputError('Smallest page value is 1')\n }\n\n const startIndex = (page - 1) * pageSize\n const endIndex = startIndex + pageSize\n\n return {\n 'REST-Range': `resources=${startIndex}-${endIndex}`,\n }\n}\n\nfunction generateFieldsArg(fields: string[]) {\n return fields.join(',')\n}\n\n/**\n * This function throws an error if any of the passed args are an URL.\n * We need to perform this check to protect our servers against possible\n * SSRF attacks.\n *\n * @param {...string[]} args\n */\nfunction checkForURLsInStringArguments(...args: string[]) {\n for (let idx = 0; idx < args.length; idx++) {\n if (validator.isURL(args[idx])) {\n throw new UserInputError('Invalid arguments')\n }\n }\n}\n\ninterface PaginationArgs {\n page: number\n pageSize: number\n}\n\n```" } ]
code_store-graphql_415cbf32
[ { "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/clients/PvtCheckout.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n JanusClient,\n RequestConfig,\n} from '@vtex/api'\n\nimport { statusToError } from '../utils'\n\nexport class PvtCheckout extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n ...(ctx.authToken ? { VtexIdclientAutCookie: ctx.authToken } : null),\n 'x-vtex-user-agent': ctx.userAgent,\n },\n })\n }\n\n private getCommonHeaders = () => {\n const { segmentToken, sessionToken } = this.context as CustomIOContext\n\n const segmentTokenCookie = segmentToken\n ? `vtex_segment=${segmentToken};`\n : ''\n\n const sessionTokenCookie = sessionToken\n ? `vtex_session=${sessionToken};`\n : ''\n\n return {\n Cookie: `${segmentTokenCookie}${sessionTokenCookie}`,\n }\n }\n\n private getChannelQueryString = (salesChannel?: string) => {\n const { segment } = this.context as CustomIOContext\n const channel = salesChannel ?? segment?.channel\n\n return channel ? `?sc=${channel}` : ''\n }\n\n public simulation = (simulation: SimulationPayload, salesChannel?: string) =>\n this.post<SimulationOrderForm>(\n this.routes.simulation(this.getChannelQueryString(salesChannel)),\n simulation,\n {\n metric: 'pvt-checkout-simulation',\n }\n )\n\n protected post = <T>(url: string, data?: any, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http.post<T>(url, data, config).catch(statusToError) as Promise<\n T\n >\n }\n\n private get routes() {\n return {\n simulation: (queryString: string) =>\n `/api/checkout/pvt/orderForms/simulation${queryString}`,\n }\n }\n}\n\n```" } ]
code_store-graphql_101864b1
[ { "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/clients/checkout.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n JanusClient,\n RequestConfig,\n IOResponse,\n IOContext,\n} from '@vtex/api'\nimport { AxiosError } from 'axios'\n\nimport { setCheckoutCookies } from '../resolvers/checkout'\nimport {\n checkoutCookieFormat,\n ownershipCookieFormat,\n OWNERSHIP_COOKIE,\n statusToError,\n} from '../utils'\n\nexport class Checkout extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n ...(ctx.storeUserAuthToken\n ? { VtexIdclientAutCookie: ctx.storeUserAuthToken }\n : null),\n 'x-vtex-user-agent': ctx.userAgent,\n },\n })\n }\n\n private getCommonHeaders = () => {\n const { orderFormId, ownerId, segmentToken, sessionToken } = this\n .context as CustomIOContext\n\n const checkoutCookie = orderFormId ? checkoutCookieFormat(orderFormId) : ''\n const ownershipCookie = ownerId ? ownershipCookieFormat(ownerId) : ''\n const segmentTokenCookie = segmentToken\n ? `vtex_segment=${segmentToken};`\n : ''\n\n const sessionTokenCookie = sessionToken\n ? `vtex_session=${sessionToken};`\n : ''\n\n return {\n Cookie: `${checkoutCookie}${ownershipCookie}${segmentTokenCookie}${sessionTokenCookie}`,\n }\n }\n\n private getChannelQueryString = () => {\n const { segment } = this.context as CustomIOContext\n const channel = segment?.channel\n const queryString = channel ? `?sc=${channel}` : ''\n\n return queryString\n }\n\n public addItem = (orderFormId: string, items: any) =>\n this.post<OrderForm>(\n this.routes.addItem(orderFormId, this.getChannelQueryString()),\n { orderItems: items },\n { metric: 'checkout-addItem' }\n )\n\n public cancelOrder = (orderFormId: string, reason: string) =>\n this.post(\n this.routes.cancelOrder(orderFormId),\n { reason },\n { metric: 'checkout-cancelOrder' }\n )\n\n public setOrderFormCustomData = (\n orderFormId: string,\n appId: string,\n field: string,\n value: any\n ) =>\n this.put(\n this.routes.orderFormCustomData(orderFormId, appId, field),\n { value },\n { metric: 'checkout-setOrderFormCustomData' }\n )\n\n public updateItems = (orderFormId: string, orderItems: any) =>\n this.post(\n this.routes.updateItems(orderFormId),\n { orderItems },\n { metric: 'checkout-updateItems' }\n )\n\n public updateOrderFormIgnoreProfile = (\n orderFormId: string,\n ignoreProfileData: boolean\n ) =>\n this.patch(\n this.routes.profile(orderFormId),\n { ignoreProfileData },\n { metric: 'checkout-updateOrderFormIgnoreProfile' }\n )\n\n public updateOrderFormPayment = (orderFormId: string, payments: any) =>\n this.post(\n this.routes.attachmentsData(orderFormId, 'paymentData'),\n { payments },\n { metric: 'checkout-updateOrderFormPayment' }\n )\n\n public updateOrderFormProfile = async (\n orderFormId: string,\n fields: any,\n ctx: Context\n ) => {\n const { data, headers } = await this.postRaw(\n this.routes.attachmentsData(orderFormId, 'clientProfileData'),\n fields,\n { metric: 'checkout-updateOrderFormProfile' }\n )\n\n setCheckoutCookies(headers, ctx, [OWNERSHIP_COOKIE])\n\n return data\n }\n\n public updateOrderFormShipping = (orderFormId: string, shipping: any) =>\n this.post(\n this.routes.attachmentsData(orderFormId, 'shippingData'),\n shipping,\n { metric: 'checkout-updateOrderFormShipping' }\n )\n\n public updateOrderFormMarketingData = (\n orderFormId: string,\n marketingData: any\n ) =>\n this.post(\n this.routes.attachmentsData(orderFormId, 'marketingData'),\n marketingData,\n { metric: 'checkout-updateOrderFormMarketingData' }\n )\n\n public updateOrderFormClientPreferencesData = (\n orderFormId: string,\n clientPreferencesData: OrderFormClientPreferencesData\n ) => {\n // The API default value of `optinNewsLetter` is `null`, but it doesn't accept a POST with its value as `null`\n const filteredClientPreferencesData =\n clientPreferencesData.optinNewsLetter === null\n ? { locale: clientPreferencesData.locale }\n : clientPreferencesData\n\n return this.post(\n this.routes.attachmentsData(orderFormId, 'clientPreferencesData'),\n filteredClientPreferencesData,\n { metric: 'checkout-updateOrderFormClientPreferencesData' }\n )\n }\n\n public addAssemblyOptions = async (\n orderFormId: string,\n itemId: string | number,\n assemblyOptionsId: string,\n body: any\n ) =>\n this.post<OrderForm>(\n this.routes.assemblyOptions(orderFormId, itemId, assemblyOptionsId),\n body,\n { metric: 'checkout-addAssemblyOptions' }\n )\n\n public removeAssemblyOptions = async (\n orderFormId: string,\n itemId: string | number,\n assemblyOptionsId: string,\n body: any\n ) =>\n this.delete<OrderForm>(\n this.routes.assemblyOptions(orderFormId, itemId, assemblyOptionsId),\n { metric: 'checkout-removeAssemblyOptions', data: body }\n )\n\n public updateOrderFormCheckin = (orderFormId: string, checkinPayload: any) =>\n this.post(this.routes.checkin(orderFormId), checkinPayload, {\n metric: 'checkout-updateOrderFormCheckin',\n })\n\n public orderForm = (orderFormId?: string) => {\n return this.post<OrderForm>(\n this.routes.orderForm(orderFormId),\n { expectedOrderFormSections: ['items'] },\n { metric: 'checkout-orderForm' }\n )\n }\n\n public orderFormRaw = () => {\n return this.postRaw<OrderForm>(\n this.routes.orderForm(),\n { expectedOrderFormSections: ['items'] },\n { metric: 'checkout-orderForm' }\n )\n }\n\n public newOrderForm = (orderFormId?: string) => {\n return this.http\n .postRaw<OrderForm>(this.routes.orderForm(orderFormId), undefined, {\n metric: 'checkout-newOrderForm',\n })\n .catch(statusToError) as Promise<IOResponse<OrderForm>>\n }\n\n public changeToAnonymousUser = (orderFormId: string) => {\n return this.get(this.routes.changeToAnonymousUser(orderFormId), {\n metric: 'checkout-change-to-anonymous',\n }).catch((err) => {\n // This endpoint is expected to return a redirect to\n // the user, so we can ignore the error if it is a 3xx\n if (!err.response || /^3..$/.test((err as AxiosError).code ?? '')) {\n throw err\n }\n })\n }\n\n // Deprecated: This endpoint is deprecated and any request will return an empty array\n public orders = () =>\n this.get(this.routes.orders, { metric: 'checkout-orders' }).catch((err) => {\n if (err.response && err.response.status === 405) {\n return []\n }\n\n throw err\n })\n\n public simulation = (simulation: SimulationPayload) =>\n this.post<SimulationOrderForm>(\n this.routes.simulation(this.getChannelQueryString()),\n simulation,\n {\n metric: 'checkout-simulation',\n }\n )\n\n protected get = <T>(url: string, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http.get<T>(url, config).catch(statusToError) as Promise<T>\n }\n\n protected post = <T>(url: string, data?: any, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http.post<T>(url, data, config).catch(statusToError) as Promise<\n T\n >\n }\n\n protected postRaw = async <T>(\n url: string,\n data?: any,\n config: RequestConfig = {}\n ) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http\n .postRaw<T>(url, data, config)\n .catch(statusToError) as Promise<IOResponse<T>>\n }\n\n protected delete = <T>(url: string, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http.delete<T>(url, config).catch(statusToError) as Promise<\n IOResponse<T>\n >\n }\n\n protected patch = <T>(\n url: string,\n data?: any,\n config: RequestConfig = {}\n ) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http\n .patch<T>(url, data, config)\n .catch(statusToError) as Promise<T>\n }\n\n protected put = <T>(url: string, data?: any, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http.put<T>(url, data, config).catch(statusToError) as Promise<\n T\n >\n }\n\n private get routes() {\n const base = '/api/checkout/pub'\n\n return {\n addItem: (orderFormId: string, queryString: string) =>\n `${base}/orderForm/${orderFormId}/items${queryString}`,\n cancelOrder: (orderFormId: string) =>\n `${base}/orders/${orderFormId}/user-cancel-request`,\n orderFormCustomData: (\n orderFormId: string,\n appId: string,\n field: string\n ) => `${base}/orderForm/${orderFormId}/customData/${appId}/${field}`,\n updateItems: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/items/update`,\n profile: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/profile`,\n attachmentsData: (orderFormId: string, field: string) =>\n `${base}/orderForm/${orderFormId}/attachments/${field}`,\n assemblyOptions: (\n orderFormId: string,\n itemId: string | number,\n assemblyOptionsId: string\n ) =>\n `${base}/orderForm/${orderFormId}/items/${itemId}/assemblyOptions/${assemblyOptionsId}`,\n checkin: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/checkIn`,\n orderForm: (orderFormId?: string) =>\n `${base}/orderForm/${orderFormId ?? ''}`,\n orders: `${base}/orders`,\n simulation: (queryString: string) =>\n `${base}/orderForms/simulation${queryString}`,\n changeToAnonymousUser: (orderFormId: string) =>\n `/checkout/changeToAnonymousUser/${orderFormId}`,\n }\n }\n}\n\n```" } ]
code_store-graphql_3fcefd75
[ { "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/clients/licenseManagerExtended.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n LicenseManager,\n RequestConfig,\n} from '@vtex/api'\n\nimport { statusToError } from '../utils'\n\nconst FIVE_SECONDS_MS = 5 * 1000\n\nexport class LicenseManagerExtendedClient extends LicenseManager {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n ...options?.headers,\n VtexIdClientAutCookie: context.authToken ?? '',\n },\n timeout: FIVE_SECONDS_MS,\n })\n }\n\n public getCurrentAccount = (customFields?: string) =>\n this.get<Account>(`${this.baseUrl}/${this.context.account}`, {\n metric: 'account-getAccount',\n params: {\n extraFields: customFields,\n },\n }).then((account: Account) => {\n account.PIIEnabled = Boolean(account.Privacy)\n\n return account\n })\n\n protected get = <T>(url: string, config?: RequestConfig) =>\n this.http.get<T>(url, config).catch<any>(statusToError)\n\n private baseUrl = '/api/pvt/accounts'\n}\n\n```" } ]
code_store-graphql_1299c117
[ { "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/clients/session.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { JanusClient } from '@vtex/api'\nimport parseCookie from 'cookie'\n\ninterface VtexIdCookies {\n account: string | null\n id: string | null\n}\n\nconst SESSION_COOKIE = 'vtex_session'\n\nconst routes = {\n base: '/api/sessions',\n}\n\nexport class Session extends JanusClient {\n /**\n * Get the session data using the given token\n */\n public getSession = async (token: string, items: string[]) => {\n const { data: sessionData, headers } = await this.http.getRaw(routes.base, {\n headers: {\n 'Content-Type': 'application/json',\n Cookie: `vtex_session=${token};`,\n },\n metric: 'session-get',\n params: {\n items: items.join(','),\n },\n })\n\n return {\n sessionData,\n sessionToken: extractSessionCookie(headers) ?? token,\n }\n }\n\n /**\n * Update the public portion of this session\n */\n public updateSession = (\n key: string,\n value: any,\n items: string[],\n token: any,\n vtexIdCookies: VtexIdCookies\n ) => {\n const data = { public: { [key]: { value } } }\n let cookies = `vtex_session=${token};`\n\n if (vtexIdCookies.account) {\n cookies += `${vtexIdCookies.account};`\n }\n\n if (vtexIdCookies.id) {\n cookies += `${vtexIdCookies.id};`\n }\n\n const config = {\n headers: {\n 'Content-Type': 'application/json',\n Cookie: cookies,\n },\n metric: 'session-update',\n params: {\n items: items.join(','),\n },\n }\n\n return this.http.post(routes.base, data, config)\n }\n}\n\nfunction extractSessionCookie(headers: Record<string, string>) {\n for (const setCookie of headers['set-cookie'] ?? []) {\n const parsedCookie = parseCookie.parse(setCookie)\n const sessionCookie = parsedCookie[SESSION_COOKIE]\n\n if (sessionCookie != null) {\n return sessionCookie\n }\n }\n\n return null\n}\n\n```" } ]
code_store-graphql_e05dc0df
[ { "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/clients/oms.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n JanusClient,\n RequestConfig,\n} from '@vtex/api'\n\nimport { statusToError } from '../utils'\n\nexport class OMS extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n ...(ctx.storeUserAuthToken\n ? { VtexIdclientAutCookie: ctx.storeUserAuthToken }\n : null),\n },\n })\n }\n\n public userLastOrder = () =>\n this.get(this.routes.lastOrder, { metric: 'oms-userLastOrder' })\n\n public order = (id: string) =>\n this.get(this.routes.order(id), { metric: 'oms-order' })\n\n protected get = <T>(url: string, config: RequestConfig = {}) => {\n const { segmentToken, sessionToken } = this.context as CustomIOContext\n const segmentTokenCookie = segmentToken\n ? `vtex_segment=${segmentToken};`\n : ''\n\n const sessionTokenCookie = sessionToken\n ? `vtex_session=${sessionToken};`\n : ''\n\n config.headers = {\n ...config.headers,\n Cookie: `${segmentTokenCookie}${sessionTokenCookie}`,\n }\n\n return this.http.get<T>(url, config).catch(statusToError)\n }\n\n private get routes() {\n const base = '/api/oms'\n\n return {\n lastOrder: `${base}/user/orders/last`,\n order: (id: string) => `${base}/pvt/orders/${id}`,\n }\n }\n\n public getEmailRetificationConfig() {\n return this.http.get('/api/oms/configuration/email-rectification-enabled', {\n headers: { VtexIdclientAutCookie: this.context.authToken },\n })\n }\n}\n\n```" } ]
code_store-graphql_adc5396f
[ { "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/clients/logistics.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n JanusClient,\n RequestConfig,\n} from '@vtex/api'\n\nimport { statusToError } from '../utils'\nimport {\n LogisticOutput,\n LogisticPickupPoint,\n} from '../resolvers/logistics/types'\n\nconst FOUR_SECONDS = 4 * 1000\n\nexport class LogisticsClient extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n VtexIdclientAutCookie: ctx.authToken,\n },\n timeout: FOUR_SECONDS,\n })\n }\n\n public pickupById = (id: string) =>\n this.get<LogisticPickupPoint>(this.routes.pickUpById(id), {\n metric: 'logistics-pickupById',\n })\n\n public nearPickupPoints = (lat: string, long: string, maxDistance = 50) =>\n this.get<LogisticOutput>(\n this.routes.nearPickupPoints(lat, long, maxDistance),\n {\n metric: 'logistics-nearPickupPoints',\n }\n )\n\n public shipping = () =>\n this.get(this.routes.shipping, {\n metric: 'logistics-shipping',\n })\n\n protected get = <T>(url: string, config?: RequestConfig) =>\n this.http.get<T>(url, config).catch(statusToError) as Promise<T>\n\n private get routes() {\n const basePVT = '/api/logistics'\n\n return {\n shipping: `${basePVT}/pub/shipping/configuration`,\n nearPickupPoints: (lat: string, long: string, maxDistance: number) =>\n `${basePVT}/pvt/configuration/pickuppoints/_search?&page=1&pageSize=100&lat=${lat}&lon=${long}&maxDistance=${maxDistance}`,\n pickUpById: (id: string) =>\n `${basePVT}/pvt/configuration/pickuppoints/${id}`,\n }\n }\n}\n\n```" } ]
code_store-graphql_7db98660
[ { "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/clients/rewriter.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n AppGraphQLClient,\n IOContext,\n InstanceOptions,\n GraphQLResponse,\n Serializable,\n} from '@vtex/api'\n\nconst getRouteQuery = `query GetRoute($id: String!, $type: String!) {\n internal {\n routes(locator: {id:$id, type:$type}) {\n route\n binding\n }\n }\n}\n`\n\ninterface Route {\n route: string\n binding: string\n}\n\ninterface GetRoutesResponse {\n internal: {\n routes: Route[]\n }\n}\n\nclass CustomGraphQLError extends Error {\n public graphQLErrors: any\n\n constructor(message: string, graphQLErrors: any[]) {\n super(message)\n this.graphQLErrors = graphQLErrors\n }\n}\n\nexport function throwOnGraphQLErrors<T extends Serializable>(message: string) {\n return function maybeGraphQLResponse(response: GraphQLResponse<T>) {\n // eslint-disable-next-line no-self-compare\n if (response?.errors?.length || 0 > 0) {\n throw new CustomGraphQLError(message, response.errors!)\n }\n\n return response\n }\n}\n\nexport class Rewriter extends AppGraphQLClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super('vtex.rewriter@1.x', context, {\n ...options,\n headers: {\n ...options?.headers,\n },\n })\n }\n\n public getRoute = async (id: string, type: string, bindingId: string) => {\n const responseData = await this.graphql\n .query<GetRoutesResponse, { id: string; type: string }>(\n {\n query: getRouteQuery,\n variables: { id, type },\n },\n {\n metric: 'search-get-route',\n }\n )\n .then(throwOnGraphQLErrors('Error getting route data from vtex.rewriter'))\n .then((data) => {\n return data.data!.internal.routes\n })\n\n return responseData.find((route) => route.binding === bindingId)?.route\n }\n}\n\n```" } ]
code_store-graphql_593dcba5
[ { "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/clients/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport { CallCenterOperator } from './callCenterOperator'\nimport { Catalog } from './catalog'\nimport { Checkout } from './checkout'\nimport { PvtCheckout } from './PvtCheckout'\nimport { MasterData } from './masterdata'\nimport { ProfileClient } from './profile'\nimport { ProfileClientV1 } from './profile/profileV1'\nimport { ProfileClientV2 } from './profile/profileV2'\nimport { LicenseManagerExtendedClient } from './licenseManagerExtended'\nimport { OMS } from './oms'\nimport { Portal } from './portal'\nimport { LogisticsClient } from './logistics'\nimport { Session } from './session'\nimport { Rewriter } from './rewriter'\n\nexport class Clients extends IOClients {\n public get masterdata() {\n return this.getOrSet('masterdata', MasterData)\n }\n\n public get checkout() {\n return this.getOrSet('checkout', Checkout)\n }\n\n public get pvtCheckout() {\n return this.getOrSet('pvtCheckout', PvtCheckout)\n }\n\n public get callCenterOperator() {\n return this.getOrSet('callCenterOperator', CallCenterOperator)\n }\n\n public get catalog() {\n return this.getOrSet('catalog', Catalog)\n }\n\n public get profile() {\n return this.getOrSet('profile', ProfileClient)\n }\n\n public get profileV1() {\n return this.getOrSet('profileV1', ProfileClientV1)\n }\n\n public get profileV2() {\n return this.getOrSet('profileV2', ProfileClientV2)\n }\n\n public get licenseManagerExtended() {\n return this.getOrSet('licenseManagerExtended', LicenseManagerExtendedClient)\n }\n\n public get oms() {\n return this.getOrSet('oms', OMS)\n }\n\n public get portal() {\n return this.getOrSet('portal', Portal)\n }\n\n public get logistics() {\n return this.getOrSet('logistics', LogisticsClient)\n }\n\n public get customSession() {\n return this.getOrSet('customSession', Session)\n }\n\n public get rewriter() {\n return this.getOrSet('rewriter', Rewriter)\n }\n}\n\n```" } ]
code_store-graphql_494aae93
[ { "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/clients/portal.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n JanusClient,\n RequestConfig,\n} from '@vtex/api'\n\nimport { statusToError } from '../utils'\n\nexport class Portal extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n VtexIdclientAutCookie: ctx.authToken,\n },\n })\n }\n\n public sites = () =>\n this.get<Site[]>(this.routes.allSites(), { metric: 'portal-sites' })\n\n public storeConfigs = (activeSite: string) =>\n this.get(this.routes.storeConfigs(activeSite), {\n metric: 'portal-site-config',\n })\n\n public defaultSalesChannel = () =>\n this.get<SalesChannel>(this.routes.scDefault, {\n metric: 'portal-default-sales-channel',\n })\n\n protected get = <T>(url: string, config?: RequestConfig) =>\n this.http.get<T>(url, config).catch(statusToError)\n\n private get routes() {\n const basePVT = '/api/portal/pvt'\n\n return {\n allSites: () => `${basePVT}/sites/`,\n storeConfigs: (activeSite: string) =>\n `${basePVT}/sites/${activeSite}/configuration`,\n scDefault: '/api/catalog_system/pub/saleschannel/default',\n }\n }\n}\n\nexport interface Site {\n id: string\n title: string\n siteName: string\n}\n\nexport interface SalesChannel {\n Id: string\n Name: string\n IsActive: true\n ProductClusterId: string | null\n CountryCode: string\n CultureInfo: string\n TimeZone: string\n CurrencyCode: string\n CurrencySymbol: string\n CurrencyLocale: number\n CurrencyFormatInfo: {\n CurrencyDecimalDigits: number\n CurrencyDecimalSeparator: string\n CurrencyGroupSeparator: string\n CurrencyGroupSize: number\n StartsWithCurrencySymbol: boolean\n }\n Origin: any\n Position: number\n ConditionRule: any\n}\n\n```" } ]
code_store-graphql_8f43177f
[ { "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/clients/catalog.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n AppClient,\n InstanceOptions,\n IOContext,\n RequestConfig,\n SegmentData,\n} from '@vtex/api'\nimport { stringify } from 'qs'\n\nimport { CatalogCrossSellingTypes } from '../resolvers/catalog/utils'\n\ninterface AutocompleteArgs {\n maxRows: string\n searchTerm: string\n}\n\nconst inflightKey = ({ baseURL, url, params, headers }: RequestConfig) => {\n const segmentToken = headers && headers['x-vtex-segment']\n const segmentQs = segmentToken ? `&segmentToken=${segmentToken}` : ''\n\n return (\n baseURL! +\n url! +\n stringify(params, { arrayFormat: 'repeat', addQueryPrefix: true }) +\n segmentQs\n )\n}\n\ninterface CategoryWithNulls\n extends Pick<\n Category,\n 'id' | 'name' | 'hasChildren' | 'MetaTagDescription' | 'Title'\n > {\n url: null\n children: null\n}\n\ninterface CatalogPageTypeResponse {\n id: string\n pageType: string\n name: string\n url: string\n title: string | null\n metaTagDescription: string | null\n}\n\n/** Catalog API\n * Docs: https://documenter.getpostman.com/view/845/catalogsystem-102/Hs44\n */\nexport class Catalog extends AppClient {\n private basePath: string\n constructor(ctx: IOContext, opts?: InstanceOptions) {\n super('vtex.catalog-api-proxy@0.x', ctx, opts)\n this.basePath = ctx.sessionToken\n ? '/proxy/authenticated/catalog'\n : '/proxy/catalog'\n }\n\n private removeSpecialCharacters = (str: string) => {\n return str.replace(/[%\"'.()+]/g, '')\n }\n\n public pageType = (path: string, query = '') => {\n const pageTypePath = path.startsWith('/') ? path.substr(1) : path\n\n const pageTypeQuery = !query || query.startsWith('?') ? query : `?${query}`\n\n return this.get<CatalogPageTypeResponse>(\n `/pub/portal/pagetype/${pageTypePath}${pageTypeQuery}`,\n { metric: 'catalog-pagetype' }\n )\n }\n\n public salesChannelAvailable = (email?: string) =>\n this.get<SalesChannelAvailable[]>(\n `/pub/saleschannel/available${\n // If we dont pass the email query string, it will return all open Trade Policies\n email ? `?email=${encodeURIComponent(email)}` : ''\n }`,\n {\n metric: 'catalog-sales-channel-available',\n }\n )\n\n public product = (slug: string) =>\n this.get<Product[]>(`/pub/products/search/${slug?.toLowerCase()}/p`, {\n metric: 'catalog-product',\n })\n\n public productByEan = (id: string) =>\n this.get<Product[]>(`/pub/products/search?fq=alternateIds_Ean:${id}`, {\n metric: 'catalog-productByEan',\n })\n\n public productsByEan = (ids: string[]) =>\n this.get<Product[]>(\n `/pub/products/search?${ids\n .map((id) => `fq=alternateIds_Ean:${id}`)\n .join('&')}`,\n { metric: 'catalog-productByEan' }\n )\n\n public productById = (id: string) =>\n this.get<Product[]>(`/pub/products/search?fq=productId:${id}`, {\n metric: 'catalog-productById',\n })\n\n public productsById = (ids: string[]) =>\n this.get<Product[]>(\n `/pub/products/search?${ids.map((id) => `fq=productId:${id}`).join('&')}`,\n { metric: 'catalog-productById' }\n )\n\n public productByReference = (id: string) =>\n this.get<Product[]>(`/pub/products/search?fq=alternateIds_RefId:${id}`, {\n metric: 'catalog-productByReference',\n })\n\n public productsByReference = (ids: string[]) =>\n this.get<Product[]>(\n `/pub/products/search?${ids\n .map((id) => `fq=alternateIds_RefId:${id}`)\n .join('&')}`,\n { metric: 'catalog-productByReference' }\n )\n\n public productBySku = (skuIds: string[]) =>\n this.get<Product[]>(\n `/pub/products/search?${skuIds\n .map((skuId) => `fq=skuId:${skuId}`)\n .join('&')}`,\n { metric: 'catalog-productBySku' }\n )\n\n public products = (args: SearchArgs, useRaw = false) => {\n const method = useRaw ? this.getRaw : this.get\n\n return method<Product[]>(this.productSearchUrl(args), {\n metric: 'catalog-products',\n })\n }\n\n public productsQuantity = async (args: SearchArgs) => {\n const {\n headers: { resources },\n } = await this.getRaw(this.productSearchUrl(args))\n\n const [, quantity] = resources.split('/')\n\n return parseInt(quantity, 10)\n }\n\n public brands = () =>\n this.get<Brand[]>('/pub/brand/list', { metric: 'catalog-brands' })\n\n public brand = (id: number) =>\n this.get<Brand[]>(`/pub/brand/${id}`, { metric: 'catalog-brands' })\n\n public categories = (treeLevel: number) =>\n this.get<Category[]>(`/pub/category/tree/${treeLevel}/`, {\n metric: 'catalog-categories',\n })\n\n public facets = (facets = '') => {\n const [path, options] = decodeURI(facets).split('?')\n\n return this.get(\n `/pub/facets/search/${encodeURI(\n `${this.removeSpecialCharacters(path.trim())}${\n options ? `?${options}` : ''\n }`\n )}`,\n { metric: 'catalog-facets' }\n )\n }\n\n public category = (id: string | number) =>\n this.get<CategoryWithNulls>(`/pub/category/${id}`, {\n metric: 'catalog-category',\n })\n\n public crossSelling = (id: string, type: CatalogCrossSellingTypes) =>\n this.get<Product[]>(`/pub/products/crossselling/${type}/${id}`, {\n metric: 'catalog-crossSelling',\n })\n\n public autocomplete = ({ maxRows, searchTerm }: AutocompleteArgs) =>\n this.get<{ itemsReturned: Item[] }>(\n `/buscaautocomplete?maxRows=${maxRows}&productNameContains=${encodeURIComponent(\n searchTerm\n )}`,\n { metric: 'catalog-autocomplete' }\n )\n\n private get = <T = any>(url: string, config: RequestConfig = {}) => {\n const segmentData: SegmentData | undefined = (this\n .context! as CustomIOContext).segment\n\n const { channel: salesChannel = '' } = segmentData ?? {}\n\n config.params = {\n ...config.params,\n ...(!!salesChannel && { sc: salesChannel }),\n }\n\n config.inflightKey = inflightKey\n\n return this.http.get<T>(`${this.basePath}${url}`, config)\n }\n\n private getRaw = <T = any>(url: string, config: RequestConfig = {}) => {\n const segmentData: SegmentData | undefined = (this\n .context! as CustomIOContext).segment\n\n const { channel: salesChannel = '' } = segmentData ?? {}\n\n config.params = {\n ...config.params,\n ...(!!salesChannel && { sc: salesChannel }),\n }\n\n config.inflightKey = inflightKey\n\n return this.http.getRaw<T>(`${this.basePath}${url}`, config)\n }\n\n private productSearchUrl = ({\n query = '',\n category = '',\n specificationFilters,\n priceRange = '',\n collection = '',\n salesChannel = '',\n orderBy = '',\n from = 0,\n to = 9,\n map = '',\n hideUnavailableItems = false,\n }: SearchArgs) => {\n const sanitizedQuery = encodeURIComponent(\n this.removeSpecialCharacters(decodeURIComponent(query ?? '').trim())\n )\n\n if (hideUnavailableItems) {\n const segmentData = (this.context as CustomIOContext).segment\n\n salesChannel = segmentData?.channel.toString() ?? ''\n }\n\n let url = `/pub/products/search/${sanitizedQuery}?`\n\n if (category && !query) {\n url += `&fq=C:/${category}/`\n }\n\n if (specificationFilters && specificationFilters.length > 0) {\n url = `${url}${specificationFilters.map((filter) => `&fq=${filter}`)}`\n }\n\n if (priceRange) {\n url += `&fq=P:[${priceRange}]`\n }\n\n if (collection) {\n url += `&fq=productClusterIds:${collection}`\n }\n\n if (salesChannel) {\n url += `&fq=isAvailablePerSalesChannel_${salesChannel}:1`\n }\n\n if (orderBy) {\n url += `&O=${orderBy}`\n }\n\n if (map) {\n url += `&map=${map}`\n }\n\n if (from != null && from > -1) {\n url += `&_from=${from}`\n }\n\n if (to != null && to > -1) {\n url += `&_to=${to}`\n }\n\n return url\n }\n}\n\n```" } ]
code_store-graphql_08d5bbfa
[ { "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/typings/Checkout.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface OrderFormMarketingData {\n utmCampaign?: string\n utmMedium?: string\n utmSource?: string\n utmiCampaign?: string\n utmiPart?: string\n utmipage?: string\n marketingTags?: string | string[]\n}\n\ninterface CheckoutAddress {\n addressType: string\n receiverName: string | null\n addressId: string\n postalCode: string\n city: string\n state: string\n country: string\n street: string\n number: string\n neighborhood: string\n complement: string\n reference: string | null\n geoCoordinates: [number, number]\n}\n\ninterface CheckoutAssemblyItem {\n id: string\n inputValues: Record<string, string>\n}\n\ninterface CheckoutAttachmentOffering {\n name: string\n required: boolean\n schema: Record<string, Record<string, unknown>>\n}\n\ninterface OrderFormItem {\n id: string\n name: string\n detailUrl: string\n imageUrl: string\n productRefId: string\n skuName: string\n quantity: number\n uniqueId: string\n productId: string\n refId: string\n ean: string\n priceValidUntil: string\n price: number\n tax: number\n listPrice: number\n sellingPrice: number\n rewardValue: number\n isGift: boolean\n parentItemIndex: number | null\n parentAssemblyBinding: string | null\n productCategoryIds: string\n priceTags: PriceTags[]\n measurementUnit: string\n additionalInfo: {\n brandName: string\n brandId: string\n offeringInfo: any | null\n offeringType: any | null\n offeringTypeId: any | null\n }\n productCategories: Record<string, string>\n seller: string\n sellerChain: string[]\n availability: string\n unitMultiplier: number\n assemblies: CheckoutAssemblyItem[]\n attachmentOfferings: CheckoutAttachmentOffering[]\n priceDefinition: {\n calculatedSellingPrice: number\n sellingPrices: SellingPrice[]\n total: number\n }\n}\n\ninterface SellingPrice {\n quantity: number\n value: number\n}\n\ninterface PriceTags {\n name: string\n value: number\n rawValue: number\n isPercentual: boolean\n identifier: string\n}\n\ninterface InstallmentOption {\n paymentSystem: string\n paymentName: string\n paymentGroupName: string\n value: number\n bin: string | null\n installments: SimulationInstallment[]\n}\n\ninterface SimulationInstallment {\n value: number\n interestRate: number\n total: number\n count: number\n}\n\ninterface PaymentSystem {\n id: number\n name: string\n groupName: string\n validator: Validator\n stringId: string\n template: string\n requiresDocument: boolean\n displayDocument: boolean\n isCustom: boolean\n description: string | null\n requiresAuthentication: boolean\n dueDate: string\n availablePayments: any\n}\n\ninterface Validator {\n regex: string\n mask: string\n cardCodeRegex: string\n cardCodeMask: string\n weights: number[]\n useCvv: boolean\n useExpirationDate: boolean\n useCardHolderName: boolean\n useBillingAddress: boolean\n}\n\ninterface OrderForm {\n orderFormId: string\n salesChannel: string\n loggedIn: boolean\n isCheckedIn: boolean\n storeId: string | null\n checkedInPickupPointId: string | null\n allowManualPrice: boolean\n canEditData: boolean\n userProfileId: string | null\n userType: string | null\n ignoreProfileData: boolean\n value: number\n messages: any[]\n items: OrderFormItem[]\n selectableGifts: any[]\n totalizers: Array<{ id: string; name: string; value: number }>\n shippingData: {\n address: CheckoutAddress\n logisticsInfo: LogisticsInfo[]\n selectedAddresses: CheckoutAddress[]\n availableAddresses: CheckoutAddress[]\n pickupPoints: Array<{\n friendlyName: string\n address: CheckoutAddress\n additionalInfo: string\n id: string\n businessHours: Array<{\n DayOfWeek: number\n OpeningTime: string\n ClosingTime: string\n }>\n }>\n }\n clientProfileData: any | null\n paymentData: PaymentData\n marketingData: OrderFormMarketingData | null\n sellers: Array<{\n id: string\n name: string\n logo: string\n }>\n clientPreferencesData: OrderFormClientPreferencesData\n commercialConditionData: any | null\n storePreferencesData: {\n countryCode: string\n saveUserData: boolean\n timeZone: string\n currencyCode: string\n currencyLocale: number\n currencySymbol: string\n currencyFormatInfo: {\n currencyDecimalDigits: number\n currencyDecimalSeparator: string\n currencyGroupSeparator: string\n currencyGroupSize: number\n startsWithCurrencySymbol: boolean\n }\n }\n giftRegistryData: any | null\n openTextField: any | null\n invoiceData: any | null\n customData: any | null\n itemMetadata: {\n items: MetadataItem[]\n }\n hooksData: any | null\n ratesAndBenefitsData: {\n rateAndBenefitsIdentifiers: any[]\n teaser: any[]\n }\n subscriptionData: any | null\n itemsOrdination: any | null\n}\n\ninterface OrderFormClientPreferencesData {\n locale: string\n optinNewsLetter: boolean | null\n}\n\ninterface OrderFormItemInput {\n id?: number\n index?: number\n quantity?: number\n seller?: string\n inputValues: Record<string, string>\n options?: AssemblyOptionInput[]\n}\n\ninterface AssemblyOptionInput {\n id: string\n quantity: number\n assemblyId: string\n seller: string\n inputValues: Record<string, string>\n options?: AssemblyOptionInput[]\n}\n\ninterface PayloadItem {\n id: string\n quantity: number\n seller: string\n parentItemIndex?: number | null\n parentAssemblyBinding?: string | null\n country?: string\n postalCode?: string\n}\n\ninterface SimulationPayload {\n country?: string\n items: PayloadItem[]\n postalCode?: string\n isCheckedIn?: boolean\n priceTables?: string[]\n marketingData?: Record<string, string>\n geoCoordinates?: [string | number, string | number]\n shippingData?: any\n}\n\ninterface SLAItem {\n id: string\n deliveryChannel: string\n name: string\n deliveryIds: Array<{\n courierId: string\n warehouseId: string\n dockId: string\n courierName: string\n quantity: number\n }>\n shippingEstimate: string\n shippingEstimateDate: string | null\n lockTTL: string | null\n availableDeliveryWindows: any[]\n deliveryWindow: string | null\n price: number\n listPrice: number\n tax: number\n pickupStoreInfo: {\n isPickupStore: boolean\n friendlyName: string | null\n address: CheckoutAddress | null\n additionalInfo: any | null\n dockId: string | null\n }\n pickupPointId: string | null\n pickupDistance: number\n polygonName: string | null\n}\n\ninterface LogisticsInfo {\n itemIndex: number\n selectedSla: string | null\n selectedDeliveryChannel: string | null\n addressId: string\n slas: SLAItem[]\n shipsTo: string[]\n itemId: string\n deliveryChannels: Array<{ id: string }>\n}\n\ninterface SimulationOrderForm extends OrderForm {\n logisticsInfo?: LogisticsInfo[]\n}\n\ninterface SLA {\n id: string\n deliveryChannel: string\n name: string\n deliveryIds: Array<{\n courierId: string\n warehouseId: string\n dockId: string\n courierName: string\n quantity: number\n }>\n shippingEstimate: string\n shippingEstimateDate: string | null\n lockTTL: string | null\n availableDeliveryWindows: any[]\n deliveryWindow: string | null\n price: number\n listPrice: number\n tax: number\n pickupStoreInfo: {\n isPickupStore: boolean\n friendlyName: string | null\n address: CheckoutAddress | null\n additionalInfo: any | null\n dockId: string | null\n }\n pickupPointId: string | null\n pickupDistance: number\n polygonName: string | null\n}\n\ninterface ItemWithSimulationInput {\n itemId: string\n sellers: Array<{\n sellerId: string\n }>\n}\n\ninterface Installment {\n count: number\n hasInterestRate: boolean\n interestRate: number\n value: number\n total: number\n sellerMerchantInstallments: Array<{\n id: string\n count: number\n hasInterestRate: boolean\n interestRate: number\n value: number\n total: number\n }>\n}\n\ninterface PaymentData {\n installmentOptions: InstallmentOption[]\n paymentSystems: PaymentSystem[]\n payments: any[]\n giftCards: any[]\n giftCardMessages: any[]\n availableAccounts: any[]\n availableTokens: any[]\n availableAssociations: any\n}\n\ninterface RatesAndBenefitsData {\n rateAndBenefitsIdentifiers: Array<{\n id: string\n name: string\n featured: boolean\n description: string\n additionalInfo?: {\n key: string\n value: string\n }\n }>\n teaser: Array<{\n featured: boolean\n id: string\n name: string\n generalValues: {\n key: string\n value: string\n }\n conditions: {\n parameters: Array<{\n name: string\n value: string\n }>\n minimumQuantity: number\n }\n effects: {\n parameters: Array<{\n name: string\n value: string\n }>\n }\n teaserType: string\n }>\n}\n\n```" } ]
code_store-graphql_198faa76
[ { "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/typings/ItemMetadata.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/**\n * Assembly options related types\n */\n\ninterface CompositionItem {\n id: string\n minQuantity: number\n maxQuantity: number\n initialQuantity: number\n priceTable: string\n seller: string\n}\n\ninterface Composition {\n minQuantity: number\n maxQuantity: number\n items: CompositionItem[]\n}\n\ninterface AssemblyOption {\n id: string\n name: string\n composition: Composition | null\n}\n\ninterface CatalogMetadataItem {\n Name: string\n NameComplete: string\n MainImage: string\n BrandName: string\n CategoryId: number\n ProductId: number\n id: string\n seller: string\n assemblyOptions: AssemblyOption[]\n}\n\ninterface MetadataItem {\n id: string\n name: string\n imageUrl: string\n detailUrl: string\n seller: string\n assemblyOptions: AssemblyOption[]\n skuName: string\n productId: string\n refId: string\n ean: string | null\n}\ninterface AddedItem {\n choiceType: string\n compositionItem: CompositionItem\n extraQuantity: number\n item: OrderFormItem\n normalizedQuantity: number\n}\n\ninterface RemovedItem {\n initialQuantity: number\n name: string\n removedQuantity: number\n}\n\n```" } ]
code_store-graphql_11c76ec5
[ { "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/typings/Session.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Session {\n id: string\n namespaces?: {\n profile: SessionProfile\n impersonate: SessionImpersonate\n authentication: SessionAuthentication\n public: SessionPublic\n }\n}\n\ninterface SessionProfile {\n id?: ObjValue\n email?: ObjValue\n firstName?: ObjValue\n lastName?: ObjValue\n phone?: ObjValue\n isAuthenticated?: ObjValue\n priceTables?: ObjValue\n}\n\ninterface SessionImpersonate {\n storeUserEmail?: ObjValue\n storeUserId?: ObjValue\n}\n\ninterface SessionAuthentication {\n [key: string]: string\n}\n\ninterface ObjValue {\n value: string\n}\n\ninterface SessionPublic {\n orderFormId?: ObjValue\n utm_source?: ObjValue\n utm_medium?: ObjValue\n utm_campaign?: ObjValue\n utm_term?: ObjValue\n utm_content?: ObjValue\n utmi_cp?: ObjValue\n utmi_pc?: ObjValue\n utmi_p?: ObjValue\n}\n\n```" } ]
code_store-graphql_0f439991
[ { "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/typings/Catalog.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface SearchArgs {\n query: string | null\n category: string | null\n specificationFilters: string[] | null\n priceRange: string | null\n collection: string | null\n salesChannel: string | null\n orderBy: string | null\n from: number | null\n to: number | null\n map: string | null\n hideUnavailableItems: boolean | null\n}\n\ninterface Metadata {\n metaTagDescription?: string\n titleTag?: string\n}\n\ninterface Brand {\n id: string\n name: string\n isActive: boolean\n title?: string\n metaTagDescription?: string\n}\n\ninterface Category {\n id: number\n name: string\n url: string\n hasChildren: boolean\n children: Category[]\n MetaTagDescription: string\n Title: string\n}\n\ninterface FacetsArgs {\n facets: string // deprecated!\n query: string\n map: string\n hideUnavailableItems: boolean\n}\n\ninterface Product {\n productId: string\n productName: string\n brand: string\n brandId: number\n linkText: string\n productReference: string\n categoryId: string\n productTitle: string\n metaTagDescription: string\n clusterHighlights: Record<string, string>\n productClusters: Record<string, string>\n searchableClusters: Record<string, string>\n categories: string[]\n categoriesIds: string[]\n link: string\n description: string\n items: Item[]\n itemMetadata: {\n items: CatalogMetadataItem[]\n }\n titleTag: string\n jsonSpecifications: string\n}\n\ninterface Item {\n itemId: string\n name: string\n nameComplete: string\n complementName: string\n ean: string\n referenceId: Array<{ Key: string; Value: string }>\n measurementUnit: string\n unitMultiplier: number\n modalType: any | null\n images: Array<{\n imageId: string\n imageLabel: string | null\n imageTag: string\n imageUrl: string\n imageText: string\n }>\n videos: Array<{\n videoUrl: string\n }>\n variations: string[]\n sellers: Seller[]\n}\n\ninterface Installment {\n Value: number\n InterestRate: number\n TotalValuePlusInterestRate: number\n NumberOfInstallments: number\n PaymentSystemName: string\n PaymentSystemGroupName: string\n Name: string\n}\n\n// TODO: It should be Commercial, but there are so many places with this typo that I prefer to keep\ninterface CommertialOffer {\n DeliverySlaSamplesPerRegion: Record<\n string,\n { DeliverySlaPerTypes: any[]; Region: any | null }\n >\n Installments: Installment[]\n DiscountHighLight: any[]\n GiftSkuIds: string[]\n Teasers: any[]\n BuyTogether: any[]\n ItemMetadataAttachment: any[]\n Price: number\n PriceWithPriceTags: number\n ListPrice: number\n PriceWithoutDiscount: number\n RewardValue: number\n PriceValidUntil: string\n AvailableQuantity: number\n Tax: number\n DeliverySlaSamples: Array<{\n DeliverySlaPerTypes: any[]\n Region: any | null\n }>\n GetInfoErrorMessage: any | null\n CacheVersionUsedToCallCheckout: string\n}\n\ninterface Seller {\n sellerId: string\n sellerName: string\n addToCartLink: string\n sellerDefault: boolean\n commertialOffer: CommertialOffer\n}\n\ninterface SalesChannelAvailable {\n Id: number\n Name: string\n IsActive: boolean\n ProductClusterId: string | null\n CountryCode: string\n CultureInfo: string\n TimeZone: string\n CurrencyCode: string\n CurrencySymbol: string\n CurrencyLocale: number\n CurrencyFormatInfo: unknown\n Position: number\n ConditionRule: string | null\n CurrencyDecimalDigits: null | number\n}\n\n```" } ]
code_store-graphql_17571a0a
[ { "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/utils/calculatePrice.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const calculatePrice = (\n unitMultiplier: number,\n sellingPrice: number,\n price: number\n) => {\n const minRange = (sellingPrice * 10 - 1) / (unitMultiplier * 10)\n const maxRange = (sellingPrice * 10 + 9) / (unitMultiplier * 10)\n\n const ceilMinRange = Math.ceil(minRange)\n\n // Check if the Price attends the rule for items without discount\n // Avoinding unnecessary calculation\n\n const realPriceFromPrice = price * unitMultiplier\n\n if (Math.trunc(realPriceFromPrice) === sellingPrice) {\n return price\n }\n\n // The real price must always be a number that, when multiplied by the multiplier unit,\n // must generate a value that, when truncated to two decimal places, results in the selling price\n // We try to find a value of two decimal places and if it is not possible, we pull the first value that meets\n\n const realPrice =\n ceilMinRange < maxRange &&\n ceilMinRange !== minRange &&\n ceilMinRange * unitMultiplier > sellingPrice\n ? ceilMinRange\n : Number(((minRange + maxRange) / 2).toFixed(1))\n\n return realPrice\n}\n\n```" } ]
code_store-graphql_d8d33cf4
[ { "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/utils/i18n.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n formatTranslatableStringV2,\n parseTranslatableStringV2,\n} from '@vtex/api'\n\nexport const formatTranslatableProp = <R, P extends keyof R, I extends keyof R>(\n prop: P,\n idProp: I\n) => (root: R, _: unknown, ctx: Context) =>\n addContextToTranslatableString(\n {\n content: (root[prop] as unknown) as string,\n context: (root[idProp] as unknown) as string,\n },\n ctx\n )\n\ninterface BaseMessage {\n content: string\n from?: string\n}\n\nexport interface Message extends BaseMessage {\n context?: string\n}\n\nexport const addContextToTranslatableString = (\n message: Message,\n ctx: Context\n) => {\n const {\n vtex: { tenant },\n } = ctx\n\n const { locale } = tenant!\n\n if (!message.content) {\n return message.content\n }\n\n const {\n content,\n context: originalContext,\n from: originalFrom,\n } = parseTranslatableStringV2(message.content)\n\n const context = (originalContext ?? message.context)?.toString()\n const from = originalFrom ?? message.from ?? locale\n\n return formatTranslatableStringV2({ content, context, from })\n}\n\n```" } ]
code_store-graphql_f360862f
[ { "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/utils/vtexId.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst vtexIdAccount = (account: string) => `VtexIdclientAutCookie_${account}`\nconst VTEX_ID = 'VtexIdclientAutCookie'\n\nexport const vtexIdCookies = (ctx: Context) => {\n const {\n cookies,\n vtex: { account },\n } = ctx\n\n const vtexIdAccountCookieValue = cookies.get(vtexIdAccount(account))\n const vtexIdValue = cookies.get(VTEX_ID)\n\n return {\n account: vtexIdAccountCookieValue\n ? `${vtexIdAccount(account)}=${vtexIdAccountCookieValue}`\n : null,\n id: vtexIdValue ? `${VTEX_ID}=${vtexIdValue}` : null,\n }\n}\n\n```" } ]
code_store-graphql_76293403
[ { "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/utils/cookie.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { parse } from 'set-cookie-parser'\nimport { SetOption } from 'cookies'\n\nconst isUserLoggedIn = (ctx: Context) => {\n const {\n vtex: { account },\n } = ctx\n\n return !!ctx.cookies.get(`VtexIdclientAutCookie_${account}`)\n}\n\nconst parseCookie = (cookie: string): ParsedCookie => {\n const [parsed] = parse(cookie)\n\n const cookieName = parsed.name\n const cookieValue = parsed.value\n\n const extraOptions = {\n path: parsed.path,\n domain: parsed.domain,\n expires: parsed.expires,\n httpOnly: true,\n secure: parsed.secure,\n sameSite: parsed.sameSite as 'strict' | 'lax' | undefined,\n }\n\n return {\n name: cookieName,\n value: cookieValue,\n options: extraOptions,\n }\n}\n\n/** Checkout cookie methods */\nconst CHECKOUT_COOKIE = 'checkout.vtex.com'\nconst ASPXAUTH_COOKIE = '.ASPXAUTH'\nconst OWNERSHIP_COOKIE = 'CheckoutOrderFormOwnership'\n\nconst checkoutCookieFormat = (orderFormId: string) =>\n `${CHECKOUT_COOKIE}=__ofid=${orderFormId};`\n\nexport function ownershipCookieFormat(ownerId: string) {\n return `${OWNERSHIP_COOKIE}=${ownerId};`\n}\n\nconst getOrderFormIdFromCookie = (cookies: Context['cookies']) => {\n const cookie = cookies.get(CHECKOUT_COOKIE)\n\n return cookie?.split('=')[1]\n}\n\nexport function getOwnerIdFromCookie(cookies: Context['cookies']) {\n return cookies.get(OWNERSHIP_COOKIE)\n}\n\nexport {\n isUserLoggedIn,\n CHECKOUT_COOKIE,\n ASPXAUTH_COOKIE,\n OWNERSHIP_COOKIE,\n checkoutCookieFormat,\n getOrderFormIdFromCookie,\n parseCookie,\n}\n\ninterface ParsedCookie {\n name: string\n value: string\n options: SetOption\n}\n\n```" } ]
code_store-graphql_e773387a
[ { "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/utils/object.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n adjust,\n curry,\n fromPairs,\n map,\n mergeAll,\n pipe,\n toPairs,\n zipObj,\n} from 'ramda'\n\n/**\n * Creates a new object with the own properties of the provided object, but the\n * keys renamed according to logic of renaming function.\n *\n * Keep in mind that in the case of keys conflict is behaviour undefined and\n * the result may vary between various JS engines!\n *\n * @func renameKeysWith\n * @category Object\n * @param {Function} func Function that renames the keys\n * @param {!Object} object Provided object\n * @return {!Object} New object with renamed keys\n * @see {@link https://github.com/ramda/ramda/wiki/Cookbook#rename-keys-of-an-object-by-a-function|Ramda Cookbook}\n * @example\n *\n * renameKeysWith(concat('a'), { A: 1, B: 2, C: 3 }) //=> { aA: 1, aB: 2, aC: 3 }\n */\ntype Tuple = [string, any]\nconst renameKeysWith = curry((func: any, object: any) =>\n pipe<any, Tuple[], any, any>(toPairs, map(adjust(0, func)), fromPairs)(object)\n)\n\n/*\n * Convert a list of fields like [ {key: 'propertyName', value: 'String'}, ... ]\n * to a JSON format.\n */\nconst parseFieldsToJson = (fields: any) =>\n mergeAll(fields.map((field: any) => zipObj([field.key], [field.value])))\n\nexport { renameKeysWith, parseFieldsToJson }\n\n```" } ]
code_store-graphql_c2e8a3fe
[ { "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/utils/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AxiosError } from 'axios'\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\n\nexport * from './object'\nexport * from './cookie'\n\nexport function generateRandomName() {\n return (1 + Math.random()).toString(36).substring(2)\n}\n\nexport function getFileExtension(fileName: string) {\n return fileName.match(/\\.[0-9a-z]+$/i)\n ? (fileName.match(/\\.[0-9a-z]+$/i) as any[])[0]\n : undefined\n}\n\nexport function statusToError(e: any) {\n if (!e.response) {\n throw e\n }\n\n const { response } = e as AxiosError\n const { status } = response!\n\n if (status === 401) {\n throw new AuthenticationError(e)\n }\n\n if (status === 403) {\n throw new ForbiddenError(e)\n }\n\n if (status === 400) {\n throw new UserInputError(e)\n }\n\n throw e\n}\n\n```" } ]
code_store-graphql_2d2cf6b5
[ { "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/utils/regionV1.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport function isRegionV1(regionId: string) {\n const regex = /v\\d+/\n\n return !regex.test(regionId)\n}\n\nexport function isUniqueSeller(regionId: string) {\n return !regionId.includes(';')\n}\n\n```" } ]
code_store-graphql_94145dff
[ { "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/utils/simulation.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { SegmentData } from '@vtex/api'\nimport atob from 'atob'\n\nimport { calculatePrice } from './calculatePrice'\nimport { isRegionV1, isUniqueSeller } from './regionV1'\n\nconst ALLOWED_TEASER_TYPES = ['Catalog', 'Profiler', 'ConditionalPrice']\n\nconst MARKETPLACE_SELLER_ID = '1'\n\nconst getMarketingData = (segment?: SegmentData) => {\n if (\n !segment?.utm_campaign &&\n !segment?.utm_source &&\n !segment?.utmi_campaign &&\n !segment?.campaigns\n ) {\n return\n }\n\n let marketingData = {}\n\n if (segment?.utm_campaign) {\n marketingData = {\n utmCampaign: segment?.utm_campaign,\n }\n }\n\n if (segment?.utm_source) {\n marketingData = {\n ...marketingData,\n utmSource: segment?.utm_source,\n }\n }\n\n if (segment?.utmi_campaign) {\n marketingData = {\n ...marketingData,\n utmiCampaign: segment?.utmi_campaign,\n }\n }\n\n if (segment?.campaigns) {\n marketingData = {\n ...marketingData,\n campaigns: [{ id: segment?.campaigns }],\n }\n }\n\n return marketingData\n}\n\nexport const getSimulationPayloadsByItem = (\n item: ItemWithSimulationInput,\n segment?: SegmentData,\n regionId?: string,\n useSellerFromRegion?: boolean,\n postalCode?: string,\n countryCode?: string\n) => {\n const payloadItems = item.sellers.map((seller) => {\n let sellerFromRegion = null\n\n if (\n useSellerFromRegion &&\n regionId &&\n seller.sellerId === MARKETPLACE_SELLER_ID\n ) {\n const regionV1 = isRegionV1(regionId)\n const sellerList = regionV1 ? atob(regionId) : null\n\n if (sellerList) {\n const uniqueSeller = isUniqueSeller(sellerList)\n\n sellerFromRegion = uniqueSeller ? sellerList.split('SW#')[1] : null\n }\n }\n\n const payLoad: PayloadItem = {\n id: item.itemId,\n quantity: 1,\n seller: sellerFromRegion || seller.sellerId,\n }\n\n if (countryCode && postalCode) {\n payLoad.country = countryCode\n payLoad.postalCode = postalCode\n }\n\n return payLoad\n })\n\n return payloadItems.map((payloadItem) => {\n return {\n priceTables: segment?.priceTables ? [segment.priceTables] : undefined,\n items: [payloadItem],\n shippingData: {\n logisticsInfo: [{ regionId: regionId ?? segment?.regionId }],\n },\n marketingData: getMarketingData(segment),\n }\n })\n}\n\nexport const orderFormItemToSeller = (\n orderFormItem: OrderFormItem & {\n paymentData: PaymentData\n ratesAndBenefitsData: RatesAndBenefitsData\n logisticsInfo: any[]\n }\n) => {\n const unitMultiplier = orderFormItem.unitMultiplier ?? 1\n\n const [logisticsInfo] = orderFormItem.logisticsInfo\n\n const sellingPrice =\n orderFormItem.priceDefinition?.calculatedSellingPrice ??\n orderFormItem.sellingPrice\n\n const { price } = orderFormItem\n\n const haveUnitMultiplier = unitMultiplier !== 1\n\n const realPrice = haveUnitMultiplier\n ? calculatePrice(unitMultiplier, sellingPrice, price)\n : sellingPrice\n\n const commertialOffer = {\n Price: Number((realPrice / 100).toFixed(3)),\n PriceValidUntil: orderFormItem.priceValidUntil,\n ListPrice: orderFormItem.listPrice / 100,\n PriceWithoutDiscount: price / 100,\n Tax: orderFormItem.tax / 100,\n AvailableQuantity:\n orderFormItem?.availability === 'available' &&\n (logisticsInfo ? logisticsInfo.stockBalance : 1)\n ? 10000\n : 0,\n Teasers: getTeasers(orderFormItem.ratesAndBenefitsData),\n DiscountHighLight: getDiscountHighLights(\n orderFormItem.ratesAndBenefitsData\n ),\n } as CommertialOffer\n\n const installmentOptions =\n orderFormItem?.paymentData?.installmentOptions || []\n\n commertialOffer.Installments = []\n\n installmentOptions.forEach((installmentOption: InstallmentOption) =>\n installmentOption.installments.forEach((installment) => {\n commertialOffer.Installments.push({\n Value: installment.value / 100,\n InterestRate: installment.interestRate / 100,\n TotalValuePlusInterestRate: installment.total / 100,\n NumberOfInstallments: installment.count,\n PaymentSystemName: installmentOption.paymentName,\n PaymentSystemGroupName: installmentOption.paymentGroupName,\n Name: generatePaymentName(\n installment.interestRate,\n installmentOption.paymentName,\n installment.count\n ),\n } as Installment)\n })\n )\n\n return {\n sellerId: orderFormItem.seller,\n commertialOffer,\n }\n}\n\nconst getTeasers = (ratesAndBenefitsData: RatesAndBenefitsData) => {\n if (!ratesAndBenefitsData) {\n return []\n }\n\n return ratesAndBenefitsData.teaser\n .filter((teaser: any) => ALLOWED_TEASER_TYPES.includes(teaser.teaserType))\n .map((teaser: any) => ({\n '<Name>k__BackingField': teaser.name,\n ...teaser,\n generalValues: Object.keys(teaser.generalValues).map(\n (objectKey: string) => ({\n key: objectKey,\n value: teaser.generalValues[objectKey],\n })\n ),\n }))\n}\n\nconst getDiscountHighLights = (ratesAndBenefitsData: RatesAndBenefitsData) => {\n if (!ratesAndBenefitsData) {\n return []\n }\n\n return ratesAndBenefitsData.rateAndBenefitsIdentifiers\n .filter(\n (rateAndBenefitsIdentifier: any) => rateAndBenefitsIdentifier.featured\n )\n .map((rateAndBenefitsIdentifier: any) => ({\n '<Name>k__BackingField': rateAndBenefitsIdentifier.name,\n ...rateAndBenefitsIdentifier,\n additionalInfo: Object.keys(\n rateAndBenefitsIdentifier.additionalInfo ?? {}\n ).map((objectKey: string) => ({\n key: objectKey,\n value: rateAndBenefitsIdentifier.additionalInfo[objectKey],\n })),\n }))\n}\n\nconst generatePaymentName = (\n interestRate: number | null,\n paymentSystemName: string | null,\n numberOfInstallments: number\n) => {\n if (interestRate === null) {\n return paymentSystemName\n }\n\n if (interestRate === 0) {\n return `${paymentSystemName} ${\n numberOfInstallments === 1\n ? 'à vista'\n : `${numberOfInstallments} vezes sem juros`\n }`\n }\n\n return `${paymentSystemName} ${\n numberOfInstallments === 1\n ? 'à vista com juros'\n : `${numberOfInstallments} vezes com juros`\n }`\n}\n\n```" } ]
code_store-graphql_5e6fc832
[ { "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/headers.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\nimport cookies from 'cookie'\n\nconst DEFAULT_PAGE_SIZE = 15\n\nexport const headers = {\n json: {\n accept: 'application/json',\n 'content-type': 'application/json',\n },\n}\n\nexport const withAuthToken = (currentHeaders = {}) => (\n ioContext: any,\n cookie = null\n) => {\n const ans: any = { ...currentHeaders }\n\n if (cookie) {\n const parsedCookie = cookies.parse(cookie!)\n\n if (parsedCookie.VtexIdclientAutCookie) {\n ans.VtexIdclientAutCookie = parsedCookie.VtexIdclientAutCookie\n }\n }\n\n return {\n ...ans,\n Authorization: `${ioContext.authToken}`,\n 'Proxy-Authorization': `${ioContext.authToken}`,\n }\n}\n\nexport const withAuthAsVTEXID = (currentHeaders = {}) => (ioContext: any) => {\n return {\n ...currentHeaders,\n 'Proxy-Authorization': ioContext.authToken,\n VtexIdclientAutCookie: ioContext.authToken,\n }\n}\n\nexport const withMDPagination = (currentHeaders = {}) => (\n ioContext: any,\n cookie = null\n) => (page = 1, pageSize = DEFAULT_PAGE_SIZE) => {\n if (page < 1) {\n throw new UserInputError('Smallest page value is 1')\n }\n\n const startIndex = (page - 1) * pageSize\n const endIndex = startIndex + pageSize\n\n return {\n ...withAuthToken(currentHeaders)(ioContext, cookie),\n 'REST-Range': `resources=${startIndex}-${endIndex}`,\n }\n}\n\n```" } ]
code_store-graphql_16b9fdcc
[ { "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/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { mutations as authMutations, queries as authQueries } from './auth'\nimport {\n fieldResolvers as benefitsFieldResolvers,\n queries as benefitsQueries,\n} from './benefits'\nimport {\n fieldResolvers as catalogFieldResolvers,\n queries as catalogQueries,\n} from './catalog'\nimport {\n fieldResolvers as checkoutFieldResolvers,\n mutations as checkoutMutations,\n queries as checkoutQueries,\n} from './checkout'\nimport {\n fieldResolvers as documentFieldResolvers,\n mutations as documentMutations,\n queries as documentQueries,\n} from './document'\nimport { mutation as listMutations, queries as listQueries } from './list'\nimport {\n fieldResolvers as logisticsResolvers,\n queries as logisticsQueries,\n} from './logistics'\nimport {\n queries as omsQueries,\n fieldResolvers as omsFieldResolvers,\n} from './oms'\nimport {\n fieldResolvers as profileFieldResolvers,\n mutations as profileMutations,\n queries as profileQueries,\n} from './profile'\nimport { resolvers as portalResolvers } from './portal'\nimport {\n mutations as sessionMutations,\n queries as sessionQueries,\n fieldResolvers as sessionResolvers,\n} from './session'\n\nexport const resolvers = {\n ...catalogFieldResolvers,\n ...benefitsFieldResolvers,\n ...profileFieldResolvers,\n ...checkoutFieldResolvers,\n ...documentFieldResolvers,\n ...logisticsResolvers,\n ...omsFieldResolvers,\n ...sessionResolvers,\n Mutation: {\n ...profileMutations,\n ...checkoutMutations,\n ...authMutations,\n ...documentMutations,\n ...sessionMutations,\n ...listMutations,\n },\n Query: {\n ...catalogQueries,\n ...benefitsQueries,\n ...profileQueries,\n ...checkoutQueries,\n ...documentQueries,\n ...authQueries,\n ...logisticsQueries,\n ...sessionQueries,\n ...listQueries,\n ...omsQueries,\n ...portalResolvers,\n },\n}\n\n```" } ]
code_store-graphql_98010124
[ { "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/paths.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { join } from 'ramda'\n\nconst paths = {\n /** Checkout API\n * Docs: https://documenter.getpostman.com/view/18468/vtex-checkout-api/6Z2QYJM\n */\n addItem: (account: any, { orderFormId }: any) =>\n `${paths.orderForm(account)}/${orderFormId}/items`,\n changeToAnonymousUser: (account: any, { orderFormId }: any) =>\n `http://${account}.vtexcommercestable.com.br/checkout/changeToAnonymousUser/${orderFormId}`,\n orderForm: (account: any) =>\n `http://${account}.vtexcommercestable.com.br/api/checkout/pub/orderForm`,\n orderFormCustomData: (account: any, { orderFormId, appId, field }: any) =>\n `${paths.orderForm(account)}/${orderFormId}/customData/${appId}/${field}`,\n orderFormIgnoreProfile: (account: any, { orderFormId }: any) =>\n `${paths.orderForm(account)}/${orderFormId}/profile`,\n orderFormPayment: (account: any, { orderFormId }: any) =>\n `${paths.orderForm(account)}/${orderFormId}/attachments/paymentData`,\n orderFormPaymentToken: (account: any, { orderFormId }: any) =>\n `${paths.orderForm(account)}/${orderFormId}/paymentData/paymentToken`,\n orderFormPaymentTokenId: (account: any, { orderFormId, tokenId }: any) =>\n `${paths.orderForm(\n account\n )}/${orderFormId}/paymentData/paymentToken/${tokenId}`,\n orderFormProfile: (account: any, { orderFormId }: any) =>\n `${paths.orderForm(account)}/${orderFormId}/attachments/clientProfileData`,\n orderFormShipping: (account: any, { orderFormId }: any) =>\n `${paths.orderForm(account)}/${orderFormId}/attachments/shippingData`,\n orderFormSimulation: (account: any, { querystring }: any) =>\n `http://${account}.vtexcommercestable.com.br/api/checkout/pvt/orderForms/simulation?${querystring}`,\n shipping: (account: any) =>\n `http://${account}.vtexcommercestable.com.br/api/checkout/pub/orderForms/simulation`,\n updateItems: (account: any, data: any) =>\n `${paths.addItem(account, data)}/update`,\n\n cancelOrder: (account: any, { orderFormId }: any) =>\n `${paths.orders(account)}/${orderFormId}/user-cancel-request`,\n orders: (account: any) =>\n `http://${account}.vtexcommercestable.com.br/api/checkout/pub/orders`,\n\n /** PCI Gateway API\n * Docs: https://documenter.getpostman.com/view/322855/pci/Hs3y#intro\n */\n gateway: (account: any) => `http://${account}.vtexpayments.com.br/api`,\n gatewayPaymentSession: (account: any) =>\n `${paths.gateway(account)}/pvt/sessions`,\n gatewayTokenizePayment: (account: any, { sessionId }: any) =>\n `${paths.gateway(account)}/pub/sessions/${sessionId}/tokens`,\n\n /** VTEX ID API */\n accessKeySignIn: () => `${paths.vtexIdPub}/authentication/accesskey/validate`,\n classicSignIn: () => `${paths.vtexIdPub}/authentication/classic/validate`,\n getUser: (accountName: any) =>\n `${paths.vtexIdPvt}/user/detailedinfo?scope=${accountName}`,\n oAuth: (authenticationToken: any, providerName: any) =>\n `${paths.vtexIdPub}/authentication/oauth/redirect?authenticationToken=${authenticationToken}&providerName=${providerName}`,\n setPassword: () => `${paths.vtexIdPub}/authentication/classic/setpassword`,\n sendEmailVerification: () =>\n `${paths.vtexIdPub}/authentication/accesskey/send`,\n sessionToken: (scope: any, account: any, redirect = '/', returnUrl = '/') =>\n `${\n paths.vtexIdPub\n }/authentication/start?appStart=true&scope=${scope}&accountName=${account}${\n redirect && `&callbackUrl=${redirect}`\n }${returnUrl && `&returnUrl=${returnUrl}`}`,\n loginSessions: (scope: string, account: string) =>\n `${paths.vtexId}/sessions?scope=${scope}&an=${account}`,\n logOutFromSession: ({\n scope,\n account,\n sessionId,\n }: {\n scope: string\n account: string\n sessionId: string\n }) =>\n `${paths.vtexId}/sessions/${sessionId}/revoke?scope=${scope}&an=${account}`,\n vtexId: `http://vtexid.vtex.com.br/api/vtexid`,\n vtexIdPub: `http://vtexid.vtex.com.br/api/vtexid/pub`,\n vtexIdPvt: `http://vtexid.vtex.com.br/api/vtexid/pvt`,\n\n /** Sessions API */\n /**\n * The path session can initialize Session, impersonate and depersonify\n * an user according to the body data that is passed to it.\n */\n getSession: (account: any) => `${paths.session(account)}?items=*`,\n session: (account: any) =>\n `http://${account}.vtexcommercestable.com.br/api/sessions`,\n\n /** Master Data API v1\n * Docs: https://documenter.getpostman.com/view/164907/masterdata-api-v102/2TqWsD\n */\n profile: (account: any) => ({\n address: (id: any) =>\n `http://api.vtex.com/${account}/dataentities/AD/documents/${id}`,\n attachments: (id: any, field: any) =>\n `http://api.vtex.com/${account}/dataentities/CL/documents/${id}/${field}/attachments`,\n filterAddress: (id: any) =>\n `http://api.vtex.com/${account}/dataentities/AD/search?userId=${id}&_fields=userId,id,receiverName,complement,neighborhood,country,state,number,street,postalCode,city,reference,addressName,addressType,geoCoordinate`,\n filterUser: (email: any, customFields?: any) =>\n join(',', [\n `http://api.vtex.com/${account}/dataentities/CL/search?email=${email}&_fields=userId,id,firstName,lastName,birthDate,gender,homePhone,businessPhone,document,email,isCorporate,tradeName,corporateName,stateRegistration,corporateDocument,profilePicture`,\n customFields,\n ]),\n payments: (id: any) =>\n `http://${account}.vtexcommercestable.com.br/api/profile-system/pvt/profiles/${id}/vcs-checkout`,\n profile: (id: any) =>\n `http://api.vtex.com/${account}/dataentities/CL/documents/${id}`,\n }),\n\n // https://documenter.getpostman.com/view/3848/vtex-logistics-api/Hs42#405fae80-9bbc-471b-92b5-3071bdbfa527\n logisticsConfig: (account: string) => ({\n pickupById: (id: string) =>\n `http://logistics.vtexcommercestable.com.br/api/logistics/pvt/configuration/pickuppoints/${id}?an=${account}`,\n pickupPoints: (lat: string, long: string, maxDistance: number) =>\n `http://logistics.vtexcommercestable.com.br/api/logistics/pvt/configuration/pickuppoints/_search?an=${account}&page=1&pageSize=100&lat=${lat}&$lon=${long}&maxDistance=${maxDistance}`,\n shipping: `http://${account}.vtexcommercestable.com.br/api/logistics/pub/shipping/configuration`,\n }),\n\n /** Catalog API\n * Docs: https://documenter.getpostman.com/view/845/vtex-catalog-api/Hs44#dc127f25-fc71-8188-1de3-0d2dff8fed11\n */\n skuById: (account: any) =>\n `http://${account}.vtexcommercestable.com.br/api/catalog_system/pvt/sku/stockkeepingunitbyid/`,\n}\n\nexport default paths\n\n```" } ]
code_store-graphql_425210e8
[ { "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/httpResolver.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOContext } from '@vtex/api'\nimport axios, { Method } from 'axios'\nimport { prop } from 'ramda'\nimport parse from 'url-parse'\n\nconst defaultMerge = (_: any, resData: any, __: any) => resData\n\nexport type URLBuilder = (account: string, data: any, root: any) => string\n\nexport type DataBuilder = (data: any) => any\n\nexport type HeadersBuider = (ioContext: IOContext) => Record<string, string>\n\nexport type ResponseMerger = (\n bodyData: any,\n responseData: any,\n response?: any\n) => any\n\nexport interface HttpResolverOptions {\n method?: Method\n url: string | URLBuilder\n data?: any | DataBuilder\n headers?: Record<string, string> | HeadersBuider\n enableCookies?: boolean\n secure?: boolean\n merge?: ResponseMerger\n}\n\nexport type HttpResolver<T> = (\n root: any,\n args: any,\n context: Context\n) => Promise<T>\n\nexport default <T = any>(options: HttpResolverOptions): HttpResolver<T> => {\n return async (\n root,\n args,\n {\n vtex: ioContext,\n request: {\n headers: { cookie, 'x-forwarded-host': host },\n },\n response,\n }: Context\n ) => {\n const {\n secure = false,\n url,\n enableCookies,\n data,\n method = 'GET',\n headers = {},\n merge = defaultMerge,\n } = options\n\n const builtUrl =\n typeof url === 'function' ? url(ioContext.account, args, root) : url\n\n const builtData = typeof data === 'function' ? data(args) : data\n const builtHeaders =\n typeof headers === 'function' ? await headers(ioContext) : headers\n\n const config = {\n method,\n url: builtUrl,\n data: builtData,\n headers: builtHeaders,\n }\n\n if (enableCookies && cookie) {\n config.headers.cookie = cookie\n config.headers.host = host\n }\n\n const { hostname } = parse(builtUrl)\n\n if (secure) {\n config.headers['X-Vtex-Proxy-To'] = `https://${hostname}`\n } else if (enableCookies && cookie) {\n config.headers['X-Vtex-Proxy-To'] = `http://${hostname}`\n }\n\n const vtexResponse = await axios.request(config)\n\n if (enableCookies) {\n const setCookie = prop('set-cookie', vtexResponse.headers)\n\n if (setCookie) {\n response.set('Set-Cookie', setCookie)\n }\n }\n\n return merge(args, vtexResponse.data, vtexResponse)\n }\n}\n\n```" } ]
code_store-graphql_b50741d3
[ { "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/routes/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/ban-ts-comment */\n/*\n Disabling because `status` and `body` are not defined in the `Context` type provided by VTEX.\n However, they are dynamically added by the middleware in the runtime, and using them works as expected.\n*/\nexport async function getEmailRetificationConfig(\n ctx: Context,\n next: () => Promise<any>\n) {\n try {\n const { storeUserAuthToken } = ctx.vtex\n const { account } = decodeToken(storeUserAuthToken ?? '')\n\n if (account !== ctx.vtex.account) {\n setForbiddenStatus(ctx)\n\n return\n }\n } catch (e) {\n setForbiddenStatus(ctx)\n\n return\n }\n\n // @ts-ignore\n ctx.status = 200\n // @ts-ignore\n ctx.body = await ctx.clients.oms.getEmailRetificationConfig()\n\n await next()\n}\n\nfunction decodeToken(token: string) {\n if (!token || !token.includes('.')) {\n throw new Error('Invalid token')\n }\n\n const [, encodedPayload] = token.split('.')\n const payload = Buffer.from(encodedPayload, 'base64').toString()\n\n return JSON.parse(payload)\n}\n\nfunction setForbiddenStatus(ctx: Context) {\n // @ts-ignore\n ctx.status = 403\n // @ts-ignore\n ctx.body = 'Forbidden'\n}\n\n```" } ]
code_store-graphql_01c38080
[ { "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/clients/profile/profileV2.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n JanusClient,\n RequestConfig,\n} from '@vtex/api'\n\nimport { statusToError } from '../../utils'\n\nconst FIVE_SECONDS_MS = 5 * 1000\n\nexport class ProfileClientV2 extends JanusClient {\n protected account: string\n private defaultPIIRequest: PIIRequest\n\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n ...options?.headers,\n VtexIdClientAutCookie: context.authToken ?? '',\n },\n timeout: FIVE_SECONDS_MS,\n params: { an: context.account },\n })\n\n this.account = context.account\n\n this.defaultPIIRequest = {\n useCase: 'MyAcocunts',\n onBehalfOf: 'user',\n } as PIIRequest\n }\n\n public getProfileInfo = (\n user: CurrentProfile,\n customFields?: string,\n piiRequest?: PIIRequest\n ) => {\n const { userKey, alternativeKey } = this.getUserKeyAndAlternateKey(user)\n const url = this.getPIIUrl(\n `${this.baseUrl}/${userKey}`,\n alternativeKey,\n piiRequest\n )\n\n return this.get<ProfileV2>(url, {\n metric: 'profile-system-v2-getProfileInfo',\n params: {\n extraFields: customFields,\n },\n })\n .then((profile: ProfileV2[]) => {\n if (profile.length > 0) {\n const profileV2 = {\n ...profile[0].document,\n pii: true,\n id: profile[0].id,\n }\n\n return profileV2\n }\n\n return {} as Profile\n })\n .then((profile: Profile) => this.fillWithPreferences(profile, piiRequest))\n }\n\n private fillWithPreferences = (profile: Profile, piiRequest?: PIIRequest) => {\n return this.getPurchaseInfo(profile, piiRequest)\n .then((purchaseInfoList: PurchaseInfo[]) => {\n const [purchaseInfo] = purchaseInfoList\n\n profile.isNewsletterOptIn =\n purchaseInfo.document.clientPreferences?.isNewsletterOptIn ?? false\n\n return profile\n })\n .catch(() => {\n profile.isNewsletterOptIn = false\n\n return profile\n })\n }\n\n private getPurchaseInfo = (profile: Profile, piiRequest?: PIIRequest) => {\n const url = this.getPIIUrl(\n `${this.baseUrl}/${profile.id}/purchase-info`,\n undefined,\n piiRequest\n )\n\n return this.get<PurchaseInfo>(url, {\n metric: 'profile-system-v2-getUserPreferences',\n }).catch<any>((e) => {\n const { status } = e.response ?? {}\n\n if (status === 404) {\n return [] as PurchaseInfo[]\n }\n\n return statusToError(e)\n })\n }\n\n public createProfile = (profile: Profile) =>\n this.post<ProfileV2>(`${this.baseUrl}`, profile).then(\n (profileV2: ProfileV2) => {\n return {\n ...(profileV2.document as Profile),\n id: profileV2.id,\n }\n }\n )\n\n public updatePersonalPreferences = (\n _: CurrentProfile,\n personalPreferences: PersonalPreferences,\n currentUserProfile: Profile\n ) => {\n const parsedPersonalPreferences = Object.fromEntries(\n Object.entries(personalPreferences).map(([key, value]) => {\n return [key, value === 'True']\n })\n )\n\n const purchaseInfo = {\n clientPreferences: {\n ...parsedPersonalPreferences,\n },\n }\n\n return this.put(\n `${this.baseUrl}/${currentUserProfile.id}/purchase-info`,\n purchaseInfo,\n {\n metric: 'profile-system-v2-subscribeNewsletter',\n }\n )\n }\n\n public updateProfileInfo = (\n user: CurrentProfile,\n profile: Profile | { profilePicture: string },\n customFields?: string\n ) => {\n const { userKey, alternativeKey } = this.getUserKeyAndAlternateKey(user)\n\n return this.patch(\n `${this.baseUrl}/${userKey}?alternativeKey=${alternativeKey}`,\n profile,\n {\n metric: 'profile-system-v2-updateProfileInfo',\n params: {\n extraFields: customFields,\n },\n }\n )\n }\n\n public getUserAddresses = (\n _: CurrentProfile,\n currentUserProfile: Profile,\n piiRequest?: PIIRequest\n ) => {\n const url = this.getPIIUrl(\n `${this.baseUrl}/${currentUserProfile.id}/addresses`,\n undefined,\n piiRequest\n )\n\n return this.get<Address[]>(url, {\n metric: 'profile-system-v2-getUserAddresses',\n })\n .then((addresses: AddressV2[]) => this.translateToV1Address(addresses))\n .catch<any>((e) => {\n const { status } = e.response ?? {}\n\n if (status === 404) {\n return [] as AddressV2[]\n }\n\n return statusToError(e)\n })\n }\n\n private translateToV1Address = (addresses: AddressV2[]) =>\n addresses.map((address: AddressV2) => {\n const addressV2 = address.document\n\n return {\n addressName: addressV2.addressName ?? addressV2.name,\n name: addressV2.name ?? addressV2.addressName ?? '',\n city: addressV2.locality,\n complement: addressV2.complement,\n country: addressV2.countryCode,\n geoCoordinates: addressV2.geoCoordinates ?? [],\n id: address.id,\n number: addressV2.streetNumber,\n postalCode: addressV2.postalCode,\n receiverName: addressV2.receiverName,\n reference: addressV2.nearly,\n state: addressV2.administrativeAreaLevel1 ?? '',\n street: addressV2.route,\n userId: addressV2.profileId,\n addressType: addressV2.addressType ?? 'residential',\n neighborhood: addressV2.localityAreaLevel1 ?? '',\n } as Address\n })\n\n private translateToV2Address = (addresses: Address[]) =>\n addresses.map((address: Address) => {\n return {\n id: address.id,\n document: {\n administrativeAreaLevel1: address.state ?? '',\n addressName: address.addressName ?? address.id,\n addressType: address.addressType ?? 'residential',\n countryCode: address.country,\n complement: address.complement ?? '',\n geoCoordinates: address.geoCoordinates ?? [],\n locality: address.city,\n localityAreaLevel1: address.neighborhood ?? '',\n name: (address.name ?? address.addressName) || '',\n nearly: address.reference ?? '',\n postalCode: address.postalCode,\n profileId: address.userId,\n route: address.street,\n streetNumber: address.number ?? '',\n receiverName: address.receiverName,\n userId: address.userId,\n },\n } as AddressV2\n })\n\n private mapAddressesObjToList(addressesObj: any): Address[] {\n return Object.entries<string>(addressesObj).map(([key, stringifiedObj]) => {\n try {\n const address = JSON.parse(stringifiedObj) as Address\n\n address.id = key\n\n return address\n } catch (e) {\n return {} as Address\n }\n })\n }\n\n public updateAddress = (user: CurrentProfile, addressesData: any) => {\n const addressesV1 = this.mapAddressesObjToList(addressesData).map(\n (addr: any) => {\n addr.geoCoordinates = addr.geoCoordinate\n\n return addr\n }\n )\n\n const addressesV2 = this.translateToV2Address(addressesV1)\n const [toChange] = addressesV2.filter(\n (addr) => addr.id === addressesV1[0].id\n )\n\n return this.getProfileInfo(user).then((profile) => {\n return this.getUserAddresses(user, profile).then(\n (addresses: Address[]) => {\n const [address] = addresses.filter(\n (addr) => addr.addressName === addressesV1[0].id\n )\n\n if (address) {\n return this.patch(\n `${this.baseUrl}/${profile.id}/addresses/${address.id}`,\n toChange.document,\n {\n metric: 'profile-system-v2-updateAddress',\n }\n )\n }\n\n return this.post(\n `${this.baseUrl}/${profile.id}/addresses`,\n toChange.document,\n {\n metric: 'profile-system-v2-createAddress',\n }\n )\n }\n )\n })\n }\n\n public deleteAddress = (user: CurrentProfile, addressName: string) => {\n return this.getProfileInfo(user).then((profile) => {\n this.getUserAddresses(user, profile).then((addresses: Address[]) => {\n const [address] = addresses.filter(\n (addr) => addr.addressName === addressName\n )\n\n return this.delete(\n `${this.baseUrl}/${profile.id}/addresses/${address.id}`,\n {\n metric: 'profile-system-v2-deleteAddress',\n }\n )\n })\n })\n }\n\n public getUserPayments = (user: CurrentProfile, piiRequest?: PIIRequest) => {\n const url = this.getPIIUrl(\n `${this.baseUrl}/${user.userId}/purchase-info`,\n undefined,\n piiRequest\n )\n return this.get(url, {\n metric: 'profile-system-v2-getUserPayments',\n }).catch<any>((e) => {\n const { status } = e.response ?? {}\n\n if (status === 404) {\n return [] as PaymentProfile[]\n }\n\n return statusToError(e)\n })\n }\n\n protected get = <T>(url: string, config?: RequestConfig) =>\n this.http.get<T>(url, config).catch<any>(statusToError)\n\n protected post = <T>(url: string, data?: any, config?: RequestConfig) =>\n this.http.post<T>(url, data, config).catch<any>(statusToError)\n\n protected delete = <T>(url: string, config?: RequestConfig) =>\n this.http.delete<T>(url, config).catch<any>(statusToError)\n\n protected patch = <T>(url: string, data?: any, config?: RequestConfig) =>\n this.http.patch<T>(url, data, config).catch<any>(statusToError)\n\n protected put = <T>(url: string, data?: any, config?: RequestConfig) =>\n this.http.put<T>(url, data, config).catch<any>(statusToError)\n\n private baseUrl = 'api/storage/profile-system/profiles'\n\n private getUserKeyAndAlternateKey(user: CurrentProfile) {\n let alternativeKey\n let userKey\n\n if (user.email) {\n alternativeKey = 'email'\n userKey = user.email\n } else {\n userKey = user.userId\n }\n\n return {\n userKey,\n alternativeKey,\n }\n }\n\n private getPIIUrl(\n url: string,\n alternativeKey?: string,\n piiRequest?: PIIRequest\n ) {\n const params = []\n\n if (alternativeKey) {\n params.push(['alternativeKey', alternativeKey])\n }\n\n const currentPIIRequest = piiRequest ?? this.defaultPIIRequest\n\n if (currentPIIRequest) {\n params.push(\n ['useCase', currentPIIRequest.useCase],\n ['onBehalfOf', currentPIIRequest.onBehalfOf]\n )\n\n url += '/unmask'\n }\n\n const queryString = params.map((el) => el.join('=')).join('&')\n\n return `${url}?${queryString}`\n }\n}\n\n```" } ]
code_store-graphql_fe87e633
[ { "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/clients/profile/profileV1.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n JanusClient,\n RequestConfig,\n} from '@vtex/api'\n\nimport { statusToError } from '../../utils'\n\nconst FIVE_SECONDS_MS = 5 * 1000\n\nfunction mapAddressesObjToList(addressesObj: any): Address[] {\n return Object.values<string>(addressesObj).map(\n (stringifiedObj) => JSON.parse(stringifiedObj) as Address\n )\n}\n\nexport class ProfileClientV1 extends JanusClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n ...options?.headers,\n VtexIdClientAutCookie: context.authToken ?? '',\n },\n timeout: FIVE_SECONDS_MS,\n })\n }\n\n public getProfileInfo = (user: CurrentProfile, customFields?: string) =>\n this.get<Profile>(\n `${this.baseUrl}/${getUserIdentification(user)}/personalData`,\n {\n metric: 'profile-system-getProfileInfo',\n params: {\n extraFields: customFields,\n },\n }\n ).then((profile) => {\n profile.pii = false\n\n return profile\n })\n\n public getUserAddresses = (user: CurrentProfile, _: Profile) =>\n this.get(`${this.baseUrl}/${getUserIdentification(user)}/addresses`, {\n metric: 'profile-system-getUserAddresses',\n }).then(mapAddressesObjToList)\n\n public getUserPayments = (user: CurrentProfile) =>\n this.get(`${this.baseUrl}/${getUserIdentification(user)}/vcs-checkout`, {\n metric: 'profile-system-getUserPayments',\n })\n\n public updateProfileInfo = (\n user: CurrentProfile,\n profile: Profile | { profilePicture: string },\n customFields?: string\n ) =>\n this.post<Profile>(\n `${this.baseUrl}/${getUserIdentification(user)}/personalData`,\n profile,\n {\n metric: 'profile-system-updateProfileInfo',\n params: {\n extraFields: customFields,\n },\n }\n )\n\n public updateAddress = (user: CurrentProfile, addressesData: any) =>\n this.post(\n `${this.baseUrl}/${getUserIdentification(user)}/addresses`,\n addressesData,\n {\n metric: 'profile-system-updateAddress',\n }\n )\n\n public deleteAddress(user: CurrentProfile, addressName: string) {\n return this.getProfileInfo(user).then((profile) => {\n this.getUserAddresses(user, profile).then((addresses: Address[]) => {\n const [address] = addresses.filter(\n (addr) => addr.addressName === addressName\n )\n\n if (!address) {\n return Promise.resolve()\n }\n\n return this.delete(\n `${this.baseUrl}/${getUserIdentification(\n user\n )}/addresses/${addressName}`,\n {\n metric: 'profile-system-deleteAddress',\n }\n )\n })\n })\n }\n\n public updatePersonalPreferences = (\n user: CurrentProfile,\n personalPreferences: PersonalPreferences,\n _: Profile\n ) =>\n this.post(\n `${this.baseUrl}/${getUserIdentification(user)}/personalPreferences/`,\n personalPreferences,\n {\n metric: 'profile-system-subscribeNewsletter',\n }\n )\n\n public createProfile = (profile: Profile) =>\n this.post(this.baseUrl, { personalData: profile })\n\n protected get = <T>(url: string, config?: RequestConfig) =>\n this.http.get<T>(url, config).catch<any>(statusToError)\n\n protected post = <T>(url: string, data?: any, config?: RequestConfig) =>\n this.http.post<T>(url, data, config).catch<any>(statusToError)\n\n protected delete = <T>(url: string, config?: RequestConfig) =>\n this.http.delete<T>(url, config).catch<any>(statusToError)\n\n protected patch = <T>(url: string, data?: any, config?: RequestConfig) =>\n this.http.patch<T>(url, data, config).catch<any>(statusToError)\n\n private baseUrl = '/api/profile-system/pvt/profiles'\n}\n\nfunction getUserIdentification(user: CurrentProfile) {\n return user.userId || encodeURIComponent(user.email)\n}\n\n```" } ]
code_store-graphql_7c4b1f93
[ { "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/clients/profile/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { InstanceOptions, IOContext, JanusClient } from '@vtex/api'\n\nconst FIVE_SECONDS_MS = 5 * 1000\n\nexport class ProfileClient extends JanusClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n ...options?.headers,\n VtexIdClientAutCookie: context.authToken ?? '',\n },\n timeout: FIVE_SECONDS_MS,\n })\n }\n\n public getProfileInfo = (\n user: CurrentProfile,\n context: Context,\n customFields?: string\n ) =>\n this.getProfileClient(context).then((profileClient) =>\n profileClient.getProfileInfo(user, customFields)\n )\n\n public createProfile = (profile: Profile, context: Context) =>\n this.getProfileClient(context).then((profileClient) =>\n profileClient.createProfile(profile)\n )\n\n public getUserAddresses = (\n user: CurrentProfile,\n context: Context,\n currentUserProfile?: Profile\n ) =>\n this.getProfileClient(context).then((profileClient) => {\n if (!currentUserProfile) {\n return profileClient.getProfileInfo(user).then((userProfile) => {\n return profileClient.getUserAddresses(user, userProfile, undefined)\n })\n }\n\n return profileClient.getUserAddresses(user, currentUserProfile, undefined)\n })\n\n public getUserPayments = (user: CurrentProfile, context: Context) =>\n this.getProfileClient(context).then((profileClient) =>\n profileClient.getUserPayments(user)\n )\n\n public updateProfileInfo = (\n user: CurrentProfile,\n profile: Profile | { profilePicture: string },\n context: Context,\n customFields?: string\n ) =>\n this.getProfileClient(context).then((profileClient) =>\n profileClient.updateProfileInfo(user, profile, customFields)\n )\n\n public updateAddress = (\n user: CurrentProfile,\n addressesData: any,\n context: Context\n ) =>\n this.getProfileClient(context).then((profileClient) =>\n profileClient.updateAddress(user, addressesData)\n )\n\n public deleteAddress = (\n user: CurrentProfile,\n addressName: string,\n context: Context\n ) =>\n this.getProfileClient(context).then((profileClient) =>\n profileClient.deleteAddress(user, addressName)\n )\n\n public updatePersonalPreferences = (\n user: CurrentProfile,\n personalPreferences: PersonalPreferences,\n context: Context,\n currentUserProfile?: Profile\n ) =>\n this.getProfileClient(context).then((profileClient) => {\n if (!currentUserProfile) {\n return profileClient.getProfileInfo(user).then((userProfile) => {\n profileClient.updatePersonalPreferences(\n user,\n personalPreferences,\n userProfile\n )\n })\n }\n\n return profileClient.updatePersonalPreferences(\n user,\n personalPreferences,\n currentUserProfile\n )\n })\n\n private getProfileClient = (context: Context) => {\n const licenseManager = context.clients.licenseManagerExtended\n\n return licenseManager.getCurrentAccount().then((account: Account) => {\n if (account.PIIEnabled) {\n return context.clients.profileV2\n }\n\n return context.clients.profileV1\n })\n }\n}\n\n```" } ]
code_store-graphql_5cce64c1
[ { "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/typings/@gocommerce/utils.d.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '@gocommerce/utils' {\n const Functions: any\n}\n\n```" } ]
code_store-graphql_1fcf997c
[ { "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/utils/flags/flagRegionalization.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { regionFlag } from './regionFlag'\n\nexport function isSellerFlaggedForChangingOnSimulationBasedOnRegion(\n sellerName: string\n) {\n return regionFlag.includes(sellerName)\n}\n\n```" } ]
code_store-graphql_19d1c811
[ { "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/utils/flags/regionFlag.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const regionFlag = [\n 'casinofr',\n 'casinofrprod',\n 'casinofrqa',\n 'casinofrst',\n]\n\n```" } ]
code_store-graphql_40d975a9
[ { "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/oms/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { isUserLoggedIn } from '../../utils'\n\nexport const queries = {\n userLastOrder: (_: any, __: any, ctx: Context) => {\n const {\n clients: { oms },\n } = ctx\n\n return isUserLoggedIn(ctx) ? oms.userLastOrder() : null\n },\n\n order: (_: any, { id }: { id: string }, { clients: { oms } }: Context) =>\n oms.order(id),\n}\n\nexport const fieldResolvers = {\n OrderItemPaymentConnectorResponse: {\n additionalData: ({\n tid,\n returnCode,\n message,\n ...additionalData\n }: ConnectorResponse) => additionalData,\n },\n}\n\ninterface ConnectorResponse {\n tid: string\n returnCode: string\n message: string\n [key: string]: string\n}\n\n```" } ]
code_store-graphql_cf9c1426
[ { "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/portal/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Site } from '../../clients/portal'\n\nexport const resolvers = {\n storeConfigs: async (_: any, __: any, ctx: Context) => {\n const {\n clients: { portal },\n vtex: { account },\n } = ctx\n\n const sites = await portal.sites()\n\n const currentSite = (sites as Site[]).find(\n (site: Site) => site.siteName === account\n )\n\n try {\n return portal.storeConfigs(currentSite ? currentSite.id : 'default')\n } catch (e) {\n ctx.clients.logger.info(\n JSON.stringify(currentSite),\n 'portal-storegraphql-errors'\n )\n\n return null\n }\n },\n}\n\n```" } ]
code_store-graphql_2c5b2f7c
[ { "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/auth/mapLoginSessionsFromAPI.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { UAParser } from 'ua-parser-js'\n\nimport { LoginSession, LoginAccess, DeviceType } from './types'\n\nconst getLastAccessDateFromHistory = (history: LoginAccess[]) => {\n if (history && history.length > 0) {\n const epochSeconds = history[history.length - 1].date\n\n return new Date(epochSeconds * 1000).toISOString()\n }\n\n return null\n}\n\nconst deviceTypeByParserType: Record<string, DeviceType> = {\n console: 'DESKTOP',\n mobile: 'MOBILE',\n tablet: 'TABLET',\n smarttv: 'DESKTOP',\n wearable: 'MOBILE',\n embedded: 'DESKTOP',\n}\n\nconst parseUserAgent = (userAgent: string) => {\n const parser = new UAParser(userAgent)\n const { name: browser = null } = parser.getBrowser()\n const { name: os = null } = parser.getOS()\n const { type: parserType } = parser.getDevice()\n\n const deviceType: DeviceType = parserType\n ? deviceTypeByParserType[parserType]\n : 'DESKTOP'\n\n return {\n browser,\n os,\n deviceType,\n }\n}\n\nconst mapLoginSessionsFromAPI = (loginSessions: LoginSession[]) =>\n loginSessions.map((session) => {\n const { browser, os, deviceType } = parseUserAgent(session.userAgent)\n\n return {\n id: session.id,\n cacheId: session.id,\n deviceType,\n city: null,\n lastAccess: getLastAccessDateFromHistory(session.accessHistory),\n browser,\n os,\n ip: session.ipAddress,\n fullAddress: null,\n firstAccess: session.creationDate,\n }\n })\n\nexport default mapLoginSessionsFromAPI\n\n```" } ]
code_store-graphql_0a9723d9
[ { "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/auth/types.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface LoginAccess {\n date: number\n ip: string\n}\n\nexport interface LoginSession {\n id: string\n creationDate: string\n expirationDate: string\n originHostname: string\n ipAddress: string\n userAgent: string\n accessHistory: LoginAccess[]\n}\n\nexport interface GetLoginSessionsResponse {\n currentSessionId: string | null\n sessions: LoginSession[]\n}\n\nexport type DeviceType = 'MOBILE' | 'TABLET' | 'DESKTOP'\n\n```" } ]
code_store-graphql_a237e3a3
[ { "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/auth/index.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { stringify } from 'querystring'\n\nimport { ResolverError, UserInputError } from '@vtex/api'\nimport http, { Method } from 'axios'\nimport { parse, serialize } from 'cookie'\n\nimport { withAuthToken } from '../headers'\nimport paths from '../paths'\nimport { GetLoginSessionsResponse } from './types'\nimport mapLoginSessionsFromAPI from './mapLoginSessionsFromAPI'\n\nconst E_PASS = 'Password does not follow specified format'\nconst E_TOKEN = 'VtexSessionToken cookie is null'\n\ninterface ParamsMakeRequest {\n ctx: any\n url: any\n method?: Method\n body?: any\n vtexIdVersion?: string\n authCookieAdmin?: string | null\n authCookieStore?: string | null\n}\n\nexport async function makeRequest<T = any>({\n ctx,\n url,\n method = 'GET',\n body,\n vtexIdVersion = 'store-graphql',\n authCookieAdmin = null,\n authCookieStore = null,\n}: ParamsMakeRequest) {\n const adminAuthHeader = authCookieAdmin\n ? `VtexIdClientAutCookie=${authCookieAdmin};`\n : ''\n\n const storeAuthHeader = authCookieStore\n ? `VtexIdClientAutCookie_${ctx.account}=${authCookieStore};`\n : ''\n\n const cookieHeader = `${adminAuthHeader}${storeAuthHeader}`\n\n const composedHeaders = {\n 'X-Vtex-Use-Https': 'true',\n 'vtex-ui-id-version': vtexIdVersion,\n ...(cookieHeader && { Cookie: cookieHeader }),\n ...(body && { 'content-type': 'application/x-www-form-urlencoded' }),\n }\n\n return http.request<T>({\n ...(body && { data: stringify(body) }),\n headers: withAuthToken(composedHeaders)(ctx),\n method,\n url,\n })\n}\n\nconst getSessionToken = async (ioContext: any, redirectUrl?: any) => {\n const { data, status } = await makeRequest({\n ctx: ioContext,\n url: paths.sessionToken(ioContext.account, ioContext.account, redirectUrl),\n })\n\n if (!data.authenticationToken) {\n throw new ResolverError(\n `Failed to get session token from VTEX ID. status=${status}`\n )\n }\n\n return data.authenticationToken\n}\n\nconst setVtexIdAuthCookie = (\n ioContext: any,\n response: any,\n headers: any,\n authStatus: any\n) => {\n if (authStatus === 'Success') {\n const authAccount = `VtexIdclientAutCookie_${ioContext.account}`\n const authCookie = parse(\n headers['set-cookie'].find((checkAuth: any) => {\n return checkAuth.includes(authAccount)\n })\n )\n\n const VTEXID_EXPIRES = Math.round(\n (new Date(authCookie.expires).getTime() - Date.now()) / 1000\n )\n\n response.set(\n 'Set-Cookie',\n serialize(authAccount, authCookie[authAccount], {\n httpOnly: true,\n maxAge: VTEXID_EXPIRES,\n path: '/',\n secure: true,\n })\n )\n }\n\n return authStatus\n}\n\n/** Password must have at least eight characters with at least one number,\n * one lowercase and one uppercase letter\n */\nconst checkPasswordFormat = (password: any) => {\n const regex = /(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/\n\n return regex.test(password)\n}\n\nexport const queries = {\n /**\n * Request to the VTEX ID API the list of available login\n * options to the user authentication.\n */\n loginOptions: async (_: any, __: any, { vtex: ioContext }: any) => {\n const {\n data: {\n oauthProviders,\n showClassicAuthentication,\n showAccessKeyAuthentication,\n },\n } = await makeRequest({\n ctx: ioContext,\n url: paths.sessionToken(ioContext.account, ioContext.account),\n })\n\n return {\n accessKeyAuthentication: showAccessKeyAuthentication,\n classicAuthentication: showClassicAuthentication,\n providers: oauthProviders,\n }\n },\n\n /**\n * Get all currently active Login Sessions from user (identified by the cookie)\n * @return Object with Login Sessions list and currentSessionId\n */\n loginSessionsInfo: async (\n _: any,\n __: any,\n {\n request: {\n headers: { 'vtex-ui-id-version': uiVersion },\n },\n vtex: ioContext,\n }: any\n ) => {\n const { storeUserAuthToken, account } = ioContext\n\n if (!storeUserAuthToken) {\n return null\n }\n\n const {\n data: { currentSessionId, sessions },\n } = await makeRequest<GetLoginSessionsResponse>({\n ctx: ioContext,\n url: paths.loginSessions(account, account),\n authCookieStore: storeUserAuthToken,\n vtexIdVersion: uiVersion,\n })\n\n return {\n currentLoginSessionId: currentSessionId,\n loginSessions: mapLoginSessionsFromAPI(sessions),\n }\n },\n}\n\nexport const mutations = {\n /**\n * Get email and access code in args and set VtexIdAuthCookie in response cookies.\n * @return authStatus that show if user is logged or something wrong happens.\n */\n accessKeySignIn: async (\n _: any,\n args: any,\n {\n vtex: ioContext,\n request: {\n headers: { cookie },\n },\n response,\n }: any\n ) => {\n const { VtexSessionToken } = parse(cookie)\n\n if (!VtexSessionToken) {\n throw new UserInputError(E_TOKEN)\n }\n\n const {\n headers,\n data: { authStatus },\n } = await makeRequest({\n ctx: ioContext,\n method: 'POST',\n url: paths.accessKeySignIn(),\n body: {\n accesskey: args.code,\n authenticationToken: VtexSessionToken,\n email: args.email,\n },\n })\n\n return setVtexIdAuthCookie(ioContext, response, headers, authStatus)\n },\n\n /**\n * Get email and password in args and set VtexIdAuthCookie in response cookies.\n * @return authStatus that show if user is logged or something wrong happens.\n */\n classicSignIn: async (\n _: any,\n args: any,\n { vtex: ioContext, response }: any\n ) => {\n if (!checkPasswordFormat(args.password)) {\n throw new UserInputError(E_PASS)\n }\n\n const VtexSessionToken = await getSessionToken(ioContext)\n const {\n headers,\n data: { authStatus },\n } = await makeRequest({\n ctx: ioContext,\n method: 'POST',\n url: paths.classicSignIn(),\n body: {\n authenticationToken: VtexSessionToken,\n login: args.email,\n password: args.password,\n },\n })\n\n return setVtexIdAuthCookie(ioContext, response, headers, authStatus)\n },\n\n /** TODO: When VTEX ID have an endpoint that expires the VtexIdclientAutCookie, update this mutation.\n * 13-06-2018 - @brunojdo\n */\n logout: async (_: any, __: any, { vtex: ioContext, response }: any) => {\n response.set(\n 'Set-Cookie',\n serialize(`VtexIdclientAutCookie_${ioContext.account}`, '', {\n path: '/',\n maxAge: 0,\n })\n )\n\n return true\n },\n\n /**\n * Log out from specified login sessions of user (identified by the cookie)\n * @return login session ID\n */\n logOutFromSession: async (\n _: any,\n {\n sessionId,\n }: {\n sessionId: string\n },\n {\n request: {\n headers: { 'vtex-ui-id-version': uiVersion },\n },\n vtex: ioContext,\n }: any\n ) => {\n const { storeUserAuthToken, account } = ioContext\n\n if (!storeUserAuthToken) {\n return null\n }\n\n await makeRequest({\n url: paths.logOutFromSession({ account, scope: account, sessionId }),\n ctx: ioContext,\n vtexIdVersion: uiVersion,\n method: 'POST',\n authCookieStore: storeUserAuthToken,\n })\n\n return sessionId\n },\n\n oAuth: async (_: any, args: any, { vtex: ioContext }: any) => {\n const { provider, redirectUrl } = args\n const VtexSessionToken = await getSessionToken(ioContext, redirectUrl)\n\n return paths.oAuth(VtexSessionToken, provider)\n },\n\n /** Set a new password for an user.\n * @return authStatus that show if password was created and user is logged or something wrong happens.\n */\n recoveryPassword: async (\n _: any,\n args: any,\n {\n vtex: ioContext,\n request: {\n headers: { cookie },\n },\n response,\n }: any\n ) => {\n const { VtexSessionToken } = parse(cookie)\n\n if (!VtexSessionToken) {\n throw new UserInputError(E_TOKEN)\n }\n\n if (!checkPasswordFormat(args.newPassword)) {\n throw new UserInputError(E_PASS)\n }\n\n const body = {\n authenticationToken: VtexSessionToken,\n login: args.email,\n newPassword: args.newPassword,\n accessKey: args.code,\n }\n\n const {\n headers,\n data: { authStatus },\n } = await makeRequest({\n ctx: ioContext,\n method: 'POST',\n url: paths.setPassword(),\n body,\n })\n\n return setVtexIdAuthCookie(ioContext, response, headers, authStatus)\n },\n\n /** Set a new password for an user.\n * @return authStatus that show if password was created and user is logged or something wrong happens.\n */\n redefinePassword: async (\n _: any,\n args: any,\n { vtex: ioContext, response }: any\n ) => {\n if (\n !checkPasswordFormat(args.newPassword) ||\n !checkPasswordFormat(args.currentPassword)\n ) {\n throw new UserInputError(E_PASS)\n }\n\n const VtexSessionToken = await getSessionToken(ioContext)\n const body = {\n authenticationToken: VtexSessionToken,\n login: args.email,\n newPassword: args.currentPassword,\n currentPassword: args.newPassword,\n }\n\n const {\n headers,\n data: { authStatus },\n } = await makeRequest({\n ctx: ioContext,\n method: 'POST',\n url: paths.setPassword(),\n body,\n vtexIdVersion: args.vtexIdVersion,\n })\n\n if (authStatus === 'WrongCredentials') {\n throw new UserInputError('Wrong credentials.')\n } else if (authStatus === 'BlockedUser') {\n throw new UserInputError('You were blocked by VTEX ID.')\n }\n\n return setVtexIdAuthCookie(ioContext, response, headers, authStatus)\n },\n\n /**\n * Send access key to user email and set VtexSessionToken in response cookies\n * @return Boolean\n */\n sendEmailVerification: async (\n _: any,\n args: any,\n { vtex: ioContext, response }: any\n ) => {\n // VtexSessionToken is valid for 10 minutes\n const SESSION_TOKEN_EXPIRES = 600\n const VtexSessionToken = await getSessionToken(ioContext)\n\n await makeRequest({\n ctx: ioContext,\n method: 'POST',\n url: paths.sendEmailVerification(),\n body: {\n authenticationToken: VtexSessionToken,\n email: args.email,\n },\n })\n response.set(\n 'Set-Cookie',\n serialize('VtexSessionToken', VtexSessionToken, {\n httpOnly: true,\n maxAge: SESSION_TOKEN_EXPIRES,\n path: '/',\n secure: true,\n })\n )\n\n return true\n },\n}\n\n```" } ]
code_store-graphql_9a3f0539
[ { "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/category.ts from the store-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop } from 'ramda'\n\nimport { getCategoryInfo } from './utils'\nimport { formatTranslatableProp } from '../../utils/i18n'\nimport { catalogSlugify } from './slug'\n\nconst getTypeForCategory = (url: string) => {\n switch (url.split('/').length) {\n case 2:\n return 'department'\n\n case 3:\n return 'category'\n\n default:\n return 'subcategory'\n }\n}\n\nconst lastSegment = (route: string) => {\n const splittedSegments = route.split('/')\n\n return splittedSegments[splittedSegments.length - 1]\n}\n\nfunction cleanUrl(url: string) {\n return url.replace(/^.*(vtexcommercestable\\.com\\.br)/, '')\n}\n\nexport const pathToCategoryHref = (path: string) => {\n const isDepartment = path.slice(1).indexOf('/') === -1\n\n return isDepartment ? `${path}/d` : path\n}\n\n/** This type has to be created because the Catlog API to get category by ID does not return the url or children for now.\n * These fields only come if you get the category from the categroy tree api.\n */\ninterface SafeCategory\n extends Pick<\n Category,\n 'id' | 'name' | 'hasChildren' | 'MetaTagDescription' | 'Title'\n > {\n url: string | null\n children: Category[] | null\n}\n\nexport const resolvers = {\n Category: {\n name: formatTranslatableProp<SafeCategory, 'name', 'id'>('name', 'id'),\n\n cacheId: prop('id'),\n\n href: async (\n { id, url }: SafeCategory,\n _: any,\n { vtex: { tenant, binding }, clients: { catalog, rewriter } }: Context\n ) => {\n if (url == null) {\n const category = await getCategoryInfo(catalog, id, 4)\n\n url = category.url\n }\n\n const path = cleanUrl(url)\n\n // Won't translate href if current locale is the same as the default locale\n // or account isn't in the tenant system, or binding data isn't present\n return tenant && binding && binding.id && tenant.locale !== binding.locale\n ? (await rewriter.getRoute(\n id.toString(),\n getTypeForCategory(path),\n binding.id\n )) ?? path\n : path\n },\n\n metaTagDescription: formatTranslatableProp<\n SafeCategory,\n 'MetaTagDescription',\n 'id'\n >('MetaTagDescription', 'id'),\n\n titleTag: formatTranslatableProp<SafeCategory, 'Title', 'id'>(\n 'Title',\n 'id'\n ),\n\n slug: async (\n { name, id, url }: SafeCategory,\n _: any,\n { vtex: { tenant, binding }, clients: { catalog, rewriter } }: Context\n ) => {\n if (url == null) {\n const category = await getCategoryInfo(catalog, id, 4)\n\n url = category.url\n }\n\n // Won't translate slug if current locale is the same as the default locale\n // or account isn't in the tenant system, or binding data isn't present\n if (\n !tenant ||\n !binding ||\n tenant?.locale === binding?.locale ||\n !binding.id\n ) {\n return catalogSlugify(name).toLowerCase()\n }\n\n const translatedRoute =\n (await rewriter.getRoute(\n id.toString(),\n getTypeForCategory(cleanUrl(url)),\n binding.id\n )) ?? url\n\n return lastSegment(translatedRoute)\n },\n\n children: async (\n { id, children }: SafeCategory,\n _: any,\n { clients: { catalog } }: Context\n ) => {\n if (children == null) {\n const category = await getCategoryInfo(catalog, id, 4)\n\n children = category.children\n }\n\n return children\n },\n },\n}\n\n```" } ]