id
stringlengths
12
53
messages
listlengths
3
3
code_product-teaser-interfaces_87b118b9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/react/Noop.tsx from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\n\nconst Noop: FunctionComponent = () => <></>\n\nexport default Noop\n\n```" } ]
code_product-teaser-interfaces_ccdde384
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/store/interfaces.json from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"product-teaser\": {\n \"component\": \"*\",\n \"extensible\": \"public\"\n },\n \"product-teaser.summary\": {\n \"component\": \"*\",\n \"extensible\": \"public\"\n },\n \"product-teaser.product\": {\n \"component\": \"*\",\n \"extensible\": \"public\"\n }\n}\n\n```" } ]
code_product-teaser-interfaces_75c9e777
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/graphql/schema.graphql from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Query {\n appSettings: Settings @cacheControl(scope: PUBLIC, maxAge: MEDIUM)\n}\n\ntype Settings {\n storeId: String\n productBinding: String\n}\n```" } ]
code_product-teaser-interfaces_82575164
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/node/package.json from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"ramda\": \"^0.25.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"8.x\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"3.8.1\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-vtex\": \"^10.1.0\",\n \"prettier\": \"^1.18.2\",\n \"typescript\": \"3.5.2\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'\"\n }\n}\n\n```" } ]
code_product-teaser-interfaces_2f495f49
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/node/index.ts from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ClientsConfig, LRUCache, Service, IOClients, ServiceContext } from '@vtex/api'\nimport { Clients } from './clients'\n\nimport settingsResolver from './resolvers/settings'\n\nconst TIMEOUT_MS = 800\n\n// Create a LRU memory cache for the Product Review client.\n// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.\nconst memoryCache = new LRUCache<string, any>({max: 5000})\nmetrics.trackCache('productReview', 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> 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<IOClients>({\n clients,\n graphql: {\n resolvers: {\n Query: {\n appSettings: settingsResolver,\n }\n },\n },\n})\n```" } ]
code_product-teaser-interfaces_f26d5cc8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/react/TeaserProduct.tsx from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport useProduct from 'vtex.product-context/useProduct'\n\nconst TeaserProduct: FunctionComponent = () => {\n const { product } = useProduct()\n\n if (!product) {\n return null\n }\n\n return (\n <div>\n <FormattedMessage\n id=\"teaser\"\n values={{\n name: product.productName,\n }}\n />\n </div>\n )\n}\n\nexport default TeaserProduct\n\n```" } ]
code_product-teaser-interfaces_c6ee6e6e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/react/TeaserSummary.tsx from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { useProductSummary } from 'vtex.product-summary-context/ProductSummaryContext'\n\nconst RatingInline: FunctionComponent = () => {\n const { product } = useProductSummary()\n\n return (\n <div>\n <FormattedMessage\n id=\"teaser\"\n values={{\n name: product.productName,\n }}\n />\n </div>\n )\n}\n\nexport default RatingInline\n\n```" } ]
code_product-teaser-interfaces_cf7733ca
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/react/package.json from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\",\n \"lint\": \"tsc --noEmit && eslint --ext ts,tsx . --fix\"\n },\n \"dependencies\": {\n \"@vtex/css-handles\": \"^1.0.0\",\n \"classnames\": \"^2.2.6\",\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.8.3\",\n \"react-apollo\": \"^2.5.8\",\n \"react-dom\": \"^16.8.3\",\n \"react-intl\": \"^2.7.2\"\n },\n \"devDependencies\": {\n \"@types/classnames\": \"^2.2.7\",\n \"@types/graphql\": \"^14.2.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/prop-types\": \"^15.7.0\",\n \"@types/ramda\": \"^0.26.5\",\n \"@types/react\": \"^16.8.10\",\n \"@types/react-intl\": \"^2.3.17\",\n \"@vtex/test-tools\": \"^0.2.0\",\n \"apollo-client\": \"^2.5.1\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-vtex-react\": \"^4.1.0\",\n \"prettier\": \"^1.18.2\",\n \"typescript\": \"3.5.2\"\n }\n}\n\n```" } ]
code_product-teaser-interfaces_86aee422
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/store/interfaces.json from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"product-teaser.summary.example-teaser\": {\n \"component\": \"TeaserSummary\"\n },\n \"product-teaser.product.example-teaser\": {\n \"component\": \"TeaserProduct\"\n }\n}\n\n```" } ]
code_product-teaser-interfaces_96cc9985
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/node/clients/productReview.ts from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ExternalClient, InstanceOptions, IOContext, IOResponse } from '@vtex/api'\n\nexport default class ProductReview extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super('http://httpstat.us', context, options)\n }\n\n public async getStatus (status: number): Promise<string> {\n return this.http.get(status.toString(), {\n metric: 'status-get',\n })\n }\n\n public async getStatusWithHeaders (status: number): Promise<IOResponse<string>> {\n return this.http.getRaw(status.toString(), {\n metric: 'status-get-raw',\n })\n }\n}\n```" } ]
code_product-teaser-interfaces_63154ec7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/node/clients/index.ts from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport ProductReview from './productReview'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get status() {\n return this.getOrSet('productReview', ProductReview)\n }\n}\n```" } ]
code_product-teaser-interfaces_45f439a4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/node/resolvers/settings.ts from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ServiceContext } from \"@vtex/api\";\n\ndeclare var process : {\n env: {\n VTEX_APP_ID: string\n }\n}\n\nconst appId = process.env.VTEX_APP_ID\n\nexport default async function settings(_root: any, _args: {}, ctx: ServiceContext) {\n const settings = await ctx.clients.apps.getAppSettings(appId)\n\n return settings\n}\n```" } ]
code_product-teaser-interfaces_5d573b1f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/react/typings/storefront.d.ts from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent, ReactElement } from 'react'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n schema?: object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n schema: object\n }\n}\n\n```" } ]
code_product-teaser-interfaces_6f9a6d06
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/react/typings/vtex.product-context.d.ts from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.product-context/useProduct' {\n import { Context } from 'react'\n\n interface ProductContext {\n product: any\n }\n\n export default function useProduct(): ProductContext\n}\n\n```" } ]
code_product-teaser-interfaces_d32bd61a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/react/typings/css.d.ts from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: any\n export default css\n}\n\n```" } ]
code_product-teaser-interfaces_e8298aca
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/react/typings/vtex.product-summary-context.d.ts from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.product-summary-context/ProductSummaryContext' {\n import { Context } from 'react'\n\n interface ProductSummaryContext {\n product: any\n }\n\n export function useProductSummary(): ProductSummaryContext\n}\n```" } ]
code_product-teaser-interfaces_da075282
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-teaser-interfaces/example/react/typings/graphql.d.ts from the product-teaser-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_formatted-price_7b3a7457
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/messages/pt.json from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/price.Free\": \"GRÁTIS\",\n \"store/price.TBD\": \"A calcular\"\n}\n\n```" } ]
code_formatted-price_ad59736b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/messages/en.json from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/price.Free\": \"FREE\",\n \"store/price.TBD\": \"TBD\"\n}\n\n```" } ]
code_formatted-price_1a14afd1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/messages/fr.json from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/price.Free\": \"GRATUIT\",\n \"store/price.TBD\": \"À déterminer\"\n}\n\n```" } ]
code_formatted-price_0825b039
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/messages/ro.json from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/price.Free\": \"GRATUIT\",\n \"store/price.TBD\": \"TBD\"\n}\n\n```" } ]
code_formatted-price_df5ae2e2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/messages/context.json from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/price.Free\": \"FREE\",\n \"store/price.TBD\": \"TBD\"\n}\n\n```" } ]
code_formatted-price_5d16ca6a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/messages/id.json from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/price.Free\": \"GRATIS\",\n \"store/price.TBD\": \"TBD\"\n}\n\n```" } ]
code_formatted-price_027ed1bd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/messages/es.json from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/price.Free\": \"GRATIS\",\n \"store/price.TBD\": \"Por calcular\"\n}\n\n```" } ]
code_formatted-price_2bfc064e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/messages/ar.json from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/price.Free\": \"مجانًا\",\n \"store/price.TBD\": \"يُحدَّد فيما بعد\"\n}\n\n```" } ]
code_formatted-price_e84b3428
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/docs/README.md from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Price\n\n> Formatting utilities for displaying prices.\n\n<table>\n<tbody>\n<tr>\n<td>\n <img width=\"60\" alt=\"free label\" src=\"https://user-images.githubusercontent.com/10223856/78281020-698c5900-74f0-11ea-96ae-c63d460e5f1c.png\">\n</td>\n<td>\n <code>&lt;FormattedPrice value={0} /&gt;</code>\n</td>\n</tr>\n<tr>\n<td>\n <img width=\"60\" alt=\"tbd label\" src=\"https://user-images.githubusercontent.com/10223856/78281021-6a24ef80-74f0-11ea-9ba4-aa0003c48ae4.png\">\n</td>\n<td>\n <code>&lt;FormattedPrice value={null} /&gt;</code>\n</td>\n</tr>\n<tr>\n<td>\n <img width=\"94\" alt=\"10 BRL label\" src=\"https://user-images.githubusercontent.com/10223856/78281024-6abd8600-74f0-11ea-92ff-ebe95f548016.png\">\n</td>\n<td>\n <code>&lt;FormattedPrice value={10} /&gt;</code>\n</td>\n</tr>\n</tbody>\n</table>\n\n## Usage\n\nTo use this app, you first need to add it in your `manifest.json` file, like so\n\n```json\n{\n \"dependencies\": {\n \"vtex.formatted-price\": \"0.x\"\n }\n}\n```\n\n> If you are using TypeScript, you may also want to run `vtex setup` after the step above\n\nNow you can import the component and use it\n\n```jsx\nimport React from 'react'\nimport { FormattedPrice } from 'vtex.formatted-price'\n\nconst ProductSummary = ({ productPrice }) => {\n return (\n <article>\n <h3>My Awesome Product</h3>\n\n <FormattedPrice value={productPrice} />\n </article>\n )\n}\n```\n\n## Components\n\n### FormattedPrice\n\nResponsible for rendering and styling the value prop as a price\nwith the current store currency settings.\n\n#### Props\n\n| Prop name | Type | Required |\n| --- | --- | --- |\n| [`value`](#formattedprice-value) | `number` | `false` |\n\n##### FormattedPrice value\n\n`number | null | undefined`\n\nValue used in the formatting.\n\n### useFormattedPrice\n\n`(value: number | null | undefined) => string`\n\nUtility hook that formats the value parameter into a price string, using the\ncurrent store currency settings.\n\n## CSS Customization\n\nIn order to apply CSS customizations in this and other blocks, follow the instructions\ngiven in [this recipe](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization)\nregarding using CSS classes for store customization.\n\n| CSS Handle | Component |\n| --- | --- |\n| `price` | `FormattedPrice` |\n\n```" } ]
code_formatted-price_cfd003f5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/react/package.json from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"classnames\": \"^2.2.6\",\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.8.3\",\n \"react-dom\": \"^16.8.3\",\n \"react-intl\": \"^4.3.1\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/classnames\": \"^2.2.10\",\n \"@types/graphql\": \"^14.2.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/prop-types\": \"^15.7.0\",\n \"@types/ramda\": \"^0.26.5\",\n \"@types/react\": \"^16.8.10\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"typescript\": \"3.8.3\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.2/public/@types/vtex.css-handles\",\n \"vtex.format-currency\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.format-currency@0.1.3/public/@types/vtex.format-currency\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.98.1/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.112.27/public/@types/vtex.styleguide\"\n },\n \"version\": \"0.8.1\"\n}\n\n```" } ]
code_formatted-price_86673bd4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/react/FormattedPrice.tsx from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classnames from 'classnames'\nimport React, { FC } from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport useFormattedPrice from './useFormattedPrice'\n\nconst CSS_HANDLES = ['price'] as const\n\ninterface FormattedPriceProps {\n value?: number | null\n}\n\nconst FormattedPrice: FC<FormattedPriceProps> = ({ value }) => {\n const handles = useCssHandles(CSS_HANDLES)\n\n const price = useFormattedPrice(value)\n\n return (\n <div className={classnames(handles.price, { 'c-success': value === 0 })}>\n {price}\n </div>\n )\n}\n\nexport default FormattedPrice\n\n```" } ]
code_formatted-price_aab65db9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/react/useFormattedPrice.ts from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useMemo } from 'react'\nimport { useIntl, defineMessages } from 'react-intl'\nimport { formatCurrency } from 'vtex.format-currency'\nimport { useRuntime } from 'vtex.render-runtime'\n\nconst messages = defineMessages({\n free: {\n id: 'store/price.Free',\n },\n tbd: {\n id: 'store/price.TBD',\n },\n})\n\nconst useFormattedPrice = (value?: number | null) => {\n const { culture } = useRuntime()\n const intl = useIntl()\n\n const formattedPrice = useMemo(() => {\n if (value == null) {\n return intl.formatMessage(messages.tbd)\n }\n if (value === 0) {\n return intl.formatMessage(messages.free)\n }\n return formatCurrency({ intl, value, culture })\n }, [culture, intl, value])\n\n return formattedPrice\n}\n\nexport default useFormattedPrice\n\n```" } ]
code_formatted-price_6c2a5dec
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/react/typings/storefront.d.ts from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n getSchema?(props: P): object\n schema?: object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n getSchema?(props: P): object\n schema: object\n }\n}\n\n```" } ]
code_formatted-price_1e86be7b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/react/typings/vtex.render-runtime.d.ts from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { RenderContext } from 'vtex.render-runtime'\n\ndeclare module 'vtex.render-runtime' {\n export const useRuntime: () => RenderContext\n}\n\n```" } ]
code_formatted-price_772bd74b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/react/typings/css.d.ts from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: any\n export default css\n}\n\n```" } ]
code_formatted-price_8628c09e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/react/typings/graphql.d.ts from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_formatted-price_a816f55a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of formatted-price/react/typings/vtex.styleguide.d.ts from the formatted-price VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n import { ComponentType } from 'react'\n\n export const Input: ComponentType<InputProps>\n\n interface InputProps {\n [key: string]: any\n }\n}\n\n```" } ]
code_smartlook_121b974c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of smartlook/docs/README.md from the smartlook VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Smartlook\n\nOpen the VTEX APP Store and install the app on your store.\n\nor\n\nRun the following command:\n\n```sh\nvtex install vtex.smartlook@0.x\n```\n\nNext, open the app settings on your admin and fill the form with Site ID.\n\n### Setup in Cart and Checkout page\n\nOpen your admin in the Checkout section in the `checkout6-custom.js`:\n\nhttps://ACCOUNT.myvtex.com/admin/portal/#/sites/default/code/files/checkout6-custom.js\n\nAdd the following snippet in the file and replace `\"YOURSITEID\"` with your Site ID:\n\n```js\n// Smartlook\nwindow.smartlook||(function(d) {\n var o=smartlook=function(){ o.api.push(arguments)},h=d.getElementsByTagName('head')[0];\n var c=d.createElement('script');o.api=new Array();c.async=true;c.type='text/javascript';\n c.charset='utf-8';c.src='https://rec.smartlook.com/recorder.js';h.appendChild(c);\n })(document);\n smartlook('init', 'YOURSITEID');\n```\n\nClick Save.\n\n```" } ]
code_cookie-script_b3b70c19
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cookie-script/docs/README.md from the cookie-script VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/cookie-script) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Cookie Script\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\n[Cookie Script](https://cookie-script.com/) app brings the [solution](https://apps.vtex.com/vtex-cookie-script/p) to make your website cookies comply with GDPR and CCPA.\n\n![image](https://user-images.githubusercontent.com/284515/86488877-d35b0f80-bd38-11ea-95f9-7610985e19d5.png)\n\nLearn how to install and configure the app on the following sections.\n\n\n## Installing Cookie Script app\n\nIt is possible to install the Cookie Script in your store either by using [App Store](https://apps.vtex.com/vtex-cookie-script/p) or the [VTEX IO CLI](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-vtex-io-cli-installation-and-command-reference).\n\n\n ### Using VTEX App Store\n \n \n1. Access the **Apps** section in your account's admin page and look for the Cookie Script box;\n2. Then, click on the **Install** button;\n3. You'll see a warning message about needing to enter the necessary configurations. Scroll down and type in your **Cookie Script ID**.\n4. Click on **Save**.\n\n### Using VTEX IO Toolbelt\n \n\n1. In your terminal, [install](https://vtex.io/docs/recipes/development/installing-an-app/) the `vtex.cookie-script@0.x` app. \n3. To confirm that the app has now been installed, run in your terminal `vtex ls` and check the installed apps' list. \n4. Access the **Apps** section in your account's admin page and look for the Cookie Script box. Once you find it, click on it.\n5. Fill in the **Cookie Script ID** field.\n6. Click on **Save**.\n\n\n\nAfter installing the app, you must create an account in [Cookie Script](https://cookie-script.com/create-an-account.html) to make the app work on your store. Follow the steps on the [Cookie Script Configuration](#cookie-script-configuration) section to create an account and configure the app.\n\n## Cookie Script Configuration\nOnce you have installed the app, you need to create an account in [Cookie Script](https://cookie-script.com/create-an-account.html) to be able to configure the app.\n\n>⚠️ *You must follow the steps described in this section to guarantee the cookies will work. Otherwise, they will break the purchases flow from your store.*\n\n1. Go to the [Cookie Script](https://cookie-script.com/create-an-account.html) page and create your account.\n2. After creating your account, go to the **Dashboard** tab and click on `Add website`.\n\n![app-dashboard](https://user-images.githubusercontent.com/67270558/133613562-3248fadc-e6a0-4859-8b05-5167085e4242.gif)\n\n3. Once you have added your website, go to the **Cookie scanner** tab and run a scan. \n2. After the scan is complete, go to **Cookies** tab and make sure the following cookies are categorized as **Stricly Necessary**: `ASPXAUTH`, `checkout.vtex.com`, `CookieConsent`, `device`, `vtex_segment`, `vtex_session`, `VtexFingerPrint`, `VtexRCMacIdv7`, `VtexRCRequestCounter`, `VtexRCSessionIdv7` and `VtexWorkspace`.\n\n\n<!-- DOCS-IGNORE:start -->\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n<!-- DOCS-IGNORE:end -->\n\n```" } ]
code_cookie-script_57699365
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cookie-script/public/metadata/messages/es-AR.json from the cookie-script VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Cookie Script\",\n \"headline\": \"Haga que las cookies de su sitio web cumplan con GDPR y CCPA.\",\n \"overview\": \"Esta aplicación permite una fácil integración con los servicios ofrecidos por Cookie Script.\\r\\nCookie Script lo ayuda a cumplir con GDPR y CCPA. Cree su propia ventana emergente de información de cookies sin la necesidad de habilidades de programación. Puedes usar el servicio gratis.\",\n \"features\": [\n \"Cookie Script comprueba, categoriza y agrega automáticamente la descripción de todas las cookies que se encuentran en su sitio web\",\n \"Analizamos su sitio web y generamos informes detallados sobre todos los tipos de cookies utilizados\",\n \"Registramos y almacenamos todos los consentimientos de los visitantes para que pueda descargarlos según lo requiera el RGPD\",\n \"Siga las reglas de GPDR y permita que sus usuarios suspendan el consentimiento de las cookies en cualquier momento en cualquier página\",\n \"Cookie Script puede eliminar todas las cookies hasta que el visitante acepte la Política de cookies. Esto es opcional, por lo que puede cumplir con GDPR y CCPA. También puede bloquear las cookies de terceros\",\n \"Seleccione qué cookies son estrictamente necesarias (funcionales) para que su sitio web funcione correctamente\"\n ],\n \"additionalInformation\": \" Algunas funciones solo están disponibles para suscripciones específicas.\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_cookie-script_f965d9aa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cookie-script/public/metadata/messages/pt-BR.json from the cookie-script VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Cookie Script\",\n \"headline\": \"Faça com que os cookies do seu site estejam em conformidade com o GDPR e o CCPA.\",\n \"overview\": \"Este aplicativo permite uma fácil integração com os serviços oferecidos por Cookie Script.\\r\\nCookie Script ajuda você a cumprir o GDPR e o CCPA. Crie seu próprio pop-up de informações sobre cookies sem a necessidade de habilidades de programação. Você pode usar o serviço gratuitamente.\",\n \"features\": [\n \"Cookie Script verifica automaticamente, categoriza e adiciona descrição a todos os cookies encontrados no seu site\",\n \"Analisamos seu site e geramos relatórios detalhados sobre todos os tipos de cookies utilizados\",\n \"Registramos e armazenamos todos os consentimentos dos visitantes para que você possa baixá-los conforme exigido pelo GDPR\",\n \"Siga as regras do GPDR e permita que seus usuários suspendam o consentimento de cookies a qualquer momento em qualquer página\",\n \"Cookie Script pode excluir todos os cookies até o visitante concordar com a Política de Cookies. Isso é opcional, para que você possa cumprir o GDPR e o CCPA. Você também pode bloquear cookies de terceiros\",\n \"Selecione quais cookies são estritamente necessários (funcionais) para o seu site funcionar corretamente\"\n ],\n \"additionalInformation\": \"Alguns recursos estão disponíveis apenas para assinaturas específicas.\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_cookie-script_b716a400
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cookie-script/public/metadata/messages/en-US.json from the cookie-script VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Cookie Script\",\n \"headline\": \"Make your website cookies comply with GDPR and CCPA.\",\n \"overview\": \"This app allows easy integration with the services offered by Cookie Script.\\r\\nCookie Script helps you to comply GDPR and CCPA. Make your own cookie information popup, no programming skills required. You can even use it for free.\",\n \"features\": [\n \"Cookie-Script automatically scans, categorizes and adds description to all cookies found on your website\",\n \"We scan your website and generate detailed report about all types of cookies used\",\n \"We record and store all visitor consents so you could download them as required by GDPR\",\n \"Follow GPDR rules and allow your users to withdraw cookie consent at any time on any page\",\n \"Cookie-Script can delete all cookies until visitor agrees to Cookie Policy. This is optional, so you can comply with both GDPR and CCPA. You can also block third-party cookies\",\n \"Select which cookies are strictly necessary (functional) for your website to work properly\"\n ],\n \"additionalInformation\": \"Some features are only available to specific subscriptions.\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_hello-support_369780f1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of hello-support/docs/README.md from the hello-support VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Hello Support #\n\nA quick setup for a support app in VTEX.\n\n### Installation ###\n```\n$ git clone https://github.com/vtex/hello-support support-app\n$ cd support-app\n$ vtex link\n```\n\nBe sure to have [VTEX's toolbelt](https://github.com/vtex/toolbelt)\ninstalled.\n\n### FAQ ###\n\n#### What is a support app? ####\n\nA support app is one of the simplest examples of apps\nthat run in VTEX IO.\n\nIts purpose is to declare groups of users in the VTEX\nplatform, and which roles they have access to.\n\nIf someone decides to install this app in a workspace,\nthey will be giving these groups of users the declared\naccesses.\n\nThis enables app developers to support users having \ntrouble with the app functionality. \nSay you're an app developer (which, by reading this, \nyou probably are) and a customer is having trouble with \nsome feature your apps have. By publishing a support app\nwith the adequate policies, you can ask your customer\nto install it and help them hand-in-hand on their own\nworkspace!\n\n#### How does it work? ####\n\nBy adding the `support` builder into the `builders`\nobject in `manifest.json`, the app declares that\nit contains a `support.json`.\n\nThe `support.json` file must be like the example given:\n\n```json\n[\n {\n \"role\": \"app-developer\",\n \"policies\": [\n {\n \"name\": \"read-write-workspace\"\n },\n {\n \"name\": \"read-workspace-info\"\n },\n {\n \"name\": \"link-apps\",\n \"attrs\": {\n \"appName\": \"vendor.appName\"\n },\n \"reason\": \"Insert reason here.\"\n },\n {\n \"name\": \"read-workspace-apps\"\n },\n ]\n },\n {\n \"role\": \"support-agent\",\n \"policies\": [\n {\n \"name\": \"read-workspace-info\"\n },\n {\n \"name\": \"read-workspace-apps\"\n }\n ]\n }\n]\n```\n\nwhere `groupName` is the name of the group of people\nthat will have access to such policies,\nand `policies` is an array of object of policies, which can\nhave\n```ts\n{\n name: string,\n reason: string,\n attrs: object,\n}\n```\n\nThis allows VTEX IO infrastructure to get this apps' support\npolicies and add to someone assuming a support role **with the\nsame vendor as the support app**. That is, having a support\napp with vendor A linked to your workspace doesn't mean\na Support Agent from vendor B will have access to those policies.\n\n\n```" } ]
code_hello-support_2b255039
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of hello-support/support/support.json from the hello-support VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n[\n {\n \"role\": \"app-developer\",\n \"policies\": [\n {\n \"name\": \"read-write-workspace\"\n },\n {\n \"name\": \"read-workspace-info\"\n },\n {\n \"name\": \"read-workspace-apps\"\n },\n {\n \"name\": \"link-apps\",\n \"attrs\": {\n \"appName\": \"vendor.appName\"\n },\n \"reason\": \"Insert reason here.\"\n }\n ]\n },\n {\n \"role\": \"support-agent\",\n \"policies\": [\n {\n \"name\": \"read-workspace-info\"\n },\n {\n \"name\": \"read-workspace-apps\"\n }\n ]\n }\n]\n\n```" } ]
code_checkout-graphql_69b59d61
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/docs/README.md from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Checkout GraphQL\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\n## Warning 🚨\n\nThis repository contains **experimental** code for VTEX Checkout and should **not** be used in production.\n\nThis code is \"experimental\" for various reasons:\n- Some are not tested as rigorously as the main code.\n- Some are tested but not maintained.\n- It can suffer from significant changes (breaking changes) without further notice.\n\n**Use it at your own risk!** ☠️\n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n <tr>\n <td align=\"center\"><a href=\"http://carafizi.com/\"><img src=\"https://avatars3.githubusercontent.com/u/51974587?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Gabriel Carafizi</b></sub></a><br /><a href=\"https://github.com/vtex-apps/checkout-graphql/commits?author=carafizi1\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n\n```" } ]
code_checkout-graphql_0093541f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/graphql/schema.graphql from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Query {\n getCardSessionId: String @withAuthMetrics\n orderForm(orderFormId: ID, refreshOutdatedData: Boolean): OrderForm!\n @noCache\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @withSegment\n checkoutProfile(email: String!): CheckoutProfile @withAuthMetrics @noCache\n shippingSLA(\n items: [ShippingItem]\n postalCode: String\n country: String\n ): Shipping\n @cacheControl(scope: SEGMENT, maxAge: MEDIUM)\n @withAuthMetrics\n @withSegment\n @withOrderFormId\n @withOwnerId\n}\n\ntype Mutation {\n addToCart(\n orderFormId: ID\n items: [ItemInput]\n marketingData: MarketingDataInput\n salesChannel: String\n allowedOutdatedData: [String!]\n ): OrderForm! @withAuthMetrics @withOrderFormId @withOwnerId @withSegment @noCache\n\n updateItems(\n orderFormId: ID\n orderItems: [ItemInput]\n splitItem: Boolean = true\n allowedOutdatedData: [String!]\n ): OrderForm! @withAuthMetrics @withOrderFormId @withOwnerId @noCache\n\n addItemOffering(orderFormId: ID, offeringInput: OfferingInput): OrderForm!\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @noCache\n removeItemOffering(orderFormId: ID, offeringInput: OfferingInput): OrderForm!\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @noCache\n\n addBundleItemAttachment(\n orderFormId: ID\n bundleItemAttachmentInput: BundleItemAttachmentInput\n ): OrderForm! @withAuthMetrics @withOrderFormId @withOwnerId @noCache\n removeBundleItemAttachment(\n orderFormId: ID\n bundleItemAttachmentInput: BundleItemAttachmentInput\n ): OrderForm! @withAuthMetrics @withOrderFormId @withOwnerId @noCache\n\n insertCoupon(orderFormId: ID, text: String): OrderForm!\n @withOrderFormId\n @withOwnerId\n @noCache\n\n estimateShipping(orderFormId: ID, address: AddressInput): OrderForm!\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @noCache\n\n selectDeliveryOption(orderFormId: ID, deliveryOptionId: String): OrderForm!\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @noCache\n\n selectPickupOption(\n orderFormId: ID\n pickupOptionId: String\n itemId: String\n ): OrderForm! @withAuthMetrics @withOrderFormId @withOwnerId @noCache\n\n \"\"\"\n Changes the currently selected address in the shipping data\n of the OrderForm\n \"\"\"\n updateSelectedAddress(orderFormId: ID, input: AddressInput!): OrderForm!\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @noCache\n\n savePaymentToken(\n orderFormId: ID\n paymentTokens: [PaymentToken]\n ): SavePaymentTokenPayload @withAuthMetrics @withOrderFormId @withOwnerId @noCache\n\n updateOrderFormProfile(orderFormId: ID, input: UserProfileInput!): OrderForm!\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @noCache\n\n updateClientPreferencesData(\n orderFormId: ID\n input: ClientPreferencesDataInput!\n ): OrderForm! @withAuthMetrics @withOrderFormId @withOwnerId @noCache\n\n updateOrderFormPayment(orderFormId: ID, input: PaymentDataInput!): OrderForm!\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @noCache\n\n setManualPrice(orderFormId: ID, input: ManualPriceInput!): OrderForm!\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @noCache\n\n updateItemsOrdination(\n orderFormId: ID\n ascending: Boolean!\n criteria: ItemsOrdinationCriteria!\n ): OrderForm! @withAuthMetrics @withOrderFormId @withOwnerId @noCache\n\n clearOrderFormMessages(orderFormId: ID): OrderForm!\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @noCache\n\n updateOrderFormOpenTextField(\n orderFormId: ID\n input: OrderFormOpenTextInput!\n ): OrderForm! @withAuthMetrics @withOrderFormId @withOwnerId @noCache\n\n updateOrderFormMarketingData(input: MarketingDataInput!): OrderForm!\n @withAuthMetrics\n @withOrderFormId\n @withOwnerId\n @noCache\n}\n\n```" } ]
code_checkout-graphql_783bf46e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/graphql/directives.graphql from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ndirective @withSegment on FIELD_DEFINITION\n\ndirective @withOrderFormId on FIELD_DEFINITION\n\ndirective @withOwnerId on FIELD_DEFINITION\n\ndirective @noCache on FIELD_DEFINITION\n\ndirective @withAuthMetrics on FIELD_DEFINITION\n\n```" } ]
code_checkout-graphql_dc8053c9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/service.json from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 258,\n \"ttl\": 43200,\n \"timeout\": 30,\n \"minReplicas\": 2,\n \"maxReplicas\": 120,\n \"workers\": 4,\n \"cpu\": 30\n}\n\n```" } ]
code_checkout-graphql_9c5b8c76
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/typings.d.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOContext as ioContext } from '@vtex/api'\nimport { Context as KoaContext } from 'koa'\n\nimport CheckoutDataSource from './dataSources/checkout'\n\ndeclare global {\n interface IOContext extends ioContext {\n params: {\n [param: string]: string\n }\n route: {\n id: string\n declarer: string\n params: {\n [param: string]: string\n }\n }\n }\n\n interface ServiceContext extends KoaContext {\n vtex: IOContext\n dataSources: SearchGraphQLDataSources\n originalPath: string\n }\n\n interface SearchGraphQLDataSources {\n checkout: CheckoutDataSource\n }\n\n type Resolver<TArgs = any, TRoot = any> = (\n root: TRoot,\n args: TArgs,\n context: ServiceContext\n ) => Promise<any>\n}\n\nexport {}\n\n```" } ]
code_checkout-graphql_1818ffeb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/package.json from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.checkout-graphql\",\n \"version\": \"0.67.1\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"atob\": \"^2.1.2\",\n \"dataloader\": \"^2.0.0\",\n \"graphql\": \"^14.0.0\",\n \"graphql-tools\": \"^4.0.0\",\n \"lodash\": \"^4.17.15\",\n \"ramda\": \"^0.26.1\",\n \"set-cookie-parser\": \"^2.5.1\"\n },\n \"devDependencies\": {\n \"@types/atob\": \"^2.1.2\",\n \"@types/cookie\": \"^0.3.3\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/lodash\": \"^4.14.138\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@types/set-cookie-parser\": \"^2.4.2\",\n \"@vtex/api\": \"6.46.1\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"@vtex/tsconfig\": \"^0.2.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.checkout-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-graphql@0.60.0/public/@types/vtex.checkout-graphql\",\n \"vtex.country-data-settings\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.country-data-settings@0.4.0/public/@types/vtex.country-data-settings\",\n \"vtex.graphql-server\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.graphql-server@1.66.4/public/_types/react\",\n \"vtex.messages\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.messages@1.64.0/public/@types/vtex.messages\"\n }\n}\n\n```" } ]
code_checkout-graphql_b7927cb8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/index.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { LRUCache, Service, RecorderState } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { schemaDirectives } from './directives'\nimport { resolvers } from './resolvers'\n\nconst THREE_SECONDS_MS = 3 * 1000\nconst TEN_SECONDS_MS = 10 * 1000\n\n// Segments are small and immutable.\nconst MAX_SEGMENT_CACHE = 10000\nconst segmentCache = new LRUCache<string, any>({ max: MAX_SEGMENT_CACHE })\nmetrics.trackCache('segment', segmentCache)\n\nconst searchGraphQLCache = new LRUCache<string, any>({ max: 5000 })\nmetrics.trackCache('searchGraphQL', searchGraphQLCache)\n\nexport default new Service<Clients, RecorderState, CustomContext>({\n clients: {\n implementation: Clients,\n options: {\n checkout: {\n timeout: TEN_SECONDS_MS,\n },\n default: {\n retries: 2,\n timeout: THREE_SECONDS_MS,\n },\n searchGraphQL: {\n memoryCache: searchGraphQLCache,\n timeout: THREE_SECONDS_MS,\n },\n segment: {\n memoryCache: segmentCache,\n timeout: THREE_SECONDS_MS,\n },\n countryDataSettings: {\n timeout: THREE_SECONDS_MS,\n },\n },\n },\n graphql: {\n resolvers,\n schemaDirectives,\n },\n})\n\n```" } ]
code_checkout-graphql_00e85cc8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/graphql/types/Profile.graphql from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ninput UserProfileInput {\n email: String\n firstName: String\n lastName: String\n document: String\n phone: String\n documentType: String\n isCorporate: Boolean\n corporateName: String\n tradeName: String\n corporateDocument: String\n stateInscription: String\n}\n\ntype UserProfile {\n email: String!\n firstName: String!\n lastName: String!\n document: String\n documentType: String\n phone: String\n corporateName: String\n tradeName: String\n corporateDocument: String\n stateInscription: String\n corporatePhone: String\n isCorporate: Boolean!\n profileCompleteOnLoading: String\n profileErrorOnLoading: String\n customerClass: String\n}\n\ntype CheckoutProfile {\n userProfileId: String\n profileProvider: String\n availableAccounts: [AvailableAccount!]!\n availableAddresses: [Address!]!\n userProfile: UserProfile\n}\n\n```" } ]
code_checkout-graphql_b8109afe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/graphql/types/OrderForm.graphql from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype OrderForm {\n id: ID!\n items: [Item!]!\n canEditData: Boolean!\n loggedIn: Boolean!\n userProfileId: String\n userType: UserType\n shipping: Shipping!\n marketingData: MarketingData!\n totalizers: [Totalizer!]!\n value: Float!\n messages: OrderFormMessages!\n paymentData: PaymentData!\n clientProfileData: ClientData\n clientPreferencesData: ClientPreferencesData\n allowManualPrice: Boolean\n openTextField: OpenTextField\n storePreferencesData: StorePreferencesData\n customData: CustomData\n}\n\ntype CustomData {\n customApps: [CustomApp!]!\n}\n\nscalar CustomFieldsObject\n\ntype CustomApp {\n id: ID!\n major: Int!\n fields: CustomFieldsObject!\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\ntype OpenTextField {\n value: String\n}\n\nenum UserType {\n CALL_CENTER_OPERATOR\n STORE_USER\n}\n\ntype MarketingData {\n utmCampaign: String\n utmMedium: String\n utmSource: String\n utmiCampaign: String\n utmiPart: String\n utmiPage: String\n coupon: String\n marketingTags: [String!]\n}\n\ninput MarketingDataInput {\n utmCampaign: String\n utmMedium: String\n utmSource: String\n utmiCampaign: String\n utmiPart: String\n utmiPage: String\n coupon: String\n marketingTags: [String!]\n}\n\ntype Totalizer {\n id: String!\n name: String @translatableV2\n value: Float!\n}\n\ntype OrderFormMessages {\n couponMessages: [Message!]!\n generalMessages: [Message!]!\n}\n\ntype Message {\n code: String\n status: String\n text: String @translatableV2\n}\n\ntype ClientPreferencesData {\n locale: String\n optInNewsletter: Boolean\n}\n\ninput ClientPreferencesDataInput {\n optInNewsletter: Boolean\n locale: String\n}\n\nenum ItemsOrdinationCriteria {\n name\n add_time\n}\n\ninput OrderFormOpenTextInput {\n value: String\n}\n\n```" } ]
code_checkout-graphql_a3493d93
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/graphql/types/Item.graphql from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nscalar InputValues\n\n\"\"\"\nProductCategoriesObject is a Record<string, string>, in the following format:\n{ '<categoryNumber>': '<categoryName>' }\n\"\"\"\nscalar ProductCategoriesObject\n\ntype Item {\n additionalInfo: ItemAdditionalInfo\n assemblyOptions: AssemblyOptionItem\n availability: String\n attachmentOfferings: [AttachmentOffering!]!\n attachments: [Attachment!]!\n bundleItems: [Item!]!\n detailUrl: String\n id: ID!\n imageUrls: ImageUrls\n listPrice: Float\n manualPrice: Float\n measurementUnit: String\n modalType: String\n name: String @translatableV2\n offerings: [Offering!]!\n options: [AssemblyOptionType]\n parentAssemblyBinding: String\n parentItemIndex: Int\n price: Float\n productCategories: ProductCategoriesObject\n productCategoryIds: String\n productSpecificationGroups: [ProductSpecificationGroups]!\n \"\"\"\n Id of the product. Can be null if included inside bundle items.\n \"\"\"\n productId: String\n productRefId: String\n quantity: Float!\n refId: String\n \"\"\"\n Product's seller. Can be null if included inside bundle items.\n \"\"\"\n seller: String\n sellingPrice: Float\n sellingPriceWithAssemblies: Float\n skuName: String @translatableV2\n skuSpecifications: [SKUSpecification!]!\n uniqueId: String!\n unitMultiplier: Float\n priceTags: [PriceTag!]!\n isGift: 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 ImageUrls {\n at1x: String!\n at2x: String!\n at3x: String!\n}\n\ntype AssemblyOptionItem {\n added: [AddedOptionItem]!\n removed: [RemovedOptionItem]!\n parentPrice: Float\n}\n\ntype RemovedOptionItem {\n initialQuantity: Int\n removedQuantity: Int\n name: String @translatableV2\n}\n\ntype AddedOptionItem {\n item: Item\n compositionItem: CompositionItem\n normalizedQuantity: Int\n choiceType: String\n extraQuantity: Int\n}\n\ntype CompositionItem {\n id: ID\n minQuantity: Int\n maxQuantity: Int\n initialQuantity: Int\n priceTable: String\n seller: String\n}\n\ntype ItemAdditionalInfo {\n brandName: String @translatableV2\n}\n\ntype SKUSpecification {\n fieldName: String @translatableV2\n fieldValues: [String]! @translatableV2\n}\n\ntype ProductSpecification {\n name: String @translatableV2\n originalName: String @translatableV2\n values: [String]! @translatableV2\n}\n\ntype ProductSpecificationGroups {\n name: String @translatableV2\n originalName: String @translatableV2\n specifications: [ProductSpecification]!\n}\n\ntype AssemblyOptionType {\n assemblyId: String!\n id: ID\n quantity: Int\n seller: String\n inputValues: InputValues\n options: [AssemblyOptionType!]\n}\n\ntype Offering {\n id: String!\n name: String! @translatableV2\n price: Int!\n type: String!\n attachmentOfferings: [AttachmentOffering!]!\n}\n\nscalar AttachmentSchema\n\ntype AttachmentOffering {\n name: String @translatableV2\n required: Boolean\n schema: AttachmentSchema\n}\n\nscalar AttachmentContent\n\ntype Attachment {\n name: String @translatableV2\n content: AttachmentContent\n}\n\ninput ItemInput {\n id: Int\n index: Int\n quantity: Float\n seller: ID\n uniqueId: String\n inputValues: InputValues\n options: [AssemblyOptionInput]\n}\n\ninput AssemblyOptionInput {\n assemblyId: String!\n id: ID\n quantity: Int\n seller: String\n inputValues: InputValues\n options: [AssemblyOptionInput!]\n}\n\nscalar OfferingInfo\n\ninput OfferingInput {\n itemIndex: Int!\n offeringId: String!\n offeringInfo: OfferingInfo\n}\n\ninput BundleItemAttachmentInput {\n itemIndex: Int!\n bundleItemId: String!\n attachmentName: String!\n attachmentContent: AttachmentContent!\n}\n\ninput ManualPriceInput {\n itemIndex: Int!\n price: Float!\n}\n\ntype PriceTag {\n identifier: String\n isPercentual: Boolean\n name: String\n ratesAndBenefitsIdentifier: RatesAndBenefitsIdentifier\n rawValue: Float\n value: Float\n}\n\ntype RatesAndBenefitsIdentifier {\n description: String\n featured: Boolean\n id: String\n matchedParameters: MatchedParameters\n name: String\n}\n\nscalar MatchedParameters\n\n```" } ]
code_checkout-graphql_57588900
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/graphql/types/Payment.graphql from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Installment {\n count: Int!\n hasInterestRate: Boolean\n interestRate: Int\n value: Float\n total: Float!\n}\n\ntype InstallmentOption {\n paymentSystem: String!\n bin: String\n paymentName: String\n paymentGroupName: String\n value: Float!\n installments: [Installment!]!\n}\n\ntype Validator {\n regex: String\n mask: String\n cardCodeRegex: String\n cardCodeMask: String\n weights: [Int]\n useCvv: Boolean\n useExpirationDate: Boolean\n useCardHolderName: Boolean\n useBillingAddress: Boolean\n}\n\ntype PaymentSystem {\n id: String!\n name: String!\n groupName: String!\n validator: Validator\n stringId: String!\n requiresDocument: Boolean!\n isCustom: Boolean!\n description: String\n requiresAuthentication: Boolean\n dueDate: String\n}\n\ntype Payment {\n paymentSystem: String\n bin: String\n accountId: String\n tokenId: String\n installments: Int\n referenceValue: Float\n value: Float\n}\n\ntype AvailableAccount {\n accountId: String!\n paymentSystem: String!\n paymentSystemName: String!\n cardNumber: String!\n bin: String!\n}\n\ntype PaymentData {\n installmentOptions: [InstallmentOption!]!\n paymentSystems: [PaymentSystem!]!\n payments: [Payment!]!\n availableAccounts: [AvailableAccount!]!\n isValid: Boolean!\n}\n\ntype SavePaymentTokenPayload {\n status: String\n}\n\ninput PaymentInput {\n hasDefaultBillingAddress: Boolean\n installmentsInterestRate: Int\n paymentSystem: String\n bin: String\n accountId: String\n tokenId: String\n installments: Int\n referenceValue: Int\n value: Int\n}\n\ninput PaymentDataInput {\n payments: [PaymentInput!]!\n}\n\ninput PaymentToken {\n creditCardToken: String!\n paymentSystem: String!\n}\n\n```" } ]
code_checkout-graphql_db4a8386
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/graphql/types/ClientProfile.graphql from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype ClientData {\n email: String\n firstName: String\n lastName: String\n document: String\n documentType: String\n phone: String\n corporateName: String\n tradeName: String\n corporateDocument: String\n stateInscription: String\n corporatePhone: String\n isCorporate: Boolean\n profileCompleteOnLoading: Boolean\n profileErrorOnLoading: Boolean\n customerClass: String\n isValid: Boolean!\n}\n\n```" } ]
code_checkout-graphql_d7ce0f98
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/graphql/types/Shipping.graphql from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Shipping {\n countries: [String]\n deliveryOptions: [DeliveryOption!]!\n pickupOptions: [PickupOption!]!\n selectedAddress: Address\n availableAddresses: [Address]\n isValid: Boolean!\n}\n\ntype DeliveryOption {\n id: String!\n deliveryChannel: String!\n price: Int!\n estimate: String!\n isSelected: Boolean!\n}\n\ntype PickupOption {\n id: String!\n address: Address!\n deliveryChannel: String!\n price: Int!\n estimate: String!\n isSelected: Boolean!\n friendlyName: String! @translatableV2\n additionalInfo: String @translatableV2\n storeDistance: Float\n transitTime: String\n businessHours: [BusinessHour!]!\n}\n\ntype BusinessHour {\n dayNumber: String!\n closed: Boolean!\n closingTime: String!\n openingTime: String!\n}\n\ntype Address {\n addressId: ID\n addressType: AddressType\n city: String\n complement: String\n country: String\n geoCoordinates: [Float]\n neighborhood: String\n number: String\n postalCode: String\n receiverName: String\n reference: String\n state: String\n street: String\n isDisposable: Boolean\n}\n\ninput AddressInput {\n addressId: ID\n addressType: AddressType\n addressQuery: String\n city: String\n complement: String\n country: String\n geoCoordinates: [Float]\n neighborhood: String\n number: String\n postalCode: String\n receiverName: String\n reference: String\n state: String\n street: String\n isDisposable: Boolean\n}\n\ninput ShippingItem {\n id: String\n quantity: String\n seller: String\n}\n\nenum AddressType {\n residential\n commercial\n inStore\n giftRegistry\n pickup\n search\n}\n\n```" } ]
code_checkout-graphql_cff7f7f3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/directives/withOwnerId.ts from the checkout-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 field.resolve = async (root: any, args: any, ctx: Context, info: any) => {\n const checkoutOwnerId = getOwnerIdFromCookie(ctx.cookies)\n ctx.vtex.ownerId = checkoutOwnerId\n return resolve(root, args, ctx, info)\n }\n }\n}\n\n```" } ]
code_checkout-graphql_e195e319
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/directives/authorization.ts from the checkout-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 const vtexRCSessionIdv7 =\n ctx.cookies.get('VtexRCSessionIdv7') ?? ctx.get('VtexRCSessionIdv7')\n\n if (!vtexRCSessionIdv7) {\n logger.warn({\n message: 'No RCSessionIdv7 cookie found',\n userAgent,\n forwardedFor,\n forwardedHost,\n forwardedPath,\n origin,\n vtexCaller,\n })\n }\n}\n\nexport class AuthorizationMetrics extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\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_checkout-graphql_faf056bd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/directives/withSegment.ts from the checkout-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 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_checkout-graphql_1ecfbaab
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/directives/withOrderFormId.ts from the checkout-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 field.resolve = async (root: any, args: any, ctx: Context, info: any) => {\n const checkoutOrderFormId = getOrderFormIdFromCookie(ctx.cookies)\n ctx.vtex.orderFormId = checkoutOrderFormId\n return resolve(root, args, ctx, info)\n }\n }\n}\n\n```" } ]
code_checkout-graphql_e4a08ab0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/directives/noCache.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n\nimport { defaultFieldResolver, GraphQLField } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nexport class NoCache extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n field.resolve = async (root: any, args: any, ctx: Context, info: any) => {\n const {\n graphql: { cacheControl }\n } = ctx\n\n cacheControl.noCache = true\n cacheControl.noStore = true\n\n return resolve(root, args, ctx, info)\n }\n }\n}\n\n```" } ]
code_checkout-graphql_96acd6d7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/directives/index.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AuthorizationMetrics } from './authorization'\nimport { WithSegment } from './withSegment'\nimport { WithOrderFormId } from './withOrderFormId'\nimport { NoCache } from './noCache'\nimport { WithOwnerId } from './withOwnerId'\n\nexport const schemaDirectives = {\n withAuthMetrics: AuthorizationMetrics,\n withSegment: WithSegment,\n withOrderFormId: WithOrderFormId,\n withOwnerId: WithOwnerId,\n noCache: NoCache,\n}\n\n```" } ]
code_checkout-graphql_f1ad6b86
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/clients/countryDataSettings.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { InstanceOptions, IOContext, AppClient } from '@vtex/api'\n\nexport class CountryDataSettings extends AppClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super('vtex.country-data-settings@0.x', ctx, {\n ...options,\n headers: {\n ...options?.headers,\n ...(ctx.storeUserAuthToken\n ? { VtexIdclientAutCookie: ctx.storeUserAuthToken }\n : null),\n },\n })\n }\n\n public getCountrySettings(\n country: string\n ): Promise<CountryDataSchema | null> {\n return this.http.get(`/country-settings/${country}`)\n }\n\n public getAllCountriesSettings(): Promise<CountryDataSchema[]> {\n return this.http.get('/country-settings/')\n }\n}\n\n```" } ]
code_checkout-graphql_a39c965c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/clients/graphqlServer.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n AppClient,\n GraphQLClient,\n InstanceOptions,\n IOContext,\n RequestConfig,\n Serializable,\n} from '@vtex/api'\n\nexport class GraphQLServer extends AppClient {\n protected graphql: GraphQLClient\n\n constructor(ctx: IOContext, opts?: InstanceOptions) {\n super('vtex.graphql-server@1.x', ctx, opts)\n this.graphql = new GraphQLClient(this.http)\n }\n\n public query = async <TResponse extends Serializable, TArgs extends object>(\n query: string,\n variables: any,\n extensions: any,\n config: RequestConfig\n ) => {\n return this.graphql.query<TResponse, TArgs>(\n {\n extensions,\n query,\n variables,\n },\n {\n ...config,\n params: {\n ...config.params,\n locale: this.context.locale,\n },\n url: '/graphql',\n }\n )\n }\n}\n\n```" } ]
code_checkout-graphql_15a7e7ba
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/clients/checkout.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InstanceOptions,\n IOContext,\n IOResponse,\n JanusClient,\n RequestConfig,\n} from '@vtex/api'\nimport { UserProfileInput } from 'vtex.checkout-graphql'\nimport { OWNERSHIP_COOKIE } from '../constants'\nimport { forwardCheckoutCookies } from '../resolvers/orderForm'\n\nimport { checkoutCookieFormat, ownershipCookieFormat, statusToError } from '../utils'\n\nexport interface SimulationData {\n country: string\n items: Array<{ id: string; quantity: number | string; seller: string }>\n postalCode?: string\n isCheckedIn?: boolean\n priceTables?: string[]\n marketingData?: Record<string, string>\n}\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 },\n })\n }\n\n public savePaymentToken = (paymentTokens: any) => {\n return this.post(\n this.routes.savePaymentToken(this.getChannelQueryString()),\n paymentTokens,\n { metric: 'checkout-save-payment' }\n )\n }\n\n public getPaymentSession = () => {\n return this.get<PaymentSession>(this.routes.getPaymentSession())\n }\n\n public addItem = (\n orderFormId: string,\n items: Array<Omit<OrderFormItemInput, 'uniqueId' | 'index' | 'options'>>,\n salesChannel?: string,\n allowedOutdatedData?: string[]\n ) =>\n this.patch<CheckoutOrderForm>(\n this.routes.addItem(\n orderFormId,\n this.getChannelQueryString(salesChannel)\n ),\n {\n orderItems: items,\n allowedOutdatedData,\n },\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 = (\n orderFormId: string,\n orderItems: Array<Omit<OrderFormItemInput, 'id'>>,\n splitItem: boolean,\n allowedOutdatedData?: string[]\n ) =>\n this.patch<CheckoutOrderForm>(\n this.routes.addItem(orderFormId, this.getChannelQueryString(undefined)),\n {\n orderItems,\n noSplitItem: !splitItem,\n allowedOutdatedData,\n },\n { metric: 'checkout-updateItems' }\n )\n\n public updateOrderFormIgnoreProfile = (\n orderFormId: string,\n ignoreProfileData: boolean\n ) =>\n this.patch(\n this.routes.orderFormProfile(orderFormId),\n { ignoreProfileData },\n { metric: 'checkout-updateOrderFormIgnoreProfile' }\n )\n\n public updateOrderFormPayment = (\n orderFormId: string,\n paymentData: PaymentDataInput\n ) =>\n this.post<CheckoutOrderForm>(\n this.routes.attachmentsData(orderFormId, 'paymentData'),\n paymentData,\n { metric: 'checkout-updateOrderFormPayment' }\n )\n\n public updateOrderFormProfile = async (\n orderFormId: string,\n fields: UserProfileInput,\n ctx: Context,\n ) => {\n const { data, headers } = await this.postRaw<CheckoutOrderForm>(\n this.routes.attachmentsData(orderFormId, 'clientProfileData'),\n fields,\n { metric: 'checkout-updateOrderFormProfile' }\n )\n forwardCheckoutCookies(headers, ctx, [OWNERSHIP_COOKIE])\n return data\n }\n\n public updateOrderFormShipping = (orderFormId: string, shipping: any) =>\n this.post<CheckoutOrderForm>(\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<CheckoutOrderForm>(\n this.routes.attachmentsData(orderFormId, 'marketingData'),\n marketingData,\n { metric: 'checkout-updateOrderFormMarketingData' }\n )\n\n public updateOrderFormClientPreferencesData = (\n orderFormId: string,\n clientPreferencesData: CheckoutClientPreferencesData\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<CheckoutOrderForm>(\n this.routes.attachmentsData(orderFormId, 'clientPreferencesData'),\n filteredClientPreferencesData,\n { metric: 'checkout-updateOrderFormClientPreferencesData' }\n )\n }\n\n public updateOrderFromOpenTextField = (\n orderFromId: string,\n openTextField: OpenTextField\n ) =>\n this.post<CheckoutOrderForm>(\n this.routes.attachmentsData(orderFromId, 'openTextField'),\n openTextField,\n { metric: 'checkout-updateOrderFromOpenTextField' }\n )\n\n public updateSubscriptionDataField = (\n orderFormId: string,\n subscriptionData: SubscriptionData\n ) =>\n this.post<CheckoutOrderForm>(\n this.routes.attachmentsData(orderFormId, 'subscriptionData'),\n subscriptionData,\n { metric: 'checkout-updateSubscriptionDataField' }\n )\n\n public addAssemblyOptions = async (\n orderFormId: string,\n itemId: string | number,\n assemblyOptionsId: string,\n body: any\n ) =>\n this.post(\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(\n this.routes.assemblyOptions(orderFormId, itemId, assemblyOptionsId),\n { metric: 'checkout-removeAssemblyOptions', data: body }\n )\n\n public addItemOffering = async (\n orderFormId: string,\n itemIndex: number,\n offeringId: string,\n offeringInfo?: any\n ) =>\n this.post<CheckoutOrderForm>(\n this.routes.offering(orderFormId, itemIndex),\n { id: offeringId, offeringInfo },\n { metric: 'checkout-addItemOffering' }\n )\n\n public removeItemOffering = async (\n orderFormId: string,\n itemIndex: number,\n offeringId: string\n ) =>\n this.post<CheckoutOrderForm>(\n this.routes.removeOffering(orderFormId, itemIndex, offeringId),\n { Id: offeringId },\n { metric: 'checkout-removeItemOffering' }\n )\n\n public addBundleItemAttachment = async (\n orderFormId: string,\n itemIndex: number,\n bundleItemId: string,\n attachmentName: string,\n attachmentContent: any\n ) =>\n this.post<CheckoutOrderForm>(\n this.routes.bundleItemAttachment(\n orderFormId,\n itemIndex,\n bundleItemId,\n attachmentName\n ),\n { content: attachmentContent },\n { metric: 'checkout-addBundleItemAttachment' }\n )\n\n public removeBundleItemAttachment = async (\n orderFormId: string,\n itemIndex: number,\n bundleItemId: string,\n attachmentName: string,\n attachmentContent: any\n ) =>\n this.delete<CheckoutOrderForm>(\n this.routes.bundleItemAttachment(\n orderFormId,\n itemIndex,\n bundleItemId,\n attachmentName\n ),\n {\n metric: 'checkout-removeBundleItemAttachment',\n data: { content: attachmentContent },\n }\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, refreshOutdatedData = false) => {\n return this.post<CheckoutOrderForm>(\n this.routes.orderForm(\n orderFormId,\n this.getOrderFormQueryString(refreshOutdatedData)\n ),\n {},\n { metric: 'checkout-orderForm' }\n )\n }\n\n public orderFormRaw = (orderFormId?: string, refreshOutdatedData = false) => {\n return this.postRaw<CheckoutOrderForm>(\n this.routes.orderForm(\n orderFormId,\n this.getOrderFormQueryString(refreshOutdatedData)\n ),\n {},\n { metric: 'checkout-orderForm' }\n )\n }\n\n public orders = () =>\n this.get(this.routes.orders, { metric: 'checkout-orders' })\n\n public simulation = (simulation: SimulationData) =>\n this.post(\n this.routes.simulation(this.getChannelQueryString()),\n simulation,\n {\n metric: 'checkout-simulation',\n }\n )\n\n public insertCoupon = (orderFormId: string, coupon: string) =>\n this.post<CheckoutOrderForm>(this.routes.insertCoupon(orderFormId), {\n text: coupon,\n })\n\n public clearMessages = (orderFormId: string) =>\n this.post<CheckoutOrderForm>(this.routes.clearMessages(orderFormId), {})\n\n public getProfile = (email: string) =>\n this.get<CheckoutProfile>(this.routes.profile(email))\n\n public updateItemsOrdination = (\n orderFormId: string,\n ascending: boolean,\n criteria: string\n ) =>\n this.post<CheckoutOrderForm>(\n this.routes.updateItemsOrdination(orderFormId),\n {\n ascending,\n criteria,\n },\n { metric: 'checkout-orderForm' }\n )\n\n protected get = <T>(url: string, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\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 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 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 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 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 return this.http.put<T>(url, data, config).catch(statusToError) as Promise<\n T\n >\n }\n\n private getCommonHeaders = () => {\n const { orderFormId, ownerId } = (this.context as unknown) as CustomIOContext\n const checkoutCookie = orderFormId ? checkoutCookieFormat(orderFormId) : ''\n const ownershipCookie = ownerId ? ownershipCookieFormat(ownerId) : ''\n return {\n Cookie: `${checkoutCookie}${ownershipCookie}vtex_segment=${this.context.segmentToken};vtex_session=${this.context.sessionToken};`,\n }\n }\n\n private getChannelQueryString = (salesChannel?: string) => {\n const { segment } = (this.context as unknown) as CustomIOContext\n const channel = salesChannel ?? segment?.channel\n const queryString = channel ? `?sc=${channel}` : ''\n return queryString\n }\n\n private getOrderFormQueryString = (refreshOutdatedData?: boolean) => {\n if (refreshOutdatedData)\n return `?refreshOutdatedData=${refreshOutdatedData}`\n\n return ''\n }\n\n private get routes() {\n const base = '/api/checkout/pub'\n return {\n addItem: (orderFormId: string, queryString: string) =>\n `${base}/orderForm/${orderFormId}/items${queryString}`,\n assemblyOptions: (\n orderFormId: string,\n itemId: string | number,\n assemblyOptionsId: string\n ) =>\n `${base}/orderForm/${orderFormId}/items/${itemId}/assemblyOptions/${encodeURI(\n assemblyOptionsId\n )}`,\n attachmentsData: (orderFormId: string, field: string) =>\n `${base}/orderForm/${orderFormId}/attachments/${field}`,\n cancelOrder: (orderFormId: string) =>\n `${base}/orders/${orderFormId}/user-cancel-request`,\n checkin: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/checkIn`,\n clearMessages: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/messages/clear`,\n insertCoupon: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/coupons`,\n orderForm: (orderFormId?: string, queryString?: string) =>\n `${base}/orderForm/${orderFormId ?? ''}${queryString}`,\n orderFormCustomData: (\n orderFormId: string,\n appId: string,\n field: string\n ) => `${base}/orderForm/${orderFormId}/customData/${appId}/${field}`,\n orders: `${base}/orders`,\n orderFormProfile: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/profile`,\n profile: (email: string) => `${base}/profiles/?email=${email}`,\n simulation: (queryString: string) =>\n `${base}/orderForms/simulation${queryString}`,\n updateItems: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/items/update`,\n offering: (orderFormId: string, itemIndex: number) =>\n `${base}/orderForm/${orderFormId}/items/${itemIndex}/offerings`,\n removeOffering: (\n orderFormId: string,\n itemIndex: number,\n offeringId: string\n ) =>\n `${base}/orderForm/${orderFormId}/items/${itemIndex}/offerings/${offeringId}/remove`,\n bundleItemAttachment: (\n orderFormId: string,\n itemIndex: number,\n bundleItemId: string,\n attachmentName: string\n ) =>\n `${base}/orderForm/${orderFormId}/items/${itemIndex}/bundles/${bundleItemId}/attachments/${attachmentName}`,\n savePaymentToken: (queryString: string) =>\n `${base}/current-user/payment-tokens/${queryString}`,\n getPaymentSession: () => `${base}/payment-session`,\n updateItemsOrdination: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/itemsOrdination`,\n }\n }\n}\n\nexport class CheckoutNoCookies extends Checkout {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super({ ...ctx, orderFormId: null, ownerId: null } as any, { ...options, headers: {} })\n }\n}\n\n```" } ]
code_checkout-graphql_e8cd7c7d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/clients/checkoutAdmin.ts from the checkout-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 { checkoutCookieFormat, statusToError } from '../utils'\n\nexport interface SimulationData {\n country: string\n items: Array<{ id: string; quantity: number | string; seller: string }>\n postalCode?: string\n isCheckedIn?: boolean\n priceTables?: string[]\n marketingData?: Record<string, string>\n}\n\nexport class CheckoutAdmin extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n ...(ctx.adminUserAuthToken\n ? { VtexIdClientAutCookie: ctx.adminUserAuthToken }\n : null),\n },\n })\n }\n\n public orderForm = () => {\n return this.post<CheckoutOrderForm>(\n this.routes.orderForm,\n {},\n { metric: 'checkout-orderForm' }\n )\n }\n\n public setManualPrice = (\n orderFormId: string,\n itemIndex: number,\n price: number\n ) =>\n this.put<CheckoutOrderForm>(\n this.routes.setManualPrice(orderFormId, itemIndex),\n {\n price,\n }\n )\n\n protected post = <T>(url: string, data?: any, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n return this.http.post<T>(url, data, config).catch(statusToError) as Promise<\n T\n >\n }\n\n protected put = <T>(url: string, data?: any, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n return this.http.put<T>(url, data, config).catch(statusToError) as Promise<\n T\n >\n }\n\n private getCommonHeaders = () => {\n const { orderFormId } = (this.context as unknown) as CustomIOContext\n const checkoutCookie = orderFormId ? checkoutCookieFormat(orderFormId) : ''\n return {\n Cookie: `${checkoutCookie}vtex_segment=${this.context.segmentToken};vtex_session=${this.context.sessionToken};`,\n }\n }\n\n private get routes() {\n const base = '/api/checkout/pub'\n return {\n orderForm: `${base}/orderForm`,\n setManualPrice: (orderFormId: string, itemIndex: number) =>\n `${base}/orderForm/${orderFormId}/items/${itemIndex}/price`,\n }\n }\n}\n\n```" } ]
code_checkout-graphql_e60f7610
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/clients/session.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { JanusClient } from '@vtex/api'\nimport parseCookie from 'set-cookie-parser'\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 if (vtexIdCookies.account) {\n cookies += `${vtexIdCookies.account};`\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 parsedSetCookies = parseCookie.parse(setCookie)\n for (const parsed of parsedSetCookies) {\n if (parsed.name === SESSION_COOKIE) {\n return parsed.value\n }\n }\n }\n\n return null\n}\n\n```" } ]
code_checkout-graphql_446a8db6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/clients/index.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport { Checkout, CheckoutNoCookies } from './checkout'\nimport { SearchGraphQL } from './searchGraphQL'\nimport { Session } from './session'\nimport { CountryDataSettings } from './countryDataSettings'\nimport { CheckoutAdmin } from './checkoutAdmin'\n\nexport class Clients extends IOClients {\n public get checkout() {\n return this.getOrSet('checkout', Checkout)\n }\n\n public get checkoutNoCookies() {\n return this.getOrSet('checkoutNoCookies', CheckoutNoCookies)\n }\n\n public get searchGraphQL() {\n return this.getOrSet('searchGraphQL', SearchGraphQL)\n }\n\n public get customSession() {\n return this.getOrSet('customSession', Session)\n }\n\n public get countryDataSettings() {\n return this.getOrSet('countryDataSettings', CountryDataSettings)\n }\n\n public get checkoutAdmin() {\n return this.getOrSet('checkoutAdmin', CheckoutAdmin)\n }\n}\n\n```" } ]
code_checkout-graphql_6c9148f2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/__fixtures__/shipping.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AddressType, DELIVERY, PICKUP_IN_POINT } from '../constants'\nimport { EMPTY_ORDER_FORM } from './orderForm'\nimport { Clients } from '../clients'\n\nconst SLA = {\n deliveryIds: [],\n deliveryWindow: null,\n listPrice: 0,\n lockTTL: null,\n pickupDistance: 0,\n pickupPointId: null,\n pickupStoreInfo: {\n additionalInfo: null,\n address: null,\n dockId: null,\n friendlyName: null,\n isPickupStore: false,\n },\n polygonName: null,\n shippingEstimateDate: null,\n tax: 0,\n}\n\nconst pickupSLA = {\n ...SLA,\n availableDeliveryWindows: [],\n deliveryChannel: PICKUP_IN_POINT,\n id: 'pickup-SLA',\n name: 'pickup-SLA',\n price: 100,\n shippingEstimate: '1d',\n}\n\nconst deliverySLA = {\n ...SLA,\n availableDeliveryWindows: [],\n deliveryChannel: DELIVERY,\n id: 'delivery-SLA',\n name: 'delivery-SLA',\n price: 100,\n shippingEstimate: '1db',\n}\n\nconst deliveryIdOne = {\n courierId: '1',\n warehouseId: '1',\n dockId: '1',\n courierName: 'PAC',\n quantity: 1,\n}\n\nconst deliveryId = {\n courierId: '1',\n warehouseId: '1a105fe',\n dockId: '1fd8f86',\n courierName: 'PAC',\n quantity: 1,\n}\n\nconst deliverySLAWithDeliveryIdOne = {\n ...SLA,\n availableDeliveryWindows: [],\n deliveryChannel: DELIVERY,\n id: 'delivery-SLA',\n name: 'delivery-SLA',\n price: 100,\n shippingEstimate: '1db',\n deliveryIds: [deliveryIdOne],\n}\n\nconst deliverySLAWithDeliveryId = {\n ...SLA,\n availableDeliveryWindows: [],\n deliveryChannel: DELIVERY,\n id: 'delivery-SLA',\n name: 'delivery-SLA',\n price: 100,\n shippingEstimate: '1db',\n deliveryIds: [deliveryId],\n}\n\nconst deliverySLAExpress = {\n ...SLA,\n availableDeliveryWindows: [],\n deliveryChannel: DELIVERY,\n id: 'delivery-SLA-Express',\n name: 'delivery-SLA-Express',\n price: 600,\n shippingEstimate: '1h',\n}\n\nconst scheduledDeliverySLA = {\n ...SLA,\n availableDeliveryWindows: [{}],\n deliveryChannel: DELIVERY,\n id: 'scheduled-delivery-SLA',\n name: 'scheduled-delivery-SLA',\n price: 100,\n shippingEstimate: '1bd',\n}\n\nexport const deliveryAddress = {\n addressId: 'test',\n addressType: AddressType.RESIDENTIAL,\n city: '',\n complement: '',\n country: 'BRA',\n geoCoordinates: [],\n neighborhood: '',\n number: '',\n postalCode: '222071060',\n receiverName: '',\n reference: null,\n state: '',\n street: '',\n}\n\nexport const ORDER_FORM_WITH_PICKUPS = {\n ...EMPTY_ORDER_FORM,\n shippingData: {\n address: null,\n availableAddresses: [deliveryAddress],\n logisticsInfo: [\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId',\n itemIndex: 0,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: deliverySLA.id,\n shipsTo: ['BRA', 'GBR'],\n slas: [deliverySLA, pickupSLA],\n },\n ],\n pickupPoints: [],\n selectedAddresses: [deliveryAddress],\n },\n}\n\nexport const ORDER_FORM_WITH_SCHEDULED_DELIVERY = {\n ...EMPTY_ORDER_FORM,\n shippingData: {\n address: null,\n availableAddresses: [deliveryAddress],\n logisticsInfo: [\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId',\n itemIndex: 0,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: deliverySLA.id,\n shipsTo: ['BRA', 'GBR'],\n slas: [deliverySLA, scheduledDeliverySLA],\n },\n ],\n pickupPoints: [],\n selectedAddresses: [deliveryAddress],\n },\n}\n\nexport const ORDER_FORM_WITH_SCHEDULED_DELIVERY_AND_PICKUPS = {\n ...EMPTY_ORDER_FORM,\n shippingData: {\n address: null,\n availableAddresses: [deliveryAddress],\n logisticsInfo: [\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId',\n itemIndex: 0,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: deliverySLA.id,\n shipsTo: ['BRA', 'GBR'],\n slas: [deliverySLA, scheduledDeliverySLA, pickupSLA],\n },\n ],\n pickupPoints: [],\n selectedAddresses: [deliveryAddress],\n },\n}\n\nexport const ORDER_FORM_WITH_DIFFERENT_SLAS_BETWEEN_LOGISTICS_INFO = {\n ...EMPTY_ORDER_FORM,\n shippingData: {\n address: null,\n availableAddresses: [deliveryAddress],\n logisticsInfo: [\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId',\n itemIndex: 0,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: deliverySLA.id,\n shipsTo: ['BRA', 'GBR'],\n slas: [deliverySLA],\n },\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId',\n itemIndex: 1,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: deliverySLA.id,\n shipsTo: ['BRA', 'GBR'],\n slas: [deliverySLA, deliverySLAExpress],\n },\n ],\n pickupPoints: [],\n selectedAddresses: [deliveryAddress],\n },\n}\n\nexport const ORDER_FORM_WITH_DUPLICATED_SLAS_WITH_DIFFERENT_DELIVERY_IDS = {\n ...EMPTY_ORDER_FORM,\n shippingData: {\n address: null,\n availableAddresses: [deliveryAddress],\n logisticsInfo: [\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId',\n itemIndex: 0,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: deliverySLA.id,\n shipsTo: ['BRA', 'GBR'],\n slas: [deliverySLAWithDeliveryId],\n },\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId',\n itemIndex: 1,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: deliverySLA.id,\n shipsTo: ['BRA', 'GBR'],\n slas: [deliverySLAWithDeliveryIdOne, deliverySLAExpress],\n },\n ],\n pickupPoints: [],\n selectedAddresses: [deliveryAddress],\n },\n}\n\nexport const ORDER_FORM_WITH_EMPTY_LOGISTICS_INFO = {\n ...EMPTY_ORDER_FORM,\n shippingData: {\n address: null,\n availableAddresses: [deliveryAddress],\n logisticsInfo: [\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId',\n itemIndex: 0,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: null,\n shipsTo: ['BRA', 'GBR'],\n slas: [],\n },\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId',\n itemIndex: 1,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: null,\n shipsTo: ['BRA', 'GBR'],\n slas: [],\n },\n ],\n pickupPoints: [],\n selectedAddresses: [deliveryAddress],\n },\n}\n\nexport const ORDER_FORM_WITH_UNAVAILABLE_ITEM_LOGISTICS_INFO = {\n ...EMPTY_ORDER_FORM,\n shippingData: {\n address: null,\n availableAddresses: [deliveryAddress],\n logisticsInfo: [\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId',\n itemIndex: 0,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: deliverySLA.id,\n shipsTo: ['BRA', 'GBR'],\n slas: [],\n },\n {\n addressId: deliveryAddress.addressId,\n deliveryChannels: [{ id: DELIVERY }, { id: PICKUP_IN_POINT }],\n itemId: 'testId2',\n itemIndex: 0,\n selectedDeliveryChannel: DELIVERY,\n selectedSla: deliverySLA.id,\n shipsTo: ['BRA', 'GBR'],\n slas: [deliverySLA, pickupSLA],\n },\n ],\n pickupPoints: [],\n selectedAddresses: [deliveryAddress],\n },\n}\n\nexport const ORDER_FORM_WITH_EMPTY_SHIPPING_DATA = {\n ...EMPTY_ORDER_FORM,\n}\n\nexport const clients = ({\n checkout: {\n updateOrderFormShipping: jest.fn(),\n },\n} as unknown) as Clients\n\n```" } ]
code_checkout-graphql_b4ff8780
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/__fixtures__/orderForm.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const EMPTY_ORDER_FORM = {\n allowManualPrice: false,\n canEditData: true,\n checkedInPickupPointId: null,\n clientPreferencesData: {\n locale: 'en',\n optinNewsLetter: null,\n },\n clientProfileData: null,\n commercialConditionData: null,\n customData: null,\n giftRegistryData: null,\n hooksData: null,\n ignoreProfileData: false,\n invoiceData: null,\n isCheckedIn: false,\n itemMetadata: {\n items: [],\n },\n items: [],\n itemsOrdination: null,\n loggedIn: false,\n marketingData: null,\n messages: [],\n openTextField: null,\n orderFormId: 'test',\n paymentData: {\n availableAccounts: [],\n availableTokens: [],\n giftCardMessages: [],\n giftCards: [],\n installmentOptions: [],\n paymentSystems: [],\n payments: [],\n },\n ratesAndBenefitsData: {\n rateAndBenefitsIdentifiers: [],\n teaser: [],\n },\n salesChannel: '1',\n selectableGifts: [],\n sellers: [],\n shippingData: {\n address: null,\n availableAddresses: [],\n logisticsInfo: [],\n pickupPoints: [],\n selectedAddresses: [],\n },\n storeId: '1',\n storePreferencesData: {\n countryCode: 'BRA',\n currencyCode: 'BRL',\n currencyFormatInfo: {\n currencyDecimalDigits: 2,\n currencyDecimalSeparator: ',',\n currencyGroupSeparator: '.',\n currencyGroupSize: 3,\n startsWithCurrencySymbol: true,\n },\n currencyLocale: 'pt-BR',\n currencySymbol: 'R$',\n saveUserData: false,\n timeZone: 'test',\n },\n subscriptionData: null,\n totalizers: [],\n userProfileId: null,\n userType: null,\n value: 1200,\n}\n\n```" } ]
code_checkout-graphql_a54fa52e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/constants/index.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport enum AddressType {\n RESIDENTIAL = 'residential',\n COMMERCIAL = 'commercial',\n INSTORE = 'inStore',\n GIFT_REGISTRY = 'giftRegistry',\n PICKUP = 'pickup',\n SEARCH = 'search',\n}\n\n// Cookies\nexport const CHECKOUT_COOKIE = 'checkout.vtex.com'\nexport const ASPXAUTH_COOKIE = '.ASPXAUTH'\nexport const OWNERSHIP_COOKIE = 'CheckoutOrderFormOwnership'\n\n// Delivery channels\nexport const DELIVERY = 'delivery'\nexport const PICKUP_IN_POINT = 'pickup-in-point'\n\nexport const VTEX_SESSION = 'vtex_session'\n\n```" } ]
code_checkout-graphql_c6a22120
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/typings/global.d.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ServiceContext, SegmentData, ParamsContext } from '@vtex/api'\nimport { Attachment } from 'vtex.checkout-graphql'\n\nimport { Clients } from '../clients'\n\ndeclare global {\n type Context = ServiceContext<Clients, RecorderState, CustomContext>\n\n interface CustomContext extends ParamsContext {\n cookie: string\n dataSources: SearchGraphQLDataSources\n originalPath: string\n vtex: CustomIOContext\n graphql: {\n cacheControl: {\n noStore: boolean\n noCache: boolean\n }\n }\n }\n\n interface CustomIOContext extends IOContext {\n segment?: SegmentData\n orderFormId?: string\n ownerId?: string\n }\n\n interface OrderFormMarketingData {\n utmCampaign?: string\n utmMedium?: string\n utmSource?: string\n utmiCampaign?: string\n utmiPart?: string\n utmipage?: string\n marketingTags?: string\n coupon?: string\n }\n\n interface CheckoutAddress {\n addressId: string\n addressType: string\n city: string | null\n complement: string | null\n country: string\n geoCoordinates: number[]\n neighborhood: string | null\n number: string | null\n postalCode: string | null\n receiverName: string | null\n reference: string | null\n state: string | null\n street: string | null\n isDisposable: boolean\n }\n\n type AddressFields = keyof CheckoutAddress\n\n interface CountryDataSchema {\n countryISO: string\n addressFields: AddressFieldsSchema\n phone: PhoneSchema\n }\n\n interface AddressFieldsSchema {\n [field in AddressField]: AddressFieldSchema\n postalCode?: AddressFieldSchema & PostalCodeSchema\n }\n\n interface PostalCodeSchema {\n forgottenURL?: string\n }\n\n interface AddressFieldSchema {\n label: string\n name?: AddressField | 'addressType'\n hidden?: boolean\n maxLength?: number\n size?: string\n required?: boolean\n autoComplete?: string\n optionsCaption?: string\n options?: AddressOption[]\n elementName?: string\n mask?: string\n }\n\n interface AddressOption {\n label: string\n value: string\n }\n\n interface BusinessHour {\n DayOfWeek: number\n ClosingTime: string\n OpeningTime: string\n }\n\n interface NormalizedBusinessHour {\n dayNumber: string | number\n closed: boolean\n closingTime: string\n openingTime: string\n }\n\n interface PhoneSchema {\n countryCode: string\n mask?: string\n pattern: string\n }\n\n interface OrderFormItem {\n id: string\n name: string\n detailUrl: string\n imageUrl: string\n skuName: string\n quantity: number\n uniqueId: string\n productId: string\n refId: string\n ean: string\n priceValidUntil: string\n price: number\n tax: number\n listPrice: number\n sellingPrice: number\n rewardValue: number\n isGift: boolean\n parentItemIndex: number | null\n parentAssemblyBinding: string | null\n productCategoryIds: string\n priceTags: string[]\n manualPrice: number\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 productSpecificationGroups: ProductSpecificationGroup[]\n productRefId: string\n seller: string\n sellerChain: string[]\n availability: string\n unitMultiplier: number\n skuSpecifications: SKUSpecification[]\n priceDefinition: {\n calculatedSellingPrice: number\n sellingPrices: SellingPrice[]\n total: number\n }\n attachments?: Attachment[]\n }\n\n interface SellingPrice {\n quantity: number\n value: number\n }\n\n interface SKUSpecification {\n fieldName: string\n fieldValues: string[]\n }\n\n interface ProductSpecification {\n name: string\n originalName: string\n values: string[]\n }\n\n interface ProductSpecificationGroup {\n name: string\n originalName: string\n specifications: ProductSpecification[]\n }\n\n interface CompositionItem {\n id: string\n minQuantity: number\n maxQuantity: number\n initialQuantity: number\n priceTable: string\n seller: string\n }\n\n interface Composition {\n minQuantity: number\n maxQuantity: number\n items: CompositionItem[]\n }\n\n interface AssemblyOption {\n id: string\n name: string\n composition: Composition | null\n }\n\n interface SubscriptionDataEntry {\n executionCount: number\n itemIndex: number\n plan: {\n frequency: {\n interval: number\n periodicity: 'YEAR' | 'MONTH' | 'WEEK' | 'DAY'\n }\n type: string\n validity: {}\n }\n }\n\n interface SubscriptionData {\n subscriptions: SubscriptionDataEntry[]\n }\n\n interface 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 }\n interface AddedItem {\n choiceType: string\n compositionItem: CompositionItem\n extraQuantity: number\n item: OrderFormItem\n normalizedQuantity: number\n }\n\n interface RemovedItem {\n initialQuantity: number\n name: string\n removedQuantity: number\n }\n\n interface CheckoutOrderForm {\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<{\n id: string\n name: string\n value: number\n }>\n shippingData: ShippingData | null\n clientProfileData: ClientProfileData | null\n paymentData: PaymentData\n marketingData: OrderFormMarketingData | null\n sellers: Array<{\n id: string\n name: string\n logo: string\n }>\n clientPreferencesData: {\n locale: string\n optinNewsLetter: any | null\n }\n commercialConditionData: any | null\n storePreferencesData: {\n countryCode: string\n currencyCode: string\n currencyFormatInfo: {\n currencyDecimalDigits: number\n currencyDecimalSeparator: string\n currencyGroupSeparator: string\n currencyGroupSize: number\n startsWithCurrencySymbol: boolean\n }\n currencyLocale: string\n currencySymbol: string\n saveUserData: boolean\n timeZone: string\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: SubscriptionData | null\n itemsOrdination: any | null\n }\n\n interface CheckoutProfile {\n userProfileId: string\n profileProvider: string\n availableAccounts: string[]\n availableAddresses: CheckoutAddress[]\n userProfile: any\n }\n\n interface ClientProfileData {\n email: string\n firstName: string\n lastName: string\n document: string\n documentType: string\n phone: string\n corporateName: string\n tradeName: string\n corporateDocument: string\n stateInscription: string\n corporatePhone: string\n isCorporate: boolean\n profileCompleteOnLoading: boolean\n profileErrorOnLoading: boolean\n customerClass: string\n }\n\n interface PaymentData {\n installmentOptions: Array<{\n paymentSystem: string\n bin: string | null\n paymentName: string | null\n paymentGroupName: string | null\n value: number\n installments: Array<{\n count: number\n hasInterestRate: false\n interestRate: number\n value: number\n total: number\n sellerMerchantInstallments: Array<{\n count: number\n hasInterestRate: false\n interestRate: number\n value: number\n total: number\n }>\n }>\n }>\n paymentSystems: Array<{\n id: string\n name: string\n groupName: string\n validator: {\n regex: string\n mask: string\n cardCodeRegex: string\n cardCodeMask: string\n weights: number[]\n useCvv: boolean\n useExpirationDate: boolean\n useCardHolderName: boolean\n useBillingAddress: boolean\n }\n stringId: string\n template: string\n requiresDocument: boolean\n isCustom: boolean\n description: string | null\n requiresAuthentication: boolean\n dueDate: string\n availablePayments: any | null\n }>\n payments: any[]\n giftCards: any[]\n giftCardMessages: any[]\n availableAccounts: any[]\n availableTokens: any[]\n }\n\n interface ShippingData {\n address: CheckoutAddress | null\n logisticsInfo: LogisticsInfo[]\n selectedAddresses: CheckoutAddress[]\n availableAddresses: CheckoutAddress[]\n pickupPoints: PickupPoint[]\n }\n\n interface PickupPoint {\n friendlyName: string\n address: CheckoutAddress\n additionalInfo: string\n id: string\n businessHours: BusinessHour[]\n }\n\n interface LogisticsInfo {\n addressId: string | null\n deliveryChannels: DeliveryChannel[]\n itemId: string\n itemIndex: number\n shipsTo: string[]\n slas: SLA[]\n selectedDeliveryChannel: string | null\n selectedSla: string | null\n }\n\n interface DeliveryChannel {\n id: string\n }\n\n interface SLA {\n id: string\n deliveryChannel: string\n name: string\n deliveryIds: DeliveryId[]\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 | null\n polygonName: string | null\n transitTime: string | null\n }\n\n interface DeliveryId {\n courierId: string\n warehouseId: string\n dockId: string\n courierName: string\n quantity: number\n }\n\n interface ShippingDataRequest {\n logisticsInfo: LogisticsInfo[]\n selectedAddresses: CheckoutAddress[]\n clearAddressIfPostalCodeNotFound?: boolean\n }\n\n interface OrderFormItemInput {\n id?: number\n index?: number\n quantity?: number\n seller?: string\n uniqueId?: string\n options?: AssemblyOptionInput[]\n }\n\n interface AssemblyOptionInput {\n id: string\n quantity: number\n assemblyId: string\n seller: string\n inputValues: Record<string, string>\n options?: AssemblyOptionInput[]\n }\n\n interface Item {\n additionalInfo: {\n brandName: string\n brandId: string\n offeringInfo: any | null\n offeringType: any | null\n offeringTypeId: any | null\n }\n availability: string\n detailUrl: string\n id: string\n imageUrls?: {\n at1x: string\n at2x: string\n at3x: string\n }\n isGift: boolean\n listPrice: number\n measurementUnit: string\n name: string\n price: number\n productId: string\n productCategories: Record<string, string>\n productCategoryIds: string\n productSpecificationGroups: ProductSpecificationGroup[]\n productRefId: string\n quantity: number\n sellingPrice: number\n skuName: string\n skuSpecifications: SKUSpecification[]\n uniqueId: string\n }\n\n interface OrderForm {\n items: Item[]\n canEditData: boolean\n shipping?: Shipping\n marketingData: OrderFormMarketingData | null\n totalizers: Array<{\n id: string\n name: string\n value: number\n }>\n value: number\n messages: OrderFormMessages\n }\n\n interface Shipping {\n availableAddresses: CheckoutAddress[]\n countries: string[]\n deliveryOptions: DeliveryOption[]\n pickupOptions: PickupOption[]\n selectedAddress: CheckoutAddress | null\n }\n\n interface DeliveryOption {\n id: string\n price: number\n estimate: string\n isSelected: boolean\n }\n\n interface PickupOption {\n id: string\n price: number\n estimate: string\n isSelected: boolean\n }\n\n interface OrderFormMessages {\n couponMessages: Message[]\n generalMessages: Message[]\n }\n\n interface Message {\n code: string\n text: string\n status: string\n }\n\n interface PaymentSession {\n id: string\n name: string\n expiresAt: string\n }\n\n interface SavePaymentTokenPayload {\n status: string\n }\n\n interface UserProfileInput {\n email?: string\n firstName?: string\n lastName?: string\n document?: string\n phone?: string\n documentType?: string\n isCorporate?: boolean\n corporateName?: string\n tradeName?: string\n corporateDocument?: string\n stateInscription?: string\n }\n\n interface ClientPreferencesDataInput {\n optInNewsletter?: boolean\n locale?: string\n }\n\n interface CheckoutClientPreferencesData {\n optinNewsLetter?: boolean\n locale?: string\n }\n\n interface PaymentInput {\n paymentSystem?: string\n bin?: string\n accountId?: string\n tokenId?: string\n installments?: number\n referenceValue?: number\n value?: number\n }\n\n interface PaymentDataInput {\n payments: PaymentInput[]\n }\n\n interface ItemsOrdinationArgs {\n ascending: boolean\n criteria: ItemsOrdinationCriteria\n }\n\n interface OpenTextField {\n value?: string\n }\n}\n\n```" } ]
code_checkout-graphql_445469b7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/validation.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/**\n * Validates the shipping portion of the orderForm\n */\nexport const isShippingValid = async (\n orderForm: CheckoutOrderForm,\n shipping: Omit<Shipping, 'selectedAddress'> &\n Partial<Pick<Shipping, 'selectedAddress'>>,\n ctx: Context\n) => {\n const selectedShippingOption =\n shipping.deliveryOptions?.some(\n deliveryOption => deliveryOption?.isSelected\n ) || shipping.pickupOptions?.some(pickupOption => pickupOption?.isSelected)\n\n if (!(shipping.selectedAddress && selectedShippingOption)) {\n return false\n }\n\n if (!orderForm.canEditData && !shipping.selectedAddress?.isDisposable) {\n return true\n }\n\n const address = shipping.selectedAddress\n\n if (address == null) {\n return false\n }\n\n if (!address.country) {\n return false\n }\n\n const countrySettings = await ctx.clients.countryDataSettings.getCountrySettings(\n address.country\n )\n\n if (!countrySettings) {\n return false\n }\n\n const fields = countrySettings.addressFields\n\n for (const [field, fieldSchema] of Object.entries(fields) as Array<\n [AddressFields, AddressFieldSchema]\n >) {\n const fieldValue = address[field]\n\n if (fieldSchema.required && !fieldValue) {\n return false\n }\n\n if (\n fieldSchema.maxLength &&\n fieldValue != null &&\n typeof fieldValue !== 'boolean' &&\n fieldValue.length > fieldSchema.maxLength\n ) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * Validates the profile portion of the orderForm\n */\nexport const isProfileValid = async (\n orderForm: CheckoutOrderForm,\n profile: ClientProfileData,\n ctx: Context\n) => {\n if (\n !profile ||\n !profile.firstName ||\n !profile.lastName ||\n !profile.phone ||\n !profile.document ||\n !profile.documentType\n ) {\n return false\n }\n\n if (!orderForm.canEditData) {\n return true\n }\n\n const countriesSettings = await ctx.clients.countryDataSettings.getAllCountriesSettings()\n\n const phoneCountry = countriesSettings.find(countrySetting => {\n return profile.phone.startsWith(`+${countrySetting.phone.countryCode}`)\n })\n\n if (!phoneCountry) {\n return false\n }\n\n return profile.phone.match(phoneCountry.phone.pattern) !== null\n}\n\n/**\n * Validates the payment portion of the orderForm\n */\nexport const isPaymentValid = (payment: PaymentData) => {\n return !!(payment.payments.length > 0)\n}\n\n```" } ]
code_checkout-graphql_7eed5fa9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/pickup.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst DAYS_ORDER = [1, 2, 3, 4, 5, 6, 0]\nconst MONDAY_INDEX = 0\nconst FRIDAY_INDEX = 4\n\nconst normalizeBusinessHours = (businessHours: BusinessHour[]) => {\n return DAYS_ORDER.map(dayNumber => {\n const day = businessHours.find(bh => dayNumber === bh.DayOfWeek)\n\n const dayObject = day && {\n closed: false,\n openingTime: day.OpeningTime,\n closingTime: day.ClosingTime,\n }\n\n return {\n dayNumber,\n closed: true,\n openingTime: '',\n closingTime: '',\n ...(dayObject ?? {}),\n }\n })\n}\n\nconst doesWeekDaysHaveTheSameHours = (\n businessHours: NormalizedBusinessHour[]\n) => {\n const weekDays = businessHours.slice(MONDAY_INDEX, FRIDAY_INDEX)\n\n const firstOpeningTime = weekDays[0].openingTime\n const firstClosingTime = weekDays[0].closingTime\n\n for (let i = 1; i < weekDays.length; i++) {\n const currentDay = weekDays[i]\n\n if (\n currentDay.openingTime !== firstOpeningTime ||\n currentDay.closingTime !== firstClosingTime\n ) {\n return false\n }\n }\n\n return true\n}\n\nconst condenseWeekDaysHours = (businessHours: NormalizedBusinessHour[]) => {\n return businessHours.reduce(\n (\n acc: NormalizedBusinessHour[],\n businessHour: NormalizedBusinessHour,\n index: number\n ) => {\n if (index >= MONDAY_INDEX && index <= FRIDAY_INDEX) {\n if (index === MONDAY_INDEX) {\n return acc.concat({\n dayNumber: '1to5',\n closed: businessHour.closed,\n openingTime: businessHour.openingTime,\n closingTime: businessHour.closingTime,\n })\n }\n return acc\n }\n\n return acc.concat(businessHour)\n },\n []\n )\n}\n\nexport function formatBusinessHoursList(businessHours: BusinessHour[]) {\n const normalizedBusinessHours = normalizeBusinessHours(businessHours)\n\n const weekDaysHaveTheSameHours = doesWeekDaysHaveTheSameHours(\n normalizedBusinessHours\n )\n\n if (weekDaysHaveTheSameHours) {\n return condenseWeekDaysHours(normalizedBusinessHours)\n }\n\n return normalizedBusinessHours\n}\n\n```" } ]
code_checkout-graphql_ab036ca0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/args.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface OrderFormIdArgs {\n orderFormId?: string\n}\n\n```" } ]
code_checkout-graphql_13815ef7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/shipping.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n// eslint-disable-next-line no-restricted-imports\nimport uniqBy from 'lodash/uniqBy'\n\nimport {\n addressHasGeocoordinates,\n filterDeliveryOptions,\n getSelectedAddress,\n} from './address'\nimport {\n getFormattedDeliveryOptions,\n hasDeliveryOption,\n} from './delivery-options'\nimport { Clients } from '../clients'\nimport { DELIVERY, PICKUP_IN_POINT } from '../constants'\nimport { formatBusinessHoursList } from './pickup'\n\nexport const getShippingData = (\n address: CheckoutAddress,\n logisticsInfo: LogisticsInfo[] | null\n) => {\n const selectedAddresses = [address]\n const hasGeocoordinates = addressHasGeocoordinates(address)\n const logisticsInfoWithAddress =\n logisticsInfo?.map((li: LogisticsInfo) => ({\n ...li,\n addressId: address.addressId,\n })) ?? []\n\n const requestPayload = {\n logisticsInfo: logisticsInfoWithAddress,\n selectedAddresses,\n ...(hasGeocoordinates ? { clearAddressIfPostalCodeNotFound: false } : {}),\n }\n\n return requestPayload\n}\n\nexport const selectShippingOption = ({\n shippingData,\n slaId,\n itemId,\n deliveryChannel,\n}: {\n shippingData: ShippingData | null\n slaId: string\n itemId?: string\n deliveryChannel: string\n}) => {\n const logisticsInfoWithSelectedDeliveryOption =\n shippingData?.logisticsInfo.map((li: LogisticsInfo) => {\n return {\n ...li,\n selectedDeliveryChannel: deliveryChannel,\n selectedSla:\n hasDeliveryOption(li.slas, slaId) &&\n (itemId != null ? li.itemId === itemId : true)\n ? slaId\n : li.selectedSla,\n }\n }) ?? []\n\n const deliveryAddress = getSelectedAddress(\n shippingData?.selectedAddresses ?? []\n )\n\n if (!deliveryAddress) {\n return shippingData\n }\n\n return getShippingData(\n deliveryAddress,\n logisticsInfoWithSelectedDeliveryOption\n )\n}\n\nexport const selectAddress = ({\n shippingData,\n address,\n}: {\n shippingData: ShippingData | null\n address: CheckoutAddress\n}): ShippingData | null => {\n if (!shippingData) {\n return null\n }\n\n return {\n ...shippingData,\n selectedAddresses: [address],\n }\n}\n\nexport const getShippingInfo = async ({\n clients,\n orderForm,\n}: {\n clients: Clients\n orderForm: Pick<\n CheckoutOrderForm,\n 'shippingData' | 'totalizers' | 'orderFormId' | 'value'\n >\n}) => {\n const logisticsInfo = orderForm.shippingData?.logisticsInfo ?? []\n const pickupPoints = orderForm.shippingData?.pickupPoints ?? []\n\n const countries = Array.from(\n new Set(logisticsInfo.flatMap(item => item.shipsTo)).values()\n )\n\n const availableAddresses = orderForm.shippingData?.availableAddresses ?? []\n\n const selectedAddress =\n orderForm.shippingData &&\n getSelectedAddress(orderForm.shippingData.selectedAddresses)\n\n const availableItemsLogisticsInfo = logisticsInfo\n ? logisticsInfo.filter((item: LogisticsInfo) => item.slas.length > 0)\n : []\n\n const deliveryOptions = uniqBy(\n availableItemsLogisticsInfo.flatMap((item: LogisticsInfo) => item.slas),\n 'id'\n )\n\n // Since at this time shipping does not show scheduled delivery/pickup\n // we are filtering from them results.\n // Also we will filter deliveryOptions which does not apply to all LogisticsInfo.\n const filteredDeliveryOptions = filterDeliveryOptions(\n deliveryOptions,\n availableItemsLogisticsInfo\n )\n\n const updatedDeliveryOptions = getFormattedDeliveryOptions(\n filteredDeliveryOptions,\n availableItemsLogisticsInfo\n )\n\n const selectedDeliveryOption = updatedDeliveryOptions.find(\n option => option.isSelected && option.deliveryChannel === DELIVERY\n )\n\n const shippingTotalizer = orderForm.totalizers.find(\n totalizer => totalizer.id === 'Shipping'\n )\n\n if (\n selectedDeliveryOption &&\n shippingTotalizer &&\n selectedDeliveryOption.price !== shippingTotalizer.value\n ) {\n const newShippingData = selectShippingOption({\n slaId: selectedDeliveryOption.id,\n deliveryChannel: DELIVERY,\n shippingData: orderForm.shippingData,\n })\n\n await clients.checkout.updateOrderFormShipping(\n orderForm.orderFormId,\n newShippingData\n )\n\n const difference = selectedDeliveryOption.price - shippingTotalizer.value\n shippingTotalizer.value = selectedDeliveryOption.price\n orderForm.value += difference\n }\n\n return {\n availableAddresses,\n countries,\n deliveryOptions: updatedDeliveryOptions.filter(\n ({ deliveryChannel }) => deliveryChannel === DELIVERY\n ),\n pickupOptions: updatedDeliveryOptions\n .filter(({ deliveryChannel }) => deliveryChannel === PICKUP_IN_POINT)\n .map(pickupOption => {\n return {\n id: pickupOption.id,\n address: pickupOption.sla.pickupStoreInfo.address,\n deliveryChannel: pickupOption.sla.deliveryChannel,\n price: pickupOption.price,\n estimate: pickupOption.estimate,\n isSelected: pickupOption.isSelected,\n friendlyName: pickupOption.sla.pickupStoreInfo.friendlyName,\n additionalInfo: pickupOption.sla.pickupStoreInfo.additionalInfo,\n storeDistance: pickupOption.sla.pickupDistance,\n transitTime: pickupOption.sla.transitTime,\n businessHours: formatBusinessHoursList(\n pickupPoints.find(\n (pp: PickupPoint) => pp.id === pickupOption.pickupPointId\n )?.businessHours ?? []\n ),\n }\n }),\n selectedAddress,\n }\n}\n\n```" } ]
code_checkout-graphql_4cbb13d6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/delivery-options.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { PICKUP_IN_POINT } from '../constants/index'\n\nexport function getFormattedDeliveryOptions(\n deliveryOptions: SLA[],\n logisticsInfo: LogisticsInfo[] | null\n) {\n return deliveryOptions.map(sla => {\n let price = 0\n\n const isSelected =\n logisticsInfo?.some(li => li.selectedSla === sla.id) ?? false\n\n logisticsInfo?.forEach(li => {\n const currentSla = li.slas.find(liSla => liSla.id === sla.id)\n\n if (currentSla) {\n price += currentSla.price\n }\n })\n\n return {\n estimate: sla.shippingEstimate,\n id: sla.id,\n isSelected,\n price,\n deliveryChannel: sla.deliveryChannel,\n sla,\n ...(sla.deliveryChannel === PICKUP_IN_POINT\n ? { pickupPointId: sla.pickupPointId }\n : {}),\n }\n })\n}\n\nexport function hasDeliveryOption(\n deliveryOptions: SLA[],\n deliveryOptionId: string\n) {\n return deliveryOptions.some(\n (deliveryOption: SLA) => deliveryOption.id === deliveryOptionId\n )\n}\n\n```" } ]
code_checkout-graphql_818b84d6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/subscriptions.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst FREQUENCY_PATTERN = /(\\d{1,3})?\\s*(\\w*?)(?:$|s|ly)/i\n\nconst SUBSCRIPTION_PREFIX = `vtex.subscription`\nconst SUBSCRIPTION_KEY_PREFIX = `${SUBSCRIPTION_PREFIX}.key`\n\nconst SUBSCRIPTION_KEY_FREQUENCY = `${SUBSCRIPTION_KEY_PREFIX}.frequency`\n\nexport function parseFrequency(frequency: string) {\n const match = frequency.trim().match(FREQUENCY_PATTERN)\n\n if (!match) {\n return\n }\n\n const [, count = '1', type] = match\n\n if (!type) return\n\n return {\n interval: +count,\n periodicity: type.toUpperCase(),\n } as SubscriptionDataEntry['plan']['frequency']\n}\n\nexport function generateSubscriptionDataEntry(\n subscriptionsFromAssemblyOptions: Array<{\n itemIndex: number\n options: AssemblyOptionInput[]\n }>\n): SubscriptionDataEntry[] {\n const planType = 'RECURRING_PAYMENT'\n const defaultExecutionCount = 0\n\n const subscriptionDataEntries = subscriptionsFromAssemblyOptions.map(item => {\n const { itemIndex, options } = item\n\n const subscriptionFrequencyOption = options.find(option =>\n Boolean(option.inputValues[SUBSCRIPTION_KEY_FREQUENCY])\n )\n\n if (!subscriptionFrequencyOption) {\n return null\n }\n\n const planFrequency = parseFrequency(\n subscriptionFrequencyOption.inputValues[SUBSCRIPTION_KEY_FREQUENCY]\n )\n\n if (!planFrequency) {\n return null\n }\n\n const subscriptionPlan = {\n frequency: planFrequency,\n type: planType,\n validity: {},\n }\n\n return {\n executionCount: defaultExecutionCount,\n itemIndex,\n plan: subscriptionPlan,\n }\n })\n\n // Remove null entries caused by invalid frequencies\n const validSubscriptionDataEntries = subscriptionDataEntries.filter(Boolean)\n\n return validSubscriptionDataEntries as SubscriptionDataEntry[]\n}\n\n```" } ]
code_checkout-graphql_de23d456
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/index.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\nimport { AxiosError } from 'axios'\nimport { parse } from 'set-cookie-parser'\nimport { SetOption } from 'cookies'\nimport { CHECKOUT_COOKIE, OWNERSHIP_COOKIE } from '../constants'\n\nexport function generateRandomName() {\n return (1 + Math.random()).toString(36).substring(2)\n}\n\nexport function getFileExtension(fileName: string) {\n return fileName.match(/\\.[0-9a-z]+$/i)\n ? (fileName.match(/\\.[0-9a-z]+$/i) as any[])[0]\n : undefined\n}\n\nexport function statusToError(e: any) {\n if (!e.response) {\n throw e\n }\n\n const { response } = e as AxiosError\n const { status } = response!\n\n if (status === 401) {\n throw new AuthenticationError(e)\n }\n if (status === 403) {\n throw new ForbiddenError(e)\n }\n if (status === 400) {\n throw new UserInputError(e)\n }\n\n throw e\n}\n\nexport const parseCookie = (cookie: string): ParsedCookie => {\n const [parsed] = parse(cookie)\n\n const cookieName = parsed.name\n const cookieValue = parsed.value\n\n const extraOptions: SetOption = {\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\nexport function checkoutCookieFormat(orderFormId: string) {\n return `${CHECKOUT_COOKIE}=__ofid=${orderFormId};`\n}\n\nexport function ownershipCookieFormat(ownerId: string) {\n return `${OWNERSHIP_COOKIE}=${ownerId};`\n}\n\nexport function getOrderFormIdFromCookie(cookies: Context['cookies']) {\n const cookie = cookies.get(CHECKOUT_COOKIE)\n return cookie?.split('=')[1]\n}\n\nexport function getOwnerIdFromCookie(cookies: Context['cookies']) {\n return cookies.get(OWNERSHIP_COOKIE)\n}\n\ninterface ParsedCookie {\n name: string\n value: string\n options: SetOption\n}\n```" } ]
code_checkout-graphql_5125da7c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/attachmentsHelpers.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable no-shadow */\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable no-loop-func */\n/* eslint-disable @typescript-eslint/no-use-before-define */\n/* eslint-disable no-await-in-loop */\nimport { partition, propEq, omit, eqProps } from 'ramda'\n\ntype OptionItems = Array<Omit<AssemblyOptionInput, 'assemblyId'>>\n\ninterface OptionRequestUnit {\n items: OptionItems\n inputValues: Record<string, string | boolean>\n}\n\ninterface AddOptionsLogicInput {\n checkout: Context['clients']['checkout']\n orderForm: CheckoutOrderForm\n parentUniqueId?: string\n options?: AssemblyOptionInput[]\n oldItems: OrderFormItem[]\n}\n\ninterface AssemblyOptionBody {\n noSplitItem?: boolean\n composition?: {\n items: Array<{\n id: string\n quantity: number\n seller: string\n }>\n }\n inputValues?: Record<string, string>\n}\n\nconst getNewItemsOnly = (\n previousItems: OrderFormItem[],\n allItems: OrderFormItem[]\n) => {\n return allItems.filter(item => !previousItems.find(eqProps('uniqueId', item)))\n}\n\nconst findRecentlyAddedParent = (\n recentlyAdded: OrderFormItem[],\n id: string,\n assemblyId: string | null\n) =>\n recentlyAdded.find(i => i.id === id && i.parentAssemblyBinding === assemblyId)\n\nexport const addOptionsForItems = async (\n items: OrderFormItemInput[],\n checkout: Context['clients']['checkout'],\n orderForm: CheckoutOrderForm,\n oldItems: OrderFormItem[]\n) => {\n const recentlyAdded =\n items.length > 0 ? getNewItemsOnly(oldItems, orderForm.items) : []\n\n for (const item of items) {\n if (!item.options || item.options.length === 0) {\n continue\n }\n\n const parentItem = findRecentlyAddedParent(\n recentlyAdded,\n item.id!.toString(),\n null\n )\n\n await addOptionsLogic({\n checkout,\n parentUniqueId: parentItem?.uniqueId,\n options: item.options,\n orderForm,\n oldItems,\n })\n }\n}\n\nconst joinOptionsWithType = (options: AssemblyOptionInput[]) => {\n const result: Record<string, OptionRequestUnit> = {}\n\n for (const option of options) {\n const { assemblyId, ...rest } = option\n const currentArray = (result[assemblyId] && result[assemblyId].items) || []\n\n if (rest.id) {\n currentArray.push(rest)\n }\n\n result[assemblyId] = {\n inputValues: rest.inputValues,\n items: currentArray,\n }\n }\n\n return result\n}\n\nconst removeAssemblyBody = (option: OptionRequestUnit) => ({\n composition: {\n items: option.items.map(omit(['quantity', 'options'])),\n },\n})\n\nconst addAssemblyBody = (option: OptionRequestUnit) => {\n const body: AssemblyOptionBody = {}\n\n if (option.items.length > 0) {\n body.noSplitItem = true\n body.composition = {\n items: option.items.map(omit(['options', 'inputValues'])),\n }\n }\n\n if (option.inputValues) {\n body.noSplitItem = true\n body.inputValues = Object.keys(option.inputValues).reduce<\n Record<string, string>\n >((acc, key) => {\n // Transforming boolean values to string\n acc[key] = `${option.inputValues[key]}`\n return acc\n }, {})\n }\n\n return body\n}\n\nconst addOptionsLogic = async (input: AddOptionsLogicInput) => {\n const { checkout, orderForm, parentUniqueId, options, oldItems } = input\n if (!options || options.length === 0) {\n return\n }\n\n let parentIndex = orderForm.items.findIndex(\n propEq('uniqueId', parentUniqueId)\n )\n\n if (parentIndex == null || parentIndex < 0) {\n return\n }\n\n const isRemove = (option: AssemblyOptionInput) => option.quantity === 0\n const [toRemove, toAdd] = partition<AssemblyOptionInput>(isRemove, options)\n const joinedToAdd = joinOptionsWithType(toAdd)\n const joinedToRemove = joinOptionsWithType(toRemove)\n const idsToAdd = Object.keys(joinedToAdd)\n const idsToRemove = Object.keys(joinedToRemove)\n let recentOrderForm: any = orderForm\n\n for (const assemblyId of idsToRemove) {\n parentIndex = recentOrderForm.items.findIndex(\n propEq('uniqueId', parentUniqueId)\n )\n const parsedOptions = joinedToRemove[assemblyId]\n const response = await checkout\n .removeAssemblyOptions(\n orderForm.orderFormId!,\n parentIndex,\n assemblyId,\n removeAssemblyBody(parsedOptions)\n )\n .catch(() => ({ data: recentOrderForm }))\n recentOrderForm = response.data\n }\n\n for (const assemblyId of idsToAdd) {\n parentIndex = recentOrderForm.items.findIndex(\n propEq('uniqueId', parentUniqueId)\n )\n const parsedOptions = joinedToAdd[assemblyId]\n recentOrderForm = await checkout\n .addAssemblyOptions(\n orderForm.orderFormId!,\n parentIndex,\n assemblyId,\n addAssemblyBody(parsedOptions)\n )\n .catch(() => recentOrderForm)\n }\n\n for (const assemblyId of idsToAdd) {\n const parsedOptions = joinedToAdd[assemblyId]\n const itemsWithRecursiveOptions = parsedOptions.items.filter(\n ({ options }) => !!options\n )\n\n if (itemsWithRecursiveOptions.length > 0) {\n await addOptionsRecursive(\n itemsWithRecursiveOptions,\n assemblyId,\n recentOrderForm,\n oldItems,\n checkout\n )\n }\n }\n}\n\nconst addOptionsRecursive = async (\n items: OptionItems,\n assemblyId: string,\n orderForm: CheckoutOrderForm,\n oldItems: OrderFormItem[],\n checkout: Context['clients']['checkout']\n) => {\n const recentlyAdded = getNewItemsOnly(oldItems, orderForm.items)\n\n for (const item of items) {\n const parentItem = findRecentlyAddedParent(\n recentlyAdded,\n item.id!.toString(),\n assemblyId\n )\n\n await addOptionsLogic({\n checkout,\n parentUniqueId: parentItem?.uniqueId,\n options: item.options,\n orderForm,\n oldItems,\n })\n }\n}\n\n```" } ]
code_checkout-graphql_1abdd027
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/address.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AddressType, DELIVERY, PICKUP_IN_POINT } from '../constants'\n\nexport function getSelectedAddress(selectedAddresses: CheckoutAddress[]) {\n return selectedAddresses.find((address: CheckoutAddress) => {\n const isPickup = address.addressType === AddressType.PICKUP\n const isInStore = address.addressType === AddressType.INSTORE\n\n return !isPickup && !isInStore\n })\n}\n\nexport function addressHasGeocoordinates(address: CheckoutAddress) {\n return address?.geoCoordinates && address.geoCoordinates.length > 0\n}\n\nexport function filterDeliveryOptions(\n deliveryOptions: SLA[],\n logisticsInfo: LogisticsInfo[]\n) {\n return deliveryOptions.filter(deliveryOption => {\n const deliveryOptionIsInEveryLogisticsInfo = logisticsInfo.every(\n (li: LogisticsInfo) => li.slas.some(sla => sla.id === deliveryOption.id)\n )\n\n return (\n (deliveryOption.deliveryChannel === DELIVERY ||\n deliveryOption.deliveryChannel === PICKUP_IN_POINT) &&\n deliveryOption.availableDeliveryWindows.length === 0 &&\n deliveryOptionIsInEveryLogisticsInfo\n )\n })\n}\n\n```" } ]
code_checkout-graphql_7de22a9f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/resolvers/payment.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const queries = {\n getCardSessionId: async (_: {}, __: {}, ctx: Context): Promise<string> => {\n const { clients } = ctx\n const { id: cardSessionId } = await clients.checkout.getPaymentSession()\n return cardSessionId\n },\n}\n\nexport const mutations = {\n savePaymentToken: async (\n _: {},\n {\n paymentTokens,\n }: {\n paymentTokens: Array<{ creditCardToken: string; paymentSystem: string }>\n },\n ctx: Context\n ): Promise<SavePaymentTokenPayload> => {\n const { clients } = ctx\n const { checkout } = clients\n await checkout.savePaymentToken(paymentTokens)\n return { status: 'OK' }\n },\n}\n\n```" } ]
code_checkout-graphql_5e38382b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/resolvers/items.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Logger } from '@vtex/api'\n\nimport { SearchGraphQL } from '../clients/searchGraphQL'\nimport { fixImageUrl } from '../utils/image'\nimport { addOptionsForItems } from '../utils/attachmentsHelpers'\nimport { generateSubscriptionDataEntry } from '../utils/subscriptions'\nimport { OrderFormIdArgs } from '../utils/args'\n\nconst getProductInfo = async (\n item: OrderFormItem,\n searchGraphQL: SearchGraphQL,\n logger: Logger\n) => {\n try {\n const response = await searchGraphQL.product(item.productId)\n\n return response\n } catch (err) {\n if (Math.floor(Math.random() * 100) === 0) {\n logger.warn({\n message: 'Error when communicating with vtex.search-graphql',\n error: err,\n })\n }\n return null\n }\n}\n\nconst getVariations = (skuId: string, skuList: any[]) => {\n const matchedSku = skuList.find((sku: any) => sku.itemId === skuId)\n if (!matchedSku) {\n return []\n }\n return matchedSku.variations.map((variation: any) => ({\n fieldName: variation.name,\n fieldValues: variation.values || [],\n }))\n}\n\nexport const root = {\n Item: {\n name: async (item: OrderFormItem, _: unknown, ctx: Context) => {\n const {\n vtex: { logger },\n clients: { searchGraphQL },\n } = ctx\n\n const product = await getProductInfo(item, searchGraphQL, logger)\n\n return product?.productName ?? item.name\n },\n skuName: async (item: OrderFormItem, _: unknown, ctx: Context) => {\n const {\n vtex: { logger },\n clients: { searchGraphQL },\n } = ctx\n\n const product = await getProductInfo(item, searchGraphQL, logger)\n\n return (\n product?.items.find(({ itemId }) => itemId === item.id)?.name ??\n item.skuName\n )\n },\n imageUrls: (item: OrderFormItem, _: unknown, ctx: Context) => {\n return fixImageUrl(item.imageUrl, ctx.vtex.platform)\n },\n skuSpecifications: async (\n item: OrderFormItem,\n _: unknown,\n ctx: Context\n ) => {\n const {\n vtex: { logger },\n clients: { searchGraphQL },\n } = ctx\n\n const product = await getProductInfo(item, searchGraphQL, logger)\n\n return getVariations(item.id, product?.items ?? [])\n },\n productSpecificationGroups: async (\n item: OrderFormItem,\n _: unknown,\n ctx: Context\n ) => {\n const {\n vtex: { logger },\n clients: { searchGraphQL },\n } = ctx\n\n const product = await getProductInfo(item, searchGraphQL, logger)\n\n return product?.specificationGroups ?? []\n },\n },\n}\n\nexport const mutations = {\n addToCart: async (\n _: unknown,\n args: {\n items: OrderFormItemInput[]\n marketingData: Partial<OrderFormMarketingData>\n salesChannel?: string\n allowedOutdatedData?: string[]\n } & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const {\n clients,\n vtex,\n vtex: { logger },\n } = ctx\n const {\n orderFormId = vtex.orderFormId,\n items,\n marketingData = {},\n salesChannel,\n allowedOutdatedData,\n } = args\n\n const { checkout } = clients\n const shouldUpdateMarketingData =\n Object.keys(marketingData ?? {}).length > 0\n\n const { items: previousItems } = await checkout.orderForm(orderFormId!)\n const cleanItems = items.map(\n ({ options, index, uniqueId, ...rest }) => rest\n )\n\n const withOptions = items\n .map((item, currentIndex) => ({\n ...item,\n index: item.index ?? currentIndex,\n }))\n .filter(({ options }) => !!options && options.length > 0)\n\n /**\n * Always be sure to make these requests in the same order you use\n * while spreading their properties, since the second one will always\n * contain the most recent orderForm.\n */\n let newOrderForm = await checkout.addItem(\n orderFormId!,\n cleanItems,\n salesChannel,\n allowedOutdatedData\n )\n\n try {\n if (shouldUpdateMarketingData) {\n newOrderForm = await checkout.updateOrderFormMarketingData(\n orderFormId!,\n marketingData\n )\n }\n } catch (err) {\n logger.error({\n message: 'Error when updating orderForm marketing data.',\n id: orderFormId,\n graphqlArgs: marketingData,\n originalError: err,\n })\n }\n\n if (withOptions && withOptions.length > 0) {\n await addOptionsForItems(\n withOptions,\n checkout,\n {\n ...newOrderForm,\n orderFormId: orderFormId!,\n },\n previousItems\n )\n\n const subscriptionOptionsOnly = withOptions\n .map(itemWithOptions => ({\n itemIndex: (itemWithOptions.index as number) + previousItems.length,\n options: itemWithOptions.options as AssemblyOptionInput[],\n }))\n .filter(item =>\n item.options.some(option =>\n option.assemblyId.includes('vtex.subscription')\n )\n )\n\n const newSubscriptionDataEntries = generateSubscriptionDataEntry(\n subscriptionOptionsOnly\n )\n\n if (newSubscriptionDataEntries.length > 0) {\n const updatedSubscriptionData = {\n subscriptions: newOrderForm.subscriptionData\n ? newOrderForm.subscriptionData.subscriptions.concat(\n newSubscriptionDataEntries\n )\n : newSubscriptionDataEntries,\n }\n\n await checkout.updateSubscriptionDataField(\n orderFormId!,\n updatedSubscriptionData\n )\n }\n\n return checkout.orderForm(orderFormId!)\n }\n\n return newOrderForm\n },\n\n updateItems: async (\n _: unknown,\n args: {\n orderItems: OrderFormItemInput[]\n splitItem: boolean\n allowedOutdatedData?: string[]\n } & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const { clients, vtex } = ctx\n const {\n orderFormId = vtex.orderFormId,\n orderItems,\n splitItem,\n allowedOutdatedData,\n } = args\n const { checkout } = clients\n\n const cleanItems = orderItems.map(({ id, ...rest }) => rest)\n\n // Validating subscriptions\n let subscriptions\n if (orderItems.length === 1 && orderItems[0].index !== undefined) {\n const { items } = await checkout.orderForm(orderFormId!)\n const itemToUpdate = items[orderItems[0].index]\n\n subscriptions = itemToUpdate.attachments?.some(attachment =>\n attachment.name?.includes('vtex.subscription')\n )\n }\n\n if (cleanItems.some((item: OrderFormItemInput) => !item.index)) {\n const orderForm = await checkout.orderForm(orderFormId!)\n\n const idToIndex = orderForm.items.reduce(\n (acc: Record<string, number>, item: OrderFormItem, index: number) => {\n if (acc[item.uniqueId] === undefined) {\n acc[item.uniqueId] = index\n }\n return acc\n },\n {} as Record<string, number>\n )\n\n cleanItems.forEach((item: OrderFormItemInput) => {\n if (!item.index && item.uniqueId) {\n item.index = idToIndex[item.uniqueId]\n }\n })\n }\n\n const newOrderForm = await clients.checkout.updateItems(\n orderFormId!,\n cleanItems,\n subscriptions ? false : splitItem,\n allowedOutdatedData\n )\n\n return newOrderForm\n },\n addItemOffering: async (\n _: unknown,\n args: { offeringInput: OfferingInput } & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const { clients, vtex } = ctx\n const { offeringInput, orderFormId = vtex.orderFormId } = args\n\n const newOrderForm = await clients.checkout.addItemOffering(\n orderFormId!,\n offeringInput.itemIndex,\n offeringInput.offeringId,\n offeringInput.offeringInfo\n )\n\n return newOrderForm\n },\n removeItemOffering: async (\n _: unknown,\n args: { offeringInput: OfferingInput } & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const { clients, vtex } = ctx\n const { offeringInput, orderFormId = vtex.orderFormId } = args\n\n const newOrderForm = await clients.checkout.removeItemOffering(\n orderFormId!,\n offeringInput.itemIndex,\n offeringInput.offeringId\n )\n\n return newOrderForm\n },\n addBundleItemAttachment: async (\n _: unknown,\n args: {\n bundleItemAttachmentInput: BundleItemAttachmentInput\n } & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const { clients, vtex } = ctx\n const { bundleItemAttachmentInput, orderFormId = vtex.orderFormId } = args\n\n const newOrderForm = await clients.checkout.addBundleItemAttachment(\n orderFormId!,\n bundleItemAttachmentInput.itemIndex,\n bundleItemAttachmentInput.bundleItemId,\n bundleItemAttachmentInput.attachmentName,\n bundleItemAttachmentInput.attachmentContent\n )\n\n return newOrderForm\n },\n removeBundleItemAttachment: async (\n _: unknown,\n args: {\n bundleItemAttachmentInput: BundleItemAttachmentInput\n } & OrderFormIdArgs,\n ctx: Context\n ) => {\n const { clients, vtex } = ctx\n const { bundleItemAttachmentInput, orderFormId = vtex.orderFormId } = args\n\n const { data } = await clients.checkout.removeBundleItemAttachment(\n orderFormId!,\n bundleItemAttachmentInput.itemIndex,\n bundleItemAttachmentInput.bundleItemId,\n bundleItemAttachmentInput.attachmentName,\n bundleItemAttachmentInput.attachmentContent\n )\n\n return data\n },\n setManualPrice: async (\n _: unknown,\n args: { input: { itemIndex: number; price: number } } & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const { clients, vtex } = ctx\n const {\n input: { itemIndex, price },\n orderFormId = vtex.orderFormId,\n } = args\n\n const newOrderForm = await clients.checkoutAdmin.setManualPrice(\n orderFormId!,\n itemIndex,\n price\n )\n\n return newOrderForm\n },\n}\n\ninterface OfferingInput {\n itemIndex: number\n offeringId: string\n offeringInfo: unknown\n}\n\ninterface BundleItemAttachmentInput {\n itemIndex: number\n bundleItemId: string\n attachmentName: string\n attachmentContent: unknown\n}\n\n```" } ]
code_checkout-graphql_1e21fd71
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/resolvers/messages.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst COUPON_CODES = ['couponExpired', 'couponNotFound']\nconst IGNORED_CODES = ['cannotBeDelivered']\n\nexport const fillMessages = (messages: Message[]) => {\n const orderFormMessages = messages.reduce<OrderFormMessages>(\n (acc, message) => {\n if (COUPON_CODES.includes(message.code)) {\n acc.couponMessages.push(message)\n } else if (!IGNORED_CODES.includes(message.code)) {\n acc.generalMessages.push(message)\n }\n return acc\n },\n {\n couponMessages: [],\n generalMessages: [],\n }\n )\n\n return orderFormMessages\n}\n\n```" } ]
code_checkout-graphql_6d24f692
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/resolvers/shipping.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n getShippingData,\n selectShippingOption,\n selectAddress,\n} from '../utils/shipping'\nimport { AddressType, DELIVERY, PICKUP_IN_POINT } from '../constants'\nimport { OrderFormIdArgs } from '../utils/args'\n\nconst addressTypes = new Set<string>([\n AddressType.COMMERCIAL,\n AddressType.GIFT_REGISTRY,\n AddressType.INSTORE,\n AddressType.PICKUP,\n AddressType.RESIDENTIAL,\n AddressType.SEARCH,\n])\n\nexport const root = {\n Address: {\n addressType: ({ addressType }: CheckoutAddress) => {\n if (addressTypes.has(addressType)) {\n return addressType as AddressType\n }\n\n return null\n },\n },\n}\n\nexport const mutations = {\n estimateShipping: async (\n _: unknown,\n args: { address: CheckoutAddress } & OrderFormIdArgs,\n ctx: Context\n ) => {\n const { clients, vtex } = ctx\n const { checkout } = clients\n const { orderFormId = vtex.orderFormId, address } = args\n\n const orderForm = await checkout.orderForm(orderFormId!)\n const logisticsInfo =\n orderForm.shippingData && orderForm.shippingData.logisticsInfo\n const shippingData = getShippingData(address, logisticsInfo)\n\n const newOrderForm = await checkout.updateOrderFormShipping(orderFormId!, {\n ...shippingData,\n clearAddressIfPostalCodeNotFound: false,\n })\n\n return newOrderForm\n },\n\n selectDeliveryOption: async (\n _: unknown,\n args: { deliveryOptionId: string } & OrderFormIdArgs,\n ctx: Context\n ) => {\n const { clients, vtex } = ctx\n const { checkout } = clients\n const { orderFormId = vtex.orderFormId, deliveryOptionId } = args\n\n const orderForm = await checkout.orderForm(orderFormId!)\n const newShippingData = selectShippingOption({\n slaId: deliveryOptionId,\n shippingData: orderForm.shippingData,\n deliveryChannel: DELIVERY,\n })\n\n const newOrderForm = await checkout.updateOrderFormShipping(orderFormId!, {\n ...newShippingData,\n clearAddressIfPostalCodeNotFound: false,\n })\n\n return newOrderForm\n },\n\n selectPickupOption: async (\n _: unknown,\n args: { pickupOptionId: string; itemId: string } & OrderFormIdArgs,\n ctx: Context\n ) => {\n const { clients, vtex } = ctx\n const { checkout } = clients\n const { orderFormId = vtex.orderFormId, pickupOptionId, itemId } = args\n\n const orderForm = await checkout.orderForm(orderFormId!)\n const newShippingData = selectShippingOption({\n slaId: pickupOptionId,\n itemId,\n shippingData: orderForm.shippingData,\n deliveryChannel: PICKUP_IN_POINT,\n })\n\n const newOrderForm = await checkout.updateOrderFormShipping(orderFormId!, {\n ...newShippingData,\n clearAddressIfPostalCodeNotFound: false,\n })\n\n return newOrderForm\n },\n\n updateSelectedAddress: async (\n _: unknown,\n args: { input: CheckoutAddress } & OrderFormIdArgs,\n ctx: Context\n ) => {\n const {\n clients: { checkout },\n vtex,\n } = ctx\n const { orderFormId = vtex.orderFormId, input } = args\n\n const orderForm = await checkout.orderForm(orderFormId!)\n\n const newShippingData = selectAddress({\n address: input,\n shippingData: orderForm.shippingData,\n })\n\n const newOrderForm = await checkout.updateOrderFormShipping(orderFormId!, {\n ...newShippingData,\n clearAddressIfPostalCodeNotFound: false,\n })\n\n return newOrderForm\n },\n}\n\n```" } ]
code_checkout-graphql_d4e161ee
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/resolvers/orderForm.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { prop, propOr, compose } from 'ramda'\nimport { QueryOrderFormArgs } from 'vtex.checkout-graphql'\n\nimport { parseCookie } from '../utils'\nimport { fillMessages } from './messages'\nimport { getShippingInfo } from '../utils/shipping'\nimport {\n isShippingValid,\n isProfileValid,\n isPaymentValid,\n} from '../utils/validation'\nimport {\n ASPXAUTH_COOKIE,\n CHECKOUT_COOKIE,\n OWNERSHIP_COOKIE,\n VTEX_SESSION,\n} from '../constants'\nimport { OrderFormIdArgs } from '../utils/args'\n\ninterface StoreSettings {\n enableOrderFormOptimization: boolean\n storeName: string\n titleTag: string\n metaTagDescription: string\n metaTagKeywords: string\n enableCriticalCSS: boolean\n}\n\nconst ALL_SET_COOKIES = [CHECKOUT_COOKIE, ASPXAUTH_COOKIE, OWNERSHIP_COOKIE]\n\nconst filterAllowedCookies = (setCookies: string[], allowList: string[]) => {\n return setCookies.filter(setCookie => {\n const [key] = setCookie.split('=')\n return allowList.includes(key)\n })\n}\n\nconst replaceDomain = (host: string) => (cookie: string) =>\n cookie.replace(/domain=.+?(;|$)/, `domain=${host};`)\n\nconst isCallCenterOperator = async (orderFormId: string, ctx: Context) => {\n const {\n clients: { customSession },\n vtex: { logger },\n cookies,\n } = ctx\n\n const sessionCookie = cookies.get(VTEX_SESSION)\n\n if (sessionCookie === undefined) {\n logger.warn(\n `Can't request session details: \"${VTEX_SESSION}\" is undefined. ofid=${orderFormId}`\n )\n\n return false\n }\n\n const { sessionData } = await customSession.getSession(sessionCookie, ['*'])\n\n return sessionData?.namespaces?.impersonate?.canImpersonate?.value === 'true'\n}\n\nexport const root = {\n OrderForm: {\n id: prop('orderFormId'),\n marketingData: propOr({}, 'marketingData'),\n storePreferencesData: propOr({}, 'storePreferencesData'),\n allowManualPrice: async (\n orderForm: CheckoutOrderForm,\n _: unknown,\n ctx: Context\n ) => {\n const isCallCenter = await isCallCenterOperator(\n orderForm.orderFormId,\n ctx\n )\n\n if (!isCallCenter) {\n return false\n }\n\n const adminOrderForm = await ctx.clients.checkoutAdmin.orderForm()\n\n return adminOrderForm?.allowManualPrice || orderForm.allowManualPrice\n },\n userType: async (\n orderForm: CheckoutOrderForm,\n __: unknown,\n ctx: Context\n ) => {\n const isCallCenter = await isCallCenterOperator(\n orderForm.orderFormId,\n ctx\n )\n\n if (isCallCenter) {\n return 'CALL_CENTER_OPERATOR'\n }\n\n return 'STORE_USER'\n },\n messages: (orderForm: CheckoutOrderForm, _: unknown, ctx: Context) => {\n const {\n clients: { checkout },\n } = ctx\n\n const newMessages = fillMessages(orderForm.messages)\n\n if (orderForm.messages && orderForm.messages.length > 0) {\n checkout.clearMessages(orderForm.orderFormId)\n }\n\n return newMessages\n },\n clientProfileData: async (\n orderForm: CheckoutOrderForm,\n _: unknown,\n ctx: Context\n ) => {\n if (!orderForm.clientProfileData) {\n return null\n }\n\n const isValid = await isProfileValid(\n orderForm,\n orderForm.clientProfileData,\n ctx\n )\n\n return {\n ...orderForm.clientProfileData,\n isValid,\n }\n },\n shipping: async (\n orderForm: CheckoutOrderForm,\n _: unknown,\n ctx: Context\n ) => {\n const shippingInfo = await getShippingInfo({\n orderForm,\n clients: ctx.clients,\n })\n\n const isValid = await isShippingValid(orderForm, shippingInfo, ctx)\n\n return {\n ...shippingInfo,\n isValid,\n }\n },\n paymentData: (orderForm: CheckoutOrderForm) => {\n const isValid = isPaymentValid(orderForm.paymentData)\n\n return {\n ...orderForm.paymentData,\n isValid,\n }\n },\n },\n ClientPreferencesData: {\n optInNewsletter: prop('optinNewsLetter'),\n },\n}\n\n// Ported from store-graphql\n// https://github.com/vtex-apps/store-graphql/blob/master/node/resolvers/checkout/index.ts#L185\nexport async function syncWithStoreLocale(\n orderForm: CheckoutOrderForm,\n cultureInfo: string,\n checkout: Context['clients']['checkout']\n) {\n const clientPreferencesData = orderForm.clientPreferencesData || {\n locale: cultureInfo,\n }\n\n const shouldUpdateClientPreferencesData =\n cultureInfo &&\n clientPreferencesData.locale &&\n cultureInfo !== clientPreferencesData.locale\n\n if (shouldUpdateClientPreferencesData) {\n const newClientPreferencesData = {\n ...clientPreferencesData,\n }\n\n newClientPreferencesData.locale = cultureInfo\n\n try {\n return await checkout.updateOrderFormClientPreferencesData(\n orderForm.orderFormId,\n newClientPreferencesData\n )\n } catch (e) {\n console.error(e)\n\n return orderForm\n }\n }\n\n return orderForm\n}\n\nexport async function forwardCheckoutCookies(\n rawHeaders: Record<string, any>,\n ctx: Context,\n allowList: string[] = ALL_SET_COOKIES\n) {\n const responseSetCookies: string[] = rawHeaders?.['set-cookie'] || []\n\n const host = ctx.get('x-forwarded-host')\n const forwardedSetCookies = filterAllowedCookies(\n responseSetCookies,\n allowList\n )\n const parseAndClean = compose(parseCookie, replaceDomain(host))\n const cleanCookies = forwardedSetCookies.map(parseAndClean)\n cleanCookies.forEach(({ name, value, options }) => {\n if (options.secure && !ctx.cookies.secure) {\n ctx.cookies.secure = true\n }\n\n ctx.cookies.set(name, value, options)\n })\n}\n\nexport const queries = {\n orderForm: async (\n _: unknown,\n args: QueryOrderFormArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const { clients, vtex } = ctx\n const { orderFormId = vtex.orderFormId, refreshOutdatedData } = args\n\n let { data: newOrderForm, headers } = await clients.checkout.orderFormRaw(\n orderFormId ?? undefined,\n refreshOutdatedData ?? undefined\n )\n\n const hasBrokenCookie = newOrderForm?.clientProfileData?.email?.startsWith(\n 'vrn--vtexsphinx--aws-us-east-1'\n )\n\n if (hasBrokenCookie) {\n vtex.logger.info({ message: 'Broken order form', orderFormId })\n const obj = await clients.checkoutNoCookies.orderFormRaw(undefined, true)\n newOrderForm = obj.data\n headers = obj.headers\n }\n\n newOrderForm = await syncWithStoreLocale(\n newOrderForm,\n vtex.segment!.cultureInfo,\n clients.checkout\n )\n\n /**\n * In case the enableOrderFormOptimization setting is enabled in the store,\n * this will be the only `orderForm` query performed in the client. So no\n * 'checkout.vtex.com' cookie would have been set. Otherwise vtex.store-graphql\n * would've already set this cookie and this resolver should not overwrite it.\n */\n const storeSettings: StoreSettings = await clients.apps.getAppSettings(\n 'vtex.store@2.x'\n )\n\n if (storeSettings.enableOrderFormOptimization) {\n forwardCheckoutCookies(headers, ctx)\n }\n\n return newOrderForm\n },\n}\n\ninterface MutationUpdateOrderFormProfileArgs {\n input: UserProfileInput\n}\n\ninterface MutationUpdateClientPreferencesDataArgs {\n input: ClientPreferencesDataInput\n}\n\ninterface MutationUpdateOrderFormPaymentArgs {\n input: PaymentDataInput\n}\n\ninterface MutationUpdateOrderFormOpenTextField {\n input: OpenTextField\n}\n\ninterface MutationUpdateOrderFormMarketingData {\n input: OrderFormMarketingData\n}\n\nexport const mutations = {\n updateOrderFormProfile: async (\n _: unknown,\n args: MutationUpdateOrderFormProfileArgs & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const {\n clients: { checkout },\n vtex,\n } = ctx\n const { input, orderFormId = vtex.orderFormId } = args\n\n const orderFormWithProfile = await checkout.updateOrderFormProfile(\n orderFormId!,\n input,\n ctx\n )\n\n return orderFormWithProfile\n },\n updateClientPreferencesData: async (\n _: unknown,\n args: MutationUpdateClientPreferencesDataArgs & OrderFormIdArgs,\n ctx: Context\n ) => {\n const {\n clients: { checkout },\n vtex,\n } = ctx\n const { orderFormId = vtex.orderFormId, input } = args\n\n const updatedOrderForm = await checkout.updateOrderFormClientPreferencesData(\n orderFormId!,\n {\n optinNewsLetter: input.optInNewsletter,\n locale: input.locale,\n }\n )\n\n return updatedOrderForm\n },\n updateOrderFormPayment: async (\n _: unknown,\n args: MutationUpdateOrderFormPaymentArgs & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const {\n clients: { checkout },\n vtex,\n } = ctx\n const { orderFormId = vtex.orderFormId, input } = args\n\n const orderFormWithPayments = await checkout.updateOrderFormPayment(\n orderFormId!,\n input\n )\n\n return orderFormWithPayments\n },\n updateItemsOrdination: async (\n _: unknown,\n args: ItemsOrdinationArgs & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const {\n clients: { checkout },\n vtex,\n } = ctx\n const { ascending, criteria, orderFormId = vtex.orderFormId } = args\n\n const changeItemsOrdination = await checkout.updateItemsOrdination(\n orderFormId!,\n ascending,\n criteria\n )\n\n return changeItemsOrdination\n },\n\n clearOrderFormMessages: async (\n _: unknown,\n args: OrderFormIdArgs,\n ctx: Context\n ) => {\n const {\n clients: { checkout },\n vtex,\n } = ctx\n const { orderFormId = vtex.orderFormId } = args\n\n const updatedOrderForm = await checkout.clearMessages(orderFormId!)\n\n return updatedOrderForm\n },\n\n updateOrderFormOpenTextField: async (\n _: unknown,\n args: MutationUpdateOrderFormOpenTextField & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const {\n clients: { checkout },\n vtex,\n } = ctx\n const { orderFormId = vtex.orderFormId, input } = args\n\n const orderFormWithOpenTextField = await checkout.updateOrderFromOpenTextField(\n orderFormId!,\n input\n )\n\n return orderFormWithOpenTextField\n },\n\n updateOrderFormMarketingData: async (\n _: unknown,\n args: MutationUpdateOrderFormMarketingData & OrderFormIdArgs,\n ctx: Context\n ): Promise<CheckoutOrderForm> => {\n const {\n clients: { checkout },\n vtex,\n } = ctx\n\n const { orderFormId = vtex.orderFormId, input } = args\n\n const updatedOrderForm = await checkout.updateOrderFormMarketingData(\n orderFormId!,\n input\n )\n\n return updatedOrderForm\n },\n}\n\n```" } ]
code_checkout-graphql_9cb81514
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/resolvers/sla.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { getShippingInfo } from '../utils/shipping'\n\nexport const queries = {\n shippingSLA: async (_: any, args: any, ctx: Context) => {\n const { checkout } = ctx.clients\n const shippingData = (await checkout.simulation(\n args\n )) as CheckoutOrderForm['shippingData']\n\n // Here we mock an Order Form object to use getShippingInfo\n const orderForm = {\n orderFormId: '',\n value: 0,\n shippingData: {\n ...shippingData,\n selectedAddresses: [],\n },\n totalizers: [],\n } as Pick<\n CheckoutOrderForm,\n 'shippingData' | 'totalizers' | 'orderFormId' | 'value'\n >\n\n return getShippingInfo({ clients: ctx.clients, orderForm })\n },\n}\n\n```" } ]
code_checkout-graphql_6ca6a387
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/resolvers/coupon.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { OrderFormIdArgs } from '../utils/args'\n\nexport const mutations = {\n insertCoupon: async (\n _: unknown,\n args: { text: string } & OrderFormIdArgs,\n ctx: Context\n ) => {\n const { clients, vtex } = ctx\n const { orderFormId = vtex.orderFormId } = args\n\n const newOrderForm = await clients.checkout.insertCoupon(\n orderFormId!,\n args.text\n )\n\n return newOrderForm\n },\n}\n\n```" } ]
code_checkout-graphql_ebba335d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/resolvers/profile.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const queries = {\n checkoutProfile: async (\n _: unknown,\n { email }: { email: string },\n ctx: Context\n ): Promise<CheckoutProfile> => {\n const {\n clients,\n } = ctx\n\n const profile = await clients.checkout.getProfile(email)\n\n return profile\n },\n}\n\n```" } ]
code_checkout-graphql_71763016
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/resolvers/index.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { mutations as couponMutations } from './coupon'\nimport { root as itemRoot, mutations as itemMutations } from './items'\nimport {\n root as orderFormRoot,\n queries as orderFormQueries,\n mutations as orderFormMutations,\n} from './orderForm'\nimport {\n root as shippingRoot,\n mutations as shippingMutations,\n} from './shipping'\nimport {\n queries as paymentQueries,\n mutations as paymentMutations,\n} from './payment'\nimport { queries as profileQueries } from './profile'\nimport { queries as slaQueries } from './sla'\n\nexport const resolvers = {\n MarketingData: {\n coupon: (marketingData: OrderFormMarketingData) => {\n return marketingData.coupon ?? ''\n },\n utmCampaign: (marketingData: OrderFormMarketingData) => {\n return marketingData.utmCampaign ?? ''\n },\n utmSource: (marketingData: OrderFormMarketingData) => {\n return marketingData.utmSource ?? ''\n },\n utmMedium: (marketingData: OrderFormMarketingData) => {\n return marketingData.utmMedium ?? ''\n },\n utmiCampaign: (marketingData: OrderFormMarketingData) => {\n return marketingData.utmiCampaign ?? ''\n },\n utmiPart: (marketingData: OrderFormMarketingData) => {\n return marketingData.utmiPart ?? ''\n },\n utmiPage: (marketingData: OrderFormMarketingData) => {\n return marketingData.utmipage ?? ''\n },\n },\n ...orderFormRoot,\n ...shippingRoot,\n ...itemRoot,\n Mutation: {\n ...couponMutations,\n ...itemMutations,\n ...shippingMutations,\n ...paymentMutations,\n ...orderFormMutations,\n },\n Query: {\n ...orderFormQueries,\n ...paymentQueries,\n ...profileQueries,\n ...slaQueries,\n },\n}\n\n```" } ]
code_checkout-graphql_b6b8ab72
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/__tests__/shipping.test.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n deliveryAddress,\n ORDER_FORM_WITH_DIFFERENT_SLAS_BETWEEN_LOGISTICS_INFO,\n ORDER_FORM_WITH_DUPLICATED_SLAS_WITH_DIFFERENT_DELIVERY_IDS,\n ORDER_FORM_WITH_EMPTY_LOGISTICS_INFO,\n ORDER_FORM_WITH_EMPTY_SHIPPING_DATA,\n ORDER_FORM_WITH_PICKUPS,\n ORDER_FORM_WITH_SCHEDULED_DELIVERY,\n ORDER_FORM_WITH_SCHEDULED_DELIVERY_AND_PICKUPS,\n ORDER_FORM_WITH_UNAVAILABLE_ITEM_LOGISTICS_INFO,\n clients,\n} from '../__fixtures__/shipping'\nimport { getShippingInfo } from '../utils/shipping'\n\ndescribe('Shipping Resolvers', () => {\n describe('getShippingInfo', () => {\n it('should get shipping info handling empty shippingData', async () => {\n const expectedResult = {\n availableAddresses: [],\n countries: [],\n deliveryOptions: [],\n pickupOptions: [],\n selectedAddress: undefined,\n }\n\n expect(\n await getShippingInfo({\n clients,\n orderForm: ORDER_FORM_WITH_EMPTY_SHIPPING_DATA,\n })\n ).toEqual(expectedResult)\n })\n\n it('should get shipping info handling empty logisticsInfo', async () => {\n const expectedResult = {\n availableAddresses: [deliveryAddress],\n countries: ['BRA', 'GBR'],\n deliveryOptions: [],\n pickupOptions: [],\n selectedAddress: deliveryAddress,\n }\n\n expect(\n await getShippingInfo({\n clients,\n orderForm: ORDER_FORM_WITH_EMPTY_LOGISTICS_INFO,\n })\n ).toEqual(expectedResult)\n })\n\n it('should get shipping info', async () => {\n const expectedResult = {\n availableAddresses: [deliveryAddress],\n countries: ['BRA', 'GBR'],\n deliveryOptions: [\n {\n deliveryChannel: 'delivery',\n estimate: '1db',\n id: 'delivery-SLA',\n isSelected: true,\n price: 100,\n sla: {\n availableDeliveryWindows: [],\n deliveryChannel: 'delivery',\n deliveryIds: [],\n deliveryWindow: null,\n id: 'delivery-SLA',\n listPrice: 0,\n lockTTL: null,\n name: 'delivery-SLA',\n pickupDistance: 0,\n pickupPointId: null,\n pickupStoreInfo: {\n additionalInfo: null,\n address: null,\n dockId: null,\n friendlyName: null,\n isPickupStore: false,\n },\n polygonName: null,\n price: 100,\n shippingEstimate: '1db',\n shippingEstimateDate: null,\n tax: 0,\n },\n },\n ],\n pickupOptions: [\n {\n additionalInfo: null,\n address: null,\n deliveryChannel: 'pickup-in-point',\n estimate: '1d',\n friendlyName: null,\n id: 'pickup-SLA',\n isSelected: false,\n price: 100,\n storeDistance: 0,\n transitTime: undefined,\n businessHours: [\n {\n dayNumber: '1to5',\n closed: true,\n openingTime: '',\n closingTime: '',\n },\n { dayNumber: 6, closed: true, openingTime: '', closingTime: '' },\n { dayNumber: 0, closed: true, openingTime: '', closingTime: '' },\n ],\n },\n ],\n selectedAddress: deliveryAddress,\n }\n\n expect(\n await getShippingInfo({ clients, orderForm: ORDER_FORM_WITH_PICKUPS })\n ).toEqual(expectedResult)\n })\n\n it('should get shipping info removing scheduled delivery SLAs', async () => {\n const expectedResult = {\n availableAddresses: [deliveryAddress],\n countries: ['BRA', 'GBR'],\n deliveryOptions: [\n {\n deliveryChannel: 'delivery',\n estimate: '1db',\n id: 'delivery-SLA',\n isSelected: true,\n price: 100,\n sla: {\n availableDeliveryWindows: [],\n deliveryChannel: 'delivery',\n deliveryIds: [],\n deliveryWindow: null,\n id: 'delivery-SLA',\n listPrice: 0,\n lockTTL: null,\n name: 'delivery-SLA',\n pickupDistance: 0,\n pickupPointId: null,\n pickupStoreInfo: {\n additionalInfo: null,\n address: null,\n dockId: null,\n friendlyName: null,\n isPickupStore: false,\n },\n polygonName: null,\n price: 100,\n shippingEstimate: '1db',\n shippingEstimateDate: null,\n tax: 0,\n },\n },\n ],\n pickupOptions: [],\n selectedAddress: deliveryAddress,\n }\n\n expect(\n await getShippingInfo({\n clients,\n orderForm: ORDER_FORM_WITH_SCHEDULED_DELIVERY,\n })\n ).toEqual(expectedResult)\n })\n\n it('should get shipping info with delivery and pickup SLAs but removing scheduled delivery ones', async () => {\n const expectedResult = {\n availableAddresses: [deliveryAddress],\n countries: ['BRA', 'GBR'],\n deliveryOptions: [\n {\n deliveryChannel: 'delivery',\n estimate: '1db',\n id: 'delivery-SLA',\n isSelected: true,\n price: 100,\n sla: {\n availableDeliveryWindows: [],\n deliveryChannel: 'delivery',\n deliveryIds: [],\n deliveryWindow: null,\n id: 'delivery-SLA',\n listPrice: 0,\n lockTTL: null,\n name: 'delivery-SLA',\n pickupDistance: 0,\n pickupPointId: null,\n pickupStoreInfo: {\n additionalInfo: null,\n address: null,\n dockId: null,\n friendlyName: null,\n isPickupStore: false,\n },\n polygonName: null,\n price: 100,\n shippingEstimate: '1db',\n shippingEstimateDate: null,\n tax: 0,\n },\n },\n ],\n pickupOptions: [\n {\n additionalInfo: null,\n address: null,\n deliveryChannel: 'pickup-in-point',\n estimate: '1d',\n friendlyName: null,\n id: 'pickup-SLA',\n isSelected: false,\n price: 100,\n storeDistance: 0,\n transitTime: undefined,\n businessHours: [\n {\n dayNumber: '1to5',\n closed: true,\n openingTime: '',\n closingTime: '',\n },\n { dayNumber: 6, closed: true, openingTime: '', closingTime: '' },\n { dayNumber: 0, closed: true, openingTime: '', closingTime: '' },\n ],\n },\n ],\n selectedAddress: deliveryAddress,\n }\n\n expect(\n await getShippingInfo({\n clients,\n orderForm: ORDER_FORM_WITH_SCHEDULED_DELIVERY_AND_PICKUPS,\n })\n ).toEqual(expectedResult)\n })\n\n it('should get shipping info removing SLAs which does not exist in all logisticsInfo', async () => {\n const expectedResult = {\n availableAddresses: [deliveryAddress],\n countries: ['BRA', 'GBR'],\n deliveryOptions: [\n {\n deliveryChannel: 'delivery',\n estimate: '1db',\n id: 'delivery-SLA',\n isSelected: true,\n price: 200,\n sla: {\n availableDeliveryWindows: [],\n deliveryChannel: 'delivery',\n deliveryIds: [],\n deliveryWindow: null,\n id: 'delivery-SLA',\n listPrice: 0,\n lockTTL: null,\n name: 'delivery-SLA',\n pickupDistance: 0,\n pickupPointId: null,\n pickupStoreInfo: {\n additionalInfo: null,\n address: null,\n dockId: null,\n friendlyName: null,\n isPickupStore: false,\n },\n polygonName: null,\n price: 100,\n shippingEstimate: '1db',\n shippingEstimateDate: null,\n tax: 0,\n },\n },\n ],\n pickupOptions: [],\n selectedAddress: deliveryAddress,\n }\n\n expect(\n await getShippingInfo({\n clients,\n orderForm: ORDER_FORM_WITH_DIFFERENT_SLAS_BETWEEN_LOGISTICS_INFO,\n })\n ).toEqual(expectedResult)\n })\n\n it('should get shipping info removing duplicated SLAs which have different delivery ids', async () => {\n const expectedResult = {\n availableAddresses: [deliveryAddress],\n countries: ['BRA', 'GBR'],\n deliveryOptions: [\n {\n deliveryChannel: 'delivery',\n estimate: '1db',\n id: 'delivery-SLA',\n isSelected: true,\n price: 200,\n sla: {\n availableDeliveryWindows: [],\n deliveryChannel: 'delivery',\n deliveryIds: [\n {\n courierId: '1',\n courierName: 'PAC',\n dockId: '1fd8f86',\n quantity: 1,\n warehouseId: '1a105fe',\n },\n ],\n deliveryWindow: null,\n id: 'delivery-SLA',\n listPrice: 0,\n lockTTL: null,\n name: 'delivery-SLA',\n pickupDistance: 0,\n pickupPointId: null,\n pickupStoreInfo: {\n additionalInfo: null,\n address: null,\n dockId: null,\n friendlyName: null,\n isPickupStore: false,\n },\n polygonName: null,\n price: 100,\n shippingEstimate: '1db',\n shippingEstimateDate: null,\n tax: 0,\n },\n },\n ],\n pickupOptions: [],\n selectedAddress: deliveryAddress,\n }\n\n expect(\n await getShippingInfo({\n clients,\n orderForm: ORDER_FORM_WITH_DUPLICATED_SLAS_WITH_DIFFERENT_DELIVERY_IDS,\n })\n ).toEqual(expectedResult)\n })\n\n it('should get shipping info without empty deliveryOptions', async () => {\n const expectedResult = {\n availableAddresses: [deliveryAddress],\n countries: ['BRA', 'GBR'],\n deliveryOptions: [\n {\n deliveryChannel: 'delivery',\n estimate: '1db',\n id: 'delivery-SLA',\n isSelected: true,\n price: 100,\n sla: {\n availableDeliveryWindows: [],\n deliveryChannel: 'delivery',\n deliveryIds: [],\n deliveryWindow: null,\n id: 'delivery-SLA',\n listPrice: 0,\n lockTTL: null,\n name: 'delivery-SLA',\n pickupDistance: 0,\n pickupPointId: null,\n pickupStoreInfo: {\n additionalInfo: null,\n address: null,\n dockId: null,\n friendlyName: null,\n isPickupStore: false,\n },\n polygonName: null,\n price: 100,\n shippingEstimate: '1db',\n shippingEstimateDate: null,\n tax: 0,\n },\n },\n ],\n pickupOptions: [\n {\n additionalInfo: null,\n estimate: '1d',\n address: null,\n deliveryChannel: 'pickup-in-point',\n friendlyName: null,\n id: 'pickup-SLA',\n isSelected: false,\n price: 100,\n storeDistance: 0,\n transitTime: undefined,\n businessHours: [\n {\n dayNumber: '1to5',\n closed: true,\n openingTime: '',\n closingTime: '',\n },\n { dayNumber: 6, closed: true, openingTime: '', closingTime: '' },\n { dayNumber: 0, closed: true, openingTime: '', closingTime: '' },\n ],\n },\n ],\n selectedAddress: deliveryAddress,\n }\n\n expect(\n await getShippingInfo({\n clients,\n orderForm: ORDER_FORM_WITH_UNAVAILABLE_ITEM_LOGISTICS_INFO,\n })\n ).toEqual(expectedResult)\n })\n })\n})\n\n```" } ]
code_checkout-graphql_30b1b794
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/clients/searchGraphQL/productQuery.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface ProductResponse {\n productName: string\n productId: string\n items: Array<{\n itemId: string\n name: string\n variations: Array<{\n name: string\n values: string[]\n }>\n }>\n specificationGroups: Array<{\n name: string\n originalName: string\n specifications: Array<{\n name: string\n originalName: string\n values: string[]\n }>\n }>\n}\n\nexport interface ProductsByIdentifierResponse {\n productsByIdentifier: ProductResponse[]\n}\n\nexport interface ProductArgs {\n values: string[]\n}\n\nexport const query = `\nquery Product($values: [ID!]!) {\n productsByIdentifier(field: id, values: $values) {\n productName\n productId\n items {\n itemId\n name\n variations {\n name\n values\n }\n }\n specificationGroups {\n name\n originalName\n specifications {\n name\n originalName\n values\n }\n }\n }\n}\n`\n\n```" } ]
code_checkout-graphql_296b14e5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/clients/searchGraphQL/index.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { InstanceOptions, IOContext } from '@vtex/api'\nimport DataLoader from 'dataloader'\n\nimport { GraphQLServer } from '../graphqlServer'\nimport {\n ProductArgs,\n query as productQuery,\n ProductResponse,\n ProductsByIdentifierResponse,\n} from './productQuery'\n\nconst extensions = {\n persistedQuery: {\n provider: 'vtex.search-graphql@0.x',\n sender: 'vtex.checkout-graphql@0.x',\n },\n}\n\nexport class SearchGraphQL extends GraphQLServer {\n private productLoader: DataLoader<string, ProductResponse>\n\n constructor(ctx: IOContext, opts?: InstanceOptions) {\n super(ctx, opts)\n\n this.productLoader = new DataLoader(async keys => {\n const { data, errors } = await this.query<\n ProductsByIdentifierResponse,\n ProductArgs\n >(productQuery, { values: keys }, extensions, { metric: 'get-product' })\n\n if (errors && errors.length > 0) {\n const [error] = errors\n\n return keys.map(() => error.originalError!)\n }\n\n return keys.map(\n id =>\n data?.productsByIdentifier.find(\n product => product.productId === id\n ) ?? new Error('Product not found')\n )\n })\n }\n\n public product = (productId: string) => this.productLoader.load(productId)\n}\n\n```" } ]
code_checkout-graphql_c9ce3154
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/image/gocommerce.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { DEFAULT_HDF, DEFAULT_WIDTH } from './constants'\n\nconst cleanImageUrl = (imageUrl: string | undefined) => {\n if (!imageUrl) {\n return undefined\n }\n\n return imageUrl.split('?')[0]\n}\n\nconst changeImageUrlSize = (\n imageUrl: string | undefined,\n { width = DEFAULT_WIDTH, highDensityFactor = DEFAULT_HDF } = {}\n) => {\n if (!imageUrl) {\n return undefined\n }\n\n const widthCalc = width * highDensityFactor\n return `${imageUrl}?width=${widthCalc}&height=auto&aspect=true`\n}\n\nexport default {\n changeImageUrlSize,\n cleanImageUrl,\n}\n\n```" } ]
code_checkout-graphql_97469afd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/image/vtex.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { DEFAULT_HDF, DEFAULT_WIDTH } from './constants'\n\nconst baseUrlRegex = new RegExp(/.+ids\\/(\\d+)(?:-(\\d+)-(\\d+)|)\\//)\nconst sizeRegex = new RegExp(/-(\\d+)-(\\d+)/)\n\nconst cleanImageUrl = (imageUrl: string | undefined) => {\n if (!imageUrl) {\n return undefined\n }\n\n let resizedImageUrl = imageUrl\n const result = baseUrlRegex.exec(imageUrl)\n if (result && result.length > 0) {\n if (\n result.length === 4 &&\n result[2] !== undefined &&\n result[3] !== undefined\n ) {\n resizedImageUrl = result[0].replace(sizeRegex, '')\n } else {\n resizedImageUrl = result[0]\n }\n return resizedImageUrl\n }\n return undefined\n}\n\nconst changeImageUrlSize = (\n imageUrl: string | undefined,\n { highDensityFactor = DEFAULT_HDF, width = DEFAULT_WIDTH } = {}\n) => {\n if (!imageUrl) {\n return undefined\n }\n const widthCalc = width * highDensityFactor\n const resizedImageUrl = imageUrl.slice(0, -1) // Remove last \"/\"\n return `${resizedImageUrl}-${widthCalc}-auto`\n}\n\nexport default {\n changeImageUrlSize,\n cleanImageUrl,\n}\n\n```" } ]
code_checkout-graphql_2b2f88bf
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/image/constants.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const DEFAULT_WIDTH = 96\nexport const DEFAULT_HDF = 1\n\n```" } ]
code_checkout-graphql_7a6f0306
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/image/index.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport gocommerce from './gocommerce'\nimport none from './none'\nimport vtex from './vtex'\n\ninterface ImageOptions {\n width?: number\n highDensityFactor?: number\n}\n\ninterface Module {\n cleanImageUrl: (imageUrl: string | undefined) => string | undefined\n changeImageUrlSize: (\n imageUrl: string | undefined,\n options?: ImageOptions\n ) => string | undefined\n}\n\nconst replaceHttpToRelativeProtocol = (url: string | undefined) => {\n if (!url) {\n return undefined\n }\n return url.replace(/https:\\/\\/|http:\\/\\//, '//')\n}\n\nexport const fixImageUrl = (imageUrl: string, platform: string) => {\n const modules: Record<string, Module> = {\n default: none,\n gocommerce,\n vtex,\n }\n\n const adjust = modules[platform] || modules.default\n\n const cleanImageUrl = adjust.cleanImageUrl(\n replaceHttpToRelativeProtocol(imageUrl)\n )\n\n const [at1x, at2x, at3x] = [1, 2, 3].map(hdf =>\n adjust.changeImageUrlSize(cleanImageUrl, { highDensityFactor: hdf })\n )\n\n if (!at1x || !at2x || !at3x) {\n return undefined\n }\n\n return { at1x, at2x, at3x }\n}\n\n```" } ]
code_checkout-graphql_1c2b7e13
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-graphql/node/utils/image/none.ts from the checkout-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst cleanImageUrl = (imageUrl: string | undefined) => imageUrl\n\nconst changeImageUrlSize = (imageUrl: string | undefined) => imageUrl\n\nexport default {\n changeImageUrlSize,\n cleanImageUrl,\n}\n\n```" } ]
code_2performant_0d989483
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of 2performant/docs/README.md from the 2performant VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# 2performant\n\nOpen the VTEX APP Store and install the app on your store.\n\nor\n\nRun the following command:\n\n```sh\nvtex install vtex.twoperformant@0.x\n```\n\nNext, open the app settings on your admin and fill the form with your Confirm and Campaign Unique info.\n\n\n### Subtract TVA \n\nThis new feature was specially created for a client, miniprix, that doesn't have taxes configured in VTEX but needs to send to 2Performant data without taxes. \nSo I created a checkbox that when active and if there aren't any tax information coming from vtex, will subtract 19% (Romanian base tax) from the total value. \n\n```" } ]
code_2performant_8aff381e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of 2performant/react/index.tsx from the 2performant VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { canUseDOM } from 'vtex.render-runtime'\nimport { PixelMessage, ProductOrder } from './typings/events'\n\ninterface Params {\n amount: number\n confirm: string\n campaignUnique: string\n description: string\n transactionId: string\n}\n\nfunction createIFrame(params: Params) {\n const iframe = document.createElement('iframe')\n iframe.height = '1'\n iframe.width = '1'\n iframe.scrolling = 'no'\n iframe.marginHeight = '0'\n iframe.marginWidth = '0'\n iframe.src = `https://event.2performant.com/events/salecheck?amount=${params.amount}&campaign_unique=${params.campaignUnique}&confirm=${params.confirm}&description=${encodeURIComponent(params.description)}&transaction_id=${encodeURIComponent(params.transactionId)}`\n\n document.body.appendChild(iframe)\n}\n\nexport function handleEvents(e: PixelMessage) {\n switch (e.data.eventName) {\n case 'vtex:orderPlaced': {\n let tax = e.data.transactionTax\n let totalWithoutShip = e.data.transactionTotal - e.data.transactionShipping\n\n if (!tax && window.__2performant.subtractTVA)\n tax = +(0.19 * totalWithoutShip).toFixed(2)\n\n createIFrame({\n confirm: window.__2performant.confirm,\n campaignUnique: window.__2performant.campaignUnique,\n amount: +(totalWithoutShip - tax).toFixed(2),\n description: productNames(e.data.transactionProducts),\n transactionId: e.data.transactionId,\n })\n return\n }\n default: {\n return\n }\n }\n}\n\nfunction productNames(products: ProductOrder[]): string {\n const productNames = products.map(product => product.name)\n return productNames.join(', ')\n}\n\nif (canUseDOM) {\n window.addEventListener('message', handleEvents)\n}\n\n```" } ]
code_2performant_59095108
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of 2performant/react/package.json from the 2performant VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"ramda\": \"^0.26.1\"\n },\n \"devDependencies\": {\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/ramda\": \"^0.26.5\",\n \"@vtex/test-tools\": \"^1.1.0\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-vtex-react\": \"^4.1.0\",\n \"graphql\": \"^14.5.4\",\n \"prettier\": \"^1.18.2\",\n \"tslint-eslint-rules\": \"^5.4.0\",\n \"typescript\": \"3.9.7\"\n },\n \"version\": \"0.1.7\"\n}\n\n```" } ]
code_2performant_764e3e26
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of 2performant/store/interfaces.json from the 2performant VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"pixel.2performant\": {\n \"component\": \"index\"\n }\n}\n```" } ]