id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_minimum-boilerplate-theme_031d381b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minimum-boilerplate-theme/store/blocks/home.jsonc from the minimum-boilerplate-theme VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.home\": { \n \"blocks\": [\n \"rich-text\"\n ]\n },\n \"rich-text\": { \n \"props\": { \n \"text\": \"VTEX Store Framework\",\n \"textAlignment\": \"CENTER\",\n \"textPosition\": \"CENTER\",\n \"font\": \"t-heading-1\"\n }\n }\n}\n```"
}
] |
code_minimum-boilerplate-theme_402793f3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minimum-boilerplate-theme/store/blocks/header.jsonc from the minimum-boilerplate-theme VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"header\": {\n \"blocks\": [\"header-layout.desktop\", \"header-layout.mobile\"]\n },\n \"header.full\": {\n \"blocks\": [\"header-layout.desktop\", \"header-layout.mobile\"]\n },\n \"header-layout.desktop\": {\n \"children\": [\n \"sticky-layout#desktop\"\n ]\n },\n \"sticky-layout#desktop\": {\n \"props\": {\n \"blockClass\": \"sticky-header\"\n },\n \"children\": [\"flex-layout.row#desktop\"]\n },\n \"flex-layout.row#desktop\": {\n \"props\": {\n \"horizontalAlign\": \"center\",\n \"verticalAlign\": \"center\",\n \"preventHorizontalStretch\": true,\n \"preventVerticalStretch\": true,\n \"fullWidth\": true\n },\n \"children\": [\n \"flex-layout.col#logo-desktop\",\n \"flex-layout.col#spacer\",\n \"search-bar\",\n \"locale-switcher\",\n \"login\",\n \"minicart.v2\"\n ]\n },\n \"flex-layout.col#spacer\": {\n \"props\": {\n \"width\": \"grow\"\n }\n },\n \"flex-layout.col#logo-desktop\": {\n \"props\": {\n \"verticalAlign\": \"middle\"\n },\n \"children\": [\"logo\"]\n },\n \"logo\": {\n \"props\": {\n \"title\": \"Logo\",\n \"href\": \"/\",\n \"url\": \"https://brand.vtex.com/static/media/VTEX_pink_RGB.751a9fb5.svg\",\n \"width\": \"80\"\n }\n },\n \"header-layout.mobile\": {\n \"children\": [\"sticky-layout#mobile\"]\n },\n \"sticky-layout#mobile\": {\n \"children\": [\"flex-layout.row#mobile\"]\n },\n \"flex-layout.row#mobile\": {\n \"children\": [\n \"drawer\",\n \"logo\",\n \"flex-layout.col#spacer\",\n \"login\",\n \"minicart.v2\"\n ],\n \"props\": {\n \"blockClass\": \"main-header-mobile\",\n \"preventHorizontalStretch\": true,\n \"preserveLayoutOnMobile\": true,\n \"fullWidth\": true\n }\n },\n \"drawer\": {\n \"children\": []\n }\n}\n```"
}
] |
code_minimum-boilerplate-theme_fc287cba
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minimum-boilerplate-theme/store/blocks/product.jsonc from the minimum-boilerplate-theme VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.product\": {\n \"children\": [\n \n ]\n }\n}\n```"
}
] |
code_minimum-boilerplate-theme_ff9d1009
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minimum-boilerplate-theme/store/blocks/search.jsonc from the minimum-boilerplate-theme VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.search\": {\n \"blocks\": [\n \n ]\n }\n}\n```"
}
] |
code_product-specifications_af28a3cd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/docs/README.md from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/product-specifications) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Product Specifications\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nThe Product Specifications app provides blocks to render product specification information.\n\n\n\n## Configuration\n\n### Step 1 - Adding the Product Specifications app to your theme dependencies\n\nIn your theme `manifest.json`, add the Product Specification app as a dependency:\n\n```json\n\"dependencies\": {\n \"vtex.product-specifications\": \"1.x\"\n}\n```\n\nNow, you can use all the blocks exported by the `product-specifications` app. See the full list below:\n\n| Block name | Description |\n| - | - |\n| `product-specification-group` | Renders the product specification group. |\n| `product-specification` | Renders the product specification. It should be declared as a child of `product-specification-group`. |\n| `product-specification-value` | Renders the product specification value. It should be declared as a child of `product-specification`. It can be rendered with `HTML`. |\n| `product-specification-text` | Mandatory children of `product-specification-group`, `product-specification`, and `product-specification-value`. Depending on which block is declared, the `product-specification-text` renders information regarding a specification group, a specification, or a specification value. |\n\n### Step 2 - Adding the Product Specification blocks to your theme templates\n\nCopy the example below and paste it in the desired theme template, modifying it as necessary for your use case. If necessary, add the `product-specification-group` block to the template block list.\n\n```json\n{\n \"product-specification-group\": {\n \"children\": [\"product-specification-text#group\", \"product-specification\"]\n },\n \"product-specification\": {\n \"children\": [\n \"product-specification-text#specification\",\n \"product-specification-values\"\n ]\n },\n \"product-specification-values\": {\n \"children\": [\"product-specification-text#value\"]\n },\n \"product-specification-text#group\": {\n \"props\": {\n \"message\": \"{groupName}\"\n }\n },\n \"product-specification-text#specification\": {\n \"props\": {\n \"message\": \"{specificationName}\"\n }\n },\n \"product-specification-text#value\": {\n \"props\": {\n \"message\": \"{specificationValue}\"\n }\n }\n}\n```\n\n>⚠️ The Product Specification blocks need a Product context to work properly because they handle product information. Therefore, when declaring them, be sure that they are in a theme template in which this context is available, such as `store.product`.\n\nYou can also use other blocks to wrap the blocks provided by the Product Specifications app, such as the ones exported by the [Flex Layout app](https://developers.vtex.com/docs/guides/vtex-flex-layout/). For example:\n\n```json\n{\n \"product-specification-group#table\": {\n \"children\": [\"flex-layout.row#spec-group\"]\n },\n \"flex-layout.row#spec-group\": {\n \"props\": {\n \"blockClass\": \"productSpecificationGroup\"\n },\n \"children\": [\"flex-layout.col#spec-group\"]\n },\n \"flex-layout.col#spec-group\": {\n \"children\": [\"flex-layout.row#spec-group-name\", \"product-specification\"]\n },\n \"flex-layout.row#spec-group-name\": {\n \"props\": {\n \"blockClass\": \"productSpecificationGroupName\"\n },\n \"children\": [\"product-specification-text#group\"]\n },\n \"product-specification\": {\n \"children\": [\"flex-layout.row#spec-item\"]\n },\n \"flex-layout.row#spec-item\": {\n \"props\": {\n \"blockClass\": \"productSpecification\"\n },\n \"children\": [\"flex-layout.col#spec-name\", \"flex-layout.col#spec-value\"]\n },\n \"flex-layout.col#spec-name\": {\n \"props\": {\n \"blockClass\": \"productSpecificationName\",\n \"width\": {\n \"mobile\": \"50%\",\n \"desktop\": \"25%\"\n }\n },\n \"children\": [\"product-specification-text#specification\"]\n },\n \"flex-layout.col#spec-value\": {\n \"props\": {\n \"blockClass\": \"productSpecificationValue\"\n },\n \"children\": [\"product-specification-values\"]\n },\n \"product-specification-values\": {\n \"children\": [\"product-specification-text#value\"]\n },\n \"product-specification-text#group\": {\n \"props\": {\n \"message\": \"{groupName}\"\n }\n },\n \"product-specification-text#specification\": {\n \"props\": {\n \"message\": \"{specificationName}\"\n }\n },\n \"product-specification-text#value\": {\n \"props\": {\n \"message\": \"{specificationValue}\"\n }\n }\n}\n```\n\n### `product-specification-group` props\n\n| Prop name | Type | Description | Default value |\n| --------- | -------- | --------------------------------------------------------- | ------------- |\n| `filter` | `object` | Filters the specifications that the block should display. | `undefined` |\n\n- **`filter` object:**\n\n| Prop name | Type | Description | Default value |\n| - | - | - | - |\n| `specificationGroups` | `[string]` | Array of specification group names to be hidden or shown (depending on what is defined in the `type` property) by the `product-specification-group` block. | `undefined` |\n| `type` | `enum` | Determines whether the specification group names passed to the `specificationGroups` prop should be displayed or hidden on the UI. Possible values are: `hide` (hides specification groups declared in the `specificationGroups` prop) or `show` (only shows the specification groups declared in the `specificationGroups` prop). | `undefined` |\n\n#### `product-specification-text` props\n\n| Prop name | Type | Description | Default value |\n| - | - | - | - |\n| `blockClass` | `string` | Block ID of your choice to be used in [CSS customizations](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-css-handles-for-store-customization#using-the-blockclass-property). | `undefined` |\n| `message` | `string` | Defines the block default text message to be rendered on the UI. You can also define the text message a block will render on the UI using the Site Editor in the Admin and the `markers` prop. | `undefined` |\n| `markers` | `[string]` | IDs of your choice to identify the block's rendered text message and customize it using the Site Editor in the Admin. Learn how to use them by reading the documentation on [Using the Markers prop to customize a block message](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-the-markers-prop-to-customize-a-blocks-message). Note that a block message can also be customized in the Store Theme source code using the `message` prop. | `[]` |\n\n### Step 3 - Editing the `product-specification-text` messages\n\nAs stated in the previous step, the `product-specification-text` uses the [ICU Message Format](https://format-message.github.io/icu-message-format-for-translators/), making it possible to fully edit the block's rendered text messages.\n\nWhen using the `message` prop, you will not need to create an advanced configuration: declare the prop directly in your Store Theme app and pass to it the desired text value to be rendered with the block.\n\nThe `markers` prop, in turn, requires you to add an extra configuration in the Site Editor of the Admin to properly work. When using this prop, do not forget to check out the block message variables (shown in the table below) and the [Using the Markers prop to customize a block's message](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-the-markers-prop-to-customize-a-blocks-message) documentation.\n\n| Message variable | Type | Description |\n| --------------------------- | --------- | --------------------------------------------------------------------------------- |\n| `groupName` | `string` | Specification group name. |\n| `specificationName` | `string` | Specification name. |\n| `specificationValue` | `string` | Specification value. |\n| `isFirstSpecificationValue` | `boolean` | Determines whether it is the first specification value (`true`) or not (`false`). |\n| `isLastSpecificationValue` | `boolean` | Determines whether it is the last specification value (`true`) or not (`false`). |\n\n## Customization\n\nTo apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS handles for store customization](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-css-handles-for-store-customization).\n\n| CSS handles |\n| --------------------------- |\n| `groupName` |\n| `specificationName` |\n| `specificationValue` |\n| `specificationValue--first` |\n| `specificationValue--last` |\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n <tr>\n <td align=\"center\"><a href=\"https://github.com/raissacmp\"><img src=\"https://avatars0.githubusercontent.com/u/62183926?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Raissa Campos</b></sub></a><br /><a href=\"https://github.com/vtex-apps/product-specifications/commits?author=raissacmp\" title=\"Documentation\">📖</a></td>\n <td align=\"center\"><a href=\"https://www.linkedin.com/in/samuel-rodrigues-48638618b/\"><img src=\"https://avatars.githubusercontent.com/u/62268414?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Samuel Rodrigues</b></sub></a><br /><a href=\"https://github.com/vtex-apps/product-specifications/commits?author=SamuelRodriguess\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n\n<!-- markdownlint-restore -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```"
}
] |
code_product-specifications_378afc2c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/ProductSpecificationText.tsx from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useMemo, ReactNode } from 'react'\nimport { IOMessageWithMarkers } from 'vtex.native-types'\nimport { useCssHandles, applyModifiers } from 'vtex.css-handles'\n\nimport { useProductSpecification } from './ProductSpecification'\nimport { useProductSpecificationGroup } from './ProductSpecificationGroup'\nimport { useProductSpecificationValue } from './ProductSpecificationValues'\n\ninterface Props {\n message: string\n markers?: string[]\n}\n\ninterface MessageValues {\n groupName: ReactNode\n specificationName: ReactNode\n specificationValue: ReactNode\n isFirstSpecificationValue: boolean\n isLastSpecificationValue: boolean\n}\n\nconst CSS_HANDLES = [\n 'groupName',\n 'specificationName',\n 'specificationValue',\n] as const\n\nconst ProductSpecificationText: FC<Props> = ({\n message = '',\n markers = [],\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n const group = useProductSpecificationGroup()\n const specification = useProductSpecification()\n const value = useProductSpecificationValue()\n\n const values = useMemo(() => {\n const result: MessageValues = {\n groupName: '',\n specificationName: '',\n specificationValue: '',\n isFirstSpecificationValue: true,\n isLastSpecificationValue: true,\n }\n\n if (!group) {\n return result\n }\n\n result.groupName = (\n <span\n key=\"groupName\"\n data-specification-group={group.originalName}\n className={handles.groupName}\n >\n {group.name}\n </span>\n )\n\n if (!specification) {\n return result\n }\n\n result.specificationName = (\n <span\n key=\"specificationName\"\n data-specification-group={group.originalName}\n data-specification-name={specification.originalName}\n className={handles.specificationName}\n >\n {specification.name}\n </span>\n )\n\n if (!value) {\n return result\n }\n\n result.specificationValue = (\n <span\n key=\"specificationValue\"\n data-specification-group={group.originalName}\n data-specification-name={specification.originalName}\n data-specification-value={value.value}\n className={applyModifiers(handles.specificationValue, [\n value.isFirst ? 'first' : '',\n value.isLast ? 'last' : '',\n ])}\n dangerouslySetInnerHTML={{ __html: value.value }}\n />\n )\n result.isFirstSpecificationValue = value.isFirst\n result.isLastSpecificationValue = value.isLast\n\n return result\n }, [group, specification, value, handles])\n\n return (\n <IOMessageWithMarkers\n handleBase=\"specificationText\"\n message={message}\n markers={markers}\n values={values}\n />\n )\n}\n\nexport default ProductSpecificationText\n\n```"
}
] |
code_product-specifications_01025c24
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/ProductSpecificationValues.tsx from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useMemo, useContext } from 'react'\n\nimport { useProductSpecification } from './ProductSpecification'\n\nconst ProductSpecificationValues: FC = ({ children }) => {\n const specification = useProductSpecification()\n\n if (!specification) {\n return null\n }\n\n return (\n <>\n {specification.values.map((value, index) => (\n <ProductSpecificationValueProvider\n key={index}\n value={value}\n isFirst={index === 0}\n isLast={specification.values.length - 1 === index}\n >\n {children}\n </ProductSpecificationValueProvider>\n ))}\n </>\n )\n}\n\ninterface ProductSpecificationValueProviderProps {\n value: string\n isLast: boolean\n isFirst: boolean\n}\n\nconst SpecificationValueContext = React.createContext<\n ProductSpecificationValueProviderProps | undefined\n>(undefined)\n\nconst ProductSpecificationValueProvider: FC<ProductSpecificationValueProviderProps> = ({\n value,\n isLast,\n isFirst,\n children,\n}) => {\n const contextValue = useMemo(() => {\n return {\n value,\n isLast,\n isFirst,\n }\n }, [value, isLast, isFirst])\n\n return (\n <SpecificationValueContext.Provider value={contextValue}>\n {children}\n </SpecificationValueContext.Provider>\n )\n}\n\nexport const useProductSpecificationValue = () => {\n const value = useContext(SpecificationValueContext)\n\n return value\n}\n\nexport default ProductSpecificationValues\n\n```"
}
] |
code_product-specifications_61f15ca1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/ProductSpecificationText.test.tsx from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport { useProduct, ProductContext } from 'vtex.product-context'\n\nimport ProductSpecificationGroup from './ProductSpecificationGroup'\nimport ProductSpecification from './ProductSpecification'\nimport ProductSpecificationValues from './ProductSpecificationValues'\nimport ProductSpecificationText from './ProductSpecificationText'\n\nconst mockUseProduct = useProduct as jest.Mock<ProductContext>\n\ntest('ProductSpecificationText should render only the context it has available', () => {\n mockUseProduct.mockImplementation(() => ({\n product: {\n specificationGroups: [\n {\n name: 'Group',\n originalName: 'Group',\n specifications: [\n {\n name: 'Specification 1',\n originalName: 'Specification 1',\n values: ['Value 1'],\n },\n ],\n },\n ],\n },\n }))\n\n const { getByText, queryByText, rerender } = render(\n <ProductSpecificationGroup>\n <ProductSpecificationText message=\"{groupName} {specificationName} {specificationValue}\" />\n </ProductSpecificationGroup>\n )\n\n expect(getByText('Group')).toBeInTheDocument()\n expect(queryByText('Specification 1')).not.toBeInTheDocument()\n expect(queryByText('Value 1')).not.toBeInTheDocument()\n\n rerender(\n <ProductSpecificationGroup>\n <ProductSpecification>\n <ProductSpecificationText message=\"{groupName} {specificationName} {specificationValue}\" />\n </ProductSpecification>\n </ProductSpecificationGroup>\n )\n\n expect(getByText('Group')).toBeInTheDocument()\n expect(getByText('Specification 1')).toBeInTheDocument()\n expect(queryByText('Value 1')).not.toBeInTheDocument()\n\n rerender(\n <ProductSpecificationGroup>\n <ProductSpecification>\n <ProductSpecificationValues>\n <ProductSpecificationText message=\"{groupName} {specificationName} {specificationValue}\" />\n </ProductSpecificationValues>\n </ProductSpecification>\n </ProductSpecificationGroup>\n )\n\n expect(getByText('Group')).toBeInTheDocument()\n expect(getByText('Specification 1')).toBeInTheDocument()\n expect(getByText('Value 1')).toBeInTheDocument()\n})\n\ntest('ProductSpecificationText should render first and last handles', () => {\n mockUseProduct.mockImplementation(() => ({\n product: {\n specificationGroups: [\n {\n name: 'Group',\n originalName: 'Group',\n specifications: [\n {\n name: 'Specification 1',\n originalName: 'Specification 1',\n values: ['Value 1', 'Value 2', 'Value 3'],\n },\n ],\n },\n ],\n },\n }))\n\n const Text = ({ message }: { message: string }) => (\n <ProductSpecificationGroup>\n <ProductSpecification>\n <ProductSpecificationValues>\n <ProductSpecificationText message={message} />\n </ProductSpecificationValues>\n </ProductSpecification>\n </ProductSpecificationGroup>\n )\n\n const { getByText, queryByText, rerender } = render(\n <Text message=\"{isFirstSpecificationValue, select, true {{specificationValue}} other { }}\" />\n )\n\n expect(getByText('Value 1')).toBeInTheDocument()\n expect(getByText('Value 1')).toHaveClass('specificationValue--first')\n expect(getByText('Value 1')).not.toHaveClass('specificationValue--last')\n expect(queryByText('Value 2')).not.toBeInTheDocument()\n expect(queryByText('Value 3')).not.toBeInTheDocument()\n\n rerender(\n <Text message=\"{isLastSpecificationValue, select, false {{isFirstSpecificationValue, select, false {{specificationValue}} other { } }} other { }}\" />\n )\n\n expect(queryByText('Value 1')).not.toBeInTheDocument()\n expect(getByText('Value 2')).toBeInTheDocument()\n expect(getByText('Value 2')).not.toHaveClass('specificationValue--first')\n expect(getByText('Value 2')).not.toHaveClass('specificationValue--last')\n expect(queryByText('Value 3')).not.toBeInTheDocument()\n\n rerender(\n <Text message=\"{isLastSpecificationValue, select, true {{specificationValue}} other { }}\" />\n )\n expect(queryByText('Value 1')).not.toBeInTheDocument()\n expect(queryByText('Value 2')).not.toBeInTheDocument()\n expect(getByText('Value 3')).toBeInTheDocument()\n expect(getByText('Value 3')).not.toHaveClass('specificationValue--first')\n expect(getByText('Value 3')).toHaveClass('specificationValue--last')\n})\n\n```"
}
] |
code_product-specifications_2e900b04
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/package.json from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"product-specifications\",\n \"version\": \"1.1.2\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.3.1\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.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.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.111.1/public/@types/vtex.render-runtime\"\n }\n}\n\n```"
}
] |
code_product-specifications_5ac170d8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/ProductSpecificationGroup.test.tsx from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport { useProduct, ProductContext } from 'vtex.product-context'\n\nimport ProductSpecificationGroup from './ProductSpecificationGroup'\nimport ProductSpecification from './ProductSpecification'\nimport ProductSpecificationValues from './ProductSpecificationValues'\nimport ProductSpecificationText from './ProductSpecificationText'\nimport iphone from './__fixtures__/iphone'\nimport classicShoes from './__fixtures__/classicShoes'\n\nconst mockUseProduct = useProduct as jest.Mock<ProductContext>\n\ntest('render all specifications with their attributes', () => {\n mockUseProduct.mockImplementation(() => iphone)\n\n const { getByText } = render(\n <ProductSpecificationGroup>\n <ProductSpecificationText message=\"{groupName}\" />\n <div>\n <ProductSpecification>\n <ProductSpecificationText message=\"{specificationName}\" />\n <div>\n <ProductSpecificationValues>\n <ProductSpecificationText message=\"{specificationValue}\" />\n </ProductSpecificationValues>\n </div>\n </ProductSpecification>\n </div>\n </ProductSpecificationGroup>\n )\n\n expect(getByText('Pantalla')).toHaveAttribute(\n 'data-specification-group',\n 'Pantalla'\n )\n\n const specification = getByText('Resolución')\n\n expect(specification).toHaveAttribute('data-specification-group', 'Pantalla')\n expect(specification).toHaveAttribute('data-specification-name', 'Resolución')\n\n const value = getByText('2K - QUAD HD (2560 x 1440)')\n\n expect(value).toHaveAttribute('data-specification-group', 'Pantalla')\n expect(value).toHaveAttribute('data-specification-name', 'Resolución')\n expect(value).toHaveAttribute(\n 'data-specification-value',\n '2K - QUAD HD (2560 x 1440)'\n )\n})\n\ntest('should not have allSpecifications rendered', () => {\n mockUseProduct.mockImplementation(() => classicShoes)\n\n const { queryByText } = render(\n <ProductSpecificationGroup>\n <ProductSpecificationText message=\"{groupName}\" />\n </ProductSpecificationGroup>\n )\n\n expect(queryByText('allSpecifications')).not.toBeInTheDocument()\n})\n\ntest('should filter specification groups', () => {\n mockUseProduct.mockImplementation(() => classicShoes)\n\n const { queryByText, rerender } = render(\n <ProductSpecificationGroup\n filter={{ type: 'hide', specificationGroups: ['Masculino'] }}\n >\n <ProductSpecificationText message=\"{groupName}\" />\n </ProductSpecificationGroup>\n )\n\n expect(queryByText('Masculino')).not.toBeInTheDocument()\n expect(queryByText('Medicamentos')).toBeInTheDocument()\n\n rerender(\n <ProductSpecificationGroup\n filter={{ type: 'show', specificationGroups: ['Masculino'] }}\n >\n <ProductSpecificationText message=\"{groupName}\" />\n </ProductSpecificationGroup>\n )\n\n expect(queryByText('Masculino')).toBeInTheDocument()\n expect(queryByText('Medicamentos')).not.toBeInTheDocument()\n\n rerender(\n <ProductSpecificationGroup\n filter={{\n type: 'hide',\n specificationGroups: ['Medicamentos', 'Masculino'],\n }}\n >\n <ProductSpecificationText message=\"{groupName}\" />\n </ProductSpecificationGroup>\n )\n\n expect(queryByText('Masculino')).not.toBeInTheDocument()\n expect(queryByText('Medicamentos')).not.toBeInTheDocument()\n\n rerender(\n <ProductSpecificationGroup\n filter={{\n type: 'show',\n specificationGroups: ['Medicamentos', 'Masculino'],\n }}\n >\n <ProductSpecificationText message=\"{groupName}\" />\n </ProductSpecificationGroup>\n )\n\n expect(queryByText('Masculino')).toBeInTheDocument()\n expect(queryByText('Medicamentos')).toBeInTheDocument()\n})\n\n```"
}
] |
code_product-specifications_3ed923ad
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/ProductSpecificationGroup.tsx from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useMemo, useContext, ReactNode } from 'react'\nimport { useProduct, SpecificationGroup } from 'vtex.product-context'\n\ninterface ProductSpecificationGroupProps {\n filter?: {\n type: 'hide' | 'show'\n specificationGroups: string[]\n }\n children: ReactNode\n}\n\nconst defaultFilter: ProductSpecificationGroupProps['filter'] = {\n type: 'hide',\n specificationGroups: [],\n}\n\nconst ProductSpecificationGroup: FC<ProductSpecificationGroupProps> = ({\n filter = defaultFilter,\n children,\n}) => {\n const { product } = useProduct()\n\n const { type, specificationGroups: filterSpecificationGroups } = filter\n const specificationGroups = product?.specificationGroups ?? []\n\n const groups = useMemo(\n () =>\n specificationGroups.filter((group) => {\n if (group.originalName === 'allSpecifications') {\n return false\n }\n\n const hasGroup = filterSpecificationGroups.includes(group.originalName)\n\n if ((type === 'hide' && hasGroup) || (type === 'show' && !hasGroup)) {\n return false\n }\n\n return true\n }),\n [specificationGroups, type, filterSpecificationGroups]\n )\n\n if (!product) {\n return null\n }\n\n return (\n <>\n {groups.map((group, index) => (\n <ProductSpecificationGroupProvider key={index} group={group}>\n {children}\n </ProductSpecificationGroupProvider>\n ))}\n </>\n )\n}\n\nconst SpecificationGroupContext = React.createContext<\n SpecificationGroup | undefined\n>(undefined)\n\ninterface ProductSpecificationGroupProviderProps {\n group: SpecificationGroup\n}\n\nconst ProductSpecificationGroupProvider: FC<ProductSpecificationGroupProviderProps> = ({\n group,\n children,\n}) => {\n return (\n <SpecificationGroupContext.Provider value={group}>\n {children}\n </SpecificationGroupContext.Provider>\n )\n}\n\nexport const useProductSpecificationGroup = () => {\n const group = useContext(SpecificationGroupContext)\n\n return group\n}\n\nexport default ProductSpecificationGroup\n\n```"
}
] |
code_product-specifications_b90f1f03
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/ProductSpecification.tsx from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useContext } from 'react'\nimport { Specification } from 'vtex.product-context'\n\nimport { useProductSpecificationGroup } from './ProductSpecificationGroup'\n\nconst ProductSpecificationGroup: FC = ({ children }) => {\n const group = useProductSpecificationGroup()\n\n if (!group) {\n return null\n }\n\n return (\n <>\n {group.specifications.map((specification, index) => (\n <ProductSpecificationProvider key={index} specification={specification}>\n {children}\n </ProductSpecificationProvider>\n ))}\n </>\n )\n}\n\nconst SpecificationContext = React.createContext<Specification | undefined>(\n undefined\n)\n\ninterface ProductSpecificationProviderProps {\n specification: Specification\n}\n\nconst ProductSpecificationProvider: FC<ProductSpecificationProviderProps> = ({\n specification,\n children,\n}) => {\n return (\n <SpecificationContext.Provider value={specification}>\n {children}\n </SpecificationContext.Provider>\n )\n}\n\nexport const useProductSpecification = () => {\n const group = useContext(SpecificationContext)\n\n return group\n}\n\nexport default ProductSpecificationGroup\n\n```"
}
] |
code_product-specifications_900e7050
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/store/interfaces.json from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"product-specification-group\": {\n \"component\": \"ProductSpecificationGroup\",\n \"composition\": \"children\"\n },\n \"product-specification\": {\n \"component\": \"ProductSpecification\",\n \"composition\": \"children\"\n },\n \"product-specification-values\": {\n \"component\": \"ProductSpecificationValues\",\n \"composition\": \"children\"\n },\n \"product-specification-text\": {\n \"component\": \"ProductSpecificationText\",\n \"composition\": \"children\"\n }\n}\n\n```"
}
] |
code_product-specifications_385663bd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/__fixtures__/classicShoes.tsx from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nconst data = {\n product: {\n specificationGroups: [\n {\n name: 'Masculino',\n originalName: 'Masculino',\n specifications: [\n {\n name: 'Número do calçado',\n originalName: 'Número do calçado',\n values: ['35'],\n },\n ],\n },\n {\n name: 'Medicamentos',\n originalName: 'Medicamentos',\n specifications: [\n {\n name: 'Princípio Ativo',\n originalName: 'Princípio Ativo',\n values: ['Synthetic Leather'],\n },\n {\n name: 'Conservação',\n originalName: 'Conservação',\n values: ['Far from the sun'],\n },\n {\n name: 'RMS',\n originalName: 'RMS',\n values: ['1818990029830'],\n },\n ],\n },\n {\n name: 'allSpecifications',\n originalName: 'allSpecifications',\n specifications: [\n {\n name: 'Número do calçado',\n originalName: 'Número do calçado',\n values: ['35'],\n },\n {\n name: 'Princípio Ativo',\n originalName: 'Princípio Ativo',\n values: ['Synthetic Leather'],\n },\n {\n name: 'Conservação',\n originalName: 'Conservação',\n values: ['Far from the sun'],\n },\n {\n name: 'RMS',\n originalName: 'RMS',\n values: ['1818990029830'],\n },\n ],\n },\n ],\n },\n}\n\nexport default data\n\n```"
}
] |
code_product-specifications_e1c84eea
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/__fixtures__/iphone.tsx from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nconst data = {\n product: {\n productId: '38150',\n specificationGroups: [\n {\n name: 'Pantalla',\n originalName: 'Pantalla',\n specifications: [\n {\n name: 'Resolución',\n originalName: 'Resolución',\n values: ['2K - QUAD HD (2560 x 1440)'],\n },\n ],\n },\n {\n name: 'Propiedades comunes',\n originalName: 'Propiedades comunes',\n specifications: [\n {\n name: 'Promoción',\n originalName: 'Promoción',\n values: ['Falso'],\n },\n ],\n },\n {\n name: 'Batería',\n originalName: 'Batería',\n specifications: [\n {\n name: '3174',\n originalName: '3174',\n values: [],\n },\n ],\n },\n {\n name: 'Memoria',\n originalName: 'Memoria',\n specifications: [\n {\n name: 'Interna',\n originalName: 'Interna',\n values: ['256'],\n },\n {\n name: 'RAM',\n originalName: 'RAM',\n values: ['4 GB'],\n },\n ],\n },\n {\n name: 'Conectividad',\n originalName: 'Conectividad',\n specifications: [\n {\n name: 'Redes',\n originalName: 'Redes',\n values: ['2G', '3G', '4G'],\n },\n {\n name: 'Utilidades',\n originalName: 'Utilidades',\n values: ['Bluetooth', 'GPS', 'Wifi'],\n },\n ],\n },\n {\n name: 'Tipo',\n originalName: 'Tipo',\n specifications: [\n {\n name: 'Un solo SIM',\n originalName: 'Un solo SIM',\n values: [],\n },\n ],\n },\n {\n name: 'Procesador',\n originalName: 'Procesador',\n specifications: [\n {\n name: 'manzana',\n originalName: 'manzana',\n values: [],\n },\n ],\n },\n {\n name: 'Cámara',\n originalName: 'Cámara',\n specifications: [\n {\n name: 'Trasera',\n originalName: 'Trasera',\n values: ['12'],\n },\n {\n name: 'Selfie',\n originalName: 'Selfie',\n values: ['7 7'],\n },\n ],\n },\n {\n name: 'todas las especificaciones',\n originalName: 'allSpecifications',\n specifications: [\n {\n name: 'Resolución',\n originalName: 'Resolución',\n values: ['2K - QUAD HD (2560 x 1440)'],\n },\n {\n name: 'Promoción',\n originalName: 'Promoción',\n values: ['Falso'],\n },\n {\n name: 'Batería',\n originalName: 'Batería',\n values: ['3174'],\n },\n {\n name: 'Interna',\n originalName: 'Interna',\n values: ['256'],\n },\n {\n name: 'RAM',\n originalName: 'RAM',\n values: ['4 GB'],\n },\n {\n name: 'Redes',\n originalName: 'Redes',\n values: ['2G', '3G', '4G'],\n },\n {\n name: 'Utilidades',\n originalName: 'Utilidades',\n values: ['Bluetooth', 'GPS', 'Wifi'],\n },\n {\n name: 'Tipo',\n originalName: 'Tipo',\n values: ['Un solo SIM'],\n },\n {\n name: 'SIM',\n originalName: 'SIM',\n values: ['Nano SIM'],\n },\n {\n name: 'Procesador',\n originalName: 'Procesador',\n values: ['manzana'],\n },\n {\n name: 'Trasera',\n originalName: 'Trasera',\n values: ['12'],\n },\n {\n name: 'Selfie',\n originalName: 'Selfie',\n values: ['7 7'],\n },\n ],\n },\n ],\n },\n}\n\nexport default data\n\n```"
}
] |
code_product-specifications_2a893da6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/typings/vtex.product-context.d.ts from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.product-context' {\n interface Specification {\n name: string\n originalName: string\n values: string[]\n }\n\n interface SpecificationGroup {\n name: string\n originalName: string\n specifications: Specification[]\n }\n\n interface Product {\n specificationGroups: SpecificationGroup[]\n }\n\n interface ProductContext {\n product?: Product\n }\n\n export function useProduct(): ProductContext\n}\n\n```"
}
] |
code_product-specifications_e56110fe
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-specifications/react/typings/vtex.native-types.d.ts from the product-specifications VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.native-types' {\n import { FC, ReactElement, ReactNode, Component } from 'react'\n\n interface Props {\n message: string\n handleBase: string\n markers: string[]\n values: unknown\n }\n\n const IOMessageWithMarkers: FC<Props>\n}\n\n```"
}
] |
code_b2b-quotes-graphql_56fa700c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/docs/README.md from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/b2b-quotes-graphql) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# B2B Quotes GraphQL\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\nBackend app providing GraphQL queries and mutations for [B2B Quotes](https://github.com/vtex-apps/b2b-quotes).\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```"
}
] |
code_b2b-quotes-graphql_8bc7b74c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/graphql/schema.graphql from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\ntype Query {\n getAppSettings: AppSettings\n @auditAccess\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n getQuoteEnabledForUser(email: String!): Boolean\n @auditAccess\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n getQuote(id: String): Quote\n @validateStoreUserAccess\n @withPermissions\n @withSession\n @withSegment\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n getQuotes(\n organization: [String]\n costCenter: [String]\n status: [String]\n search: String\n page: Int = 1\n pageSize: Int = 25\n sortOrder: String = \"DESC\"\n sortedBy: String = \"lastUpdate\"\n ): Quotes\n @validateStoreUserAccess\n @withPermissions\n @withSession\n @withSegment\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n getChildrenQuotes(\n id: String\n sortOrder: String = \"DESC\"\n sortedBy: String = \"lastUpdate\"\n ): [Quote]\n @validateStoreUserAccess\n @withPermissions\n @withSession\n @withSegment\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n checkSellerQuotes(sellers: [String!]!): [Seller!]!\n @validateStoreUserAccess\n @withPermissions\n @withSession\n @withSegment\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n}\n\ntype Mutation {\n createQuote(input: QuoteInput!): String\n @validateStoreUserAccess\n @withPermissions\n @withSession\n @withSegment\n updateQuote(input: QuoteUpdateInput!): String\n @validateStoreUserAccess\n @withPermissions\n @withSession\n useQuote(id: String, orderFormId: String): String\n @validateStoreUserAccess\n @withPermissions\n @withSession\n clearCart(orderFormId: String): String @validateStoreUserAccess\n saveAppSettings(input: AppSettingsInput!): AppSettings\n @validateAdminUserAccess\n @cacheControl(scope: PRIVATE)\n}\n\n```"
}
] |
code_b2b-quotes-graphql_b8be22e4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/graphql/quote.graphql from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\ninput QuoteInput {\n referenceName: String\n items: [QuoteItemInput]\n subtotal: Float\n note: String\n sendToSalesRep: Boolean\n}\n\ninput QuoteItemInput {\n name: String\n skuName: String\n refId: String\n id: String\n productId: String\n imageUrl: String\n listPrice: Float\n price: Float\n quantity: Int\n sellingPrice: Float\n seller: String\n}\n\ninput QuoteUpdateInput {\n id: String\n items: [QuoteItemInput]\n subtotal: Float\n note: String\n decline: Boolean\n expirationDate: String\n}\n\ntype Quotes {\n data: [Quote]\n pagination: Pagination\n}\n\ntype Pagination {\n page: Int\n pageSize: Int\n total: Int\n}\n\ntype Quote {\n id: String\n referenceName: String\n creatorEmail: String\n creatorName: String\n creatorRole: String\n creationDate: String\n expirationDate: String\n lastUpdate: String\n updateHistory: [QuoteUpdate]\n items: [QuoteItem]\n subtotal: Float\n status: String\n organization: String\n organizationName: String\n costCenter: String\n costCenterName: String\n viewedBySales: Boolean\n viewedByCustomer: Boolean\n salesChannel: String\n seller: String\n sellerName: String\n parentQuote: String\n hasChildren: Boolean\n childrenQuantity: Int\n}\n\ntype QuoteUpdate {\n email: String\n role: String\n date: String\n status: String\n note: String\n}\n\ntype QuoteItem {\n name: String\n skuName: String\n refId: String\n id: String\n productId: String\n imageUrl: String\n listPrice: Float\n price: Float\n quantity: Int\n sellingPrice: Float\n seller: String\n}\n\ntype Seller {\n id: String\n name: String\n}\n\n```"
}
] |
code_b2b-quotes-graphql_eee31335
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/graphql/directives.graphql from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\ndirective @withSession on FIELD | FIELD_DEFINITION\ndirective @withPermissions on FIELD | FIELD_DEFINITION\ndirective @withSegment on FIELD | FIELD_DEFINITION\ndirective @validateAdminUserAccess on FIELD | FIELD_DEFINITION\ndirective @validateStoreUserAccess on FIELD | FIELD_DEFINITION\ndirective @auditAccess on FIELD | FIELD_DEFINITION\n\n```"
}
] |
code_b2b-quotes-graphql_dbcd2e0c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/graphql/appSettings.graphql from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\ntype AppSettings {\n adminSetup: AdminSetup\n}\ntype AdminSetup {\n cartLifeSpan: Int\n quotesManagedBy: QuotesManagedBy!\n}\ninput AppSettingsInput {\n cartLifeSpan: Int\n quotesManagedBy: QuotesManagedBy\n}\nenum QuotesManagedBy {\n MARKETPLACE\n SELLER\n}\n```"
}
] |
code_b2b-quotes-graphql_d81fb978
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/service.json from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 1024,\n \"ttl\": 300,\n \"timeout\": 60,\n \"events\": {\n \"broadcasterOrder\": {\n \"sender\": \"vtex.orders-broadcast\",\n \"topics\": [\"order-created\"]\n }\n },\n \"routes\": {\n \"host\": {\n \"path\": \"/b2b-quotes-graphql/_v/0/host\",\n \"public\": true,\n \"access\": \"authorized\",\n \"policies\": [\n {\n \"effect\": \"allow\",\n \"actions\": [\"get\"]\n }\n ]\n },\n \"queueHandler\": {\n \"path\": \"/b2b-quotes-graphql/_v/0/process-queue\",\n \"public\": true,\n \"access\": \"authorized\",\n \"policies\": [\n {\n \"effect\": \"allow\",\n \"actions\": [\"get\"],\n \"principals\": [\"vrn:apps:*:*:*:app/vtex.scheduler@*\"]\n }\n ]\n },\n \"getSellerQuote\": {\n \"path\": \"/b2b-quotes-graphql/_v/0/get-seller-quote/:seller/:id\",\n \"public\": true,\n \"access\": \"authorized\",\n \"policies\": [\n {\n \"effect\": \"allow\",\n \"actions\": [\"get\"],\n \"principals\": [\"vrn:apps:*:*:*:app/vtex.b2b-seller-quotes@*\"]\n }\n ]\n },\n \"getSellerQuotesPaginated\": {\n \"path\": \"/b2b-quotes-graphql/_v/0/get-seller-quotes-paginated/:seller\",\n \"public\": true,\n \"access\": \"authorized\",\n \"policies\": [\n {\n \"effect\": \"allow\",\n \"actions\": [\"get\"],\n \"principals\": [\"vrn:apps:*:*:*:app/vtex.b2b-seller-quotes@*\"]\n }\n ]\n },\n \"saveSellerQuote\": {\n \"path\": \"/b2b-quotes-graphql/_v/0/save-seller-quote/:seller/:id\",\n \"public\": true,\n \"access\": \"authorized\",\n \"policies\": [\n {\n \"effect\": \"allow\",\n \"actions\": [\"post\"],\n \"principals\": [\"vrn:apps:*:*:*:app/vtex.b2b-seller-quotes@*\"]\n }\n ]\n }\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_571f08c8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/typings.d.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Quote {\n id: string\n referenceName: string\n creatorEmail: string\n creatorName: string\n creatorRole: string\n creationDate: string\n expirationDate: string\n lastUpdate: string\n updateHistory: QuoteUpdate[]\n items: QuoteItem[]\n subtotal: number\n status: string\n organization: string\n costCenter: string\n viewedBySales: boolean\n viewedByCustomer: boolean\n salesChannel: string | null\n seller?: string | null\n sellerName?: string | null\n parentQuote?: string | null\n hasChildren?: boolean | null\n childrenQuantity?: number | null\n}\n\ninterface QuoteUpdate {\n email: string\n role: string\n date: string\n status: string\n note: string\n}\n\ninterface QuoteItem {\n name: string\n skuName: string\n refId: string\n id: string\n productId: string\n imageUrl: string\n listPrice: number\n price: number\n quantity: number\n sellingPrice: number\n seller: string\n}\n\ninterface ReqContext {\n account: string\n workspace: string\n authToken: string\n region: string\n production: boolean\n userAgent: string\n}\n\ninterface Logger {\n log(\n content: string,\n level: LogLevel,\n details?: Record<string, unknown>\n ): PromiseLike<void>\n}\n\ninterface OperationState {\n orderFormId: string\n ctx: ReqContext\n data?: OperationData\n logger: Logger\n}\n\ninterface OperationData {\n orderForm?: any\n userProfileId: string\n cookie: string\n}\n\ntype ProcessPaymentStep = (\n state: OperationState,\n next: () => Promise<void>\n) => Promise<void>\n\ntype LogLevel = 'info' | 'error' | 'warning'\n\ninterface Timings {\n [middleware: string]: [number, number]\n}\n\ndeclare module '*.json' {\n const value: any\n export default value\n}\n\ninterface OrderFormConfiguration {\n paymentConfiguration?: PaymentConfiguration\n taxConfiguration?: TaxConfiguration\n minimumQuantityAccumulatedForItems?: number\n decimalDigitsPrecision?: number\n minimumValueAccumulated?: number\n apps?: [App]\n allowMultipleDeliveries?: boolean\n allowManualPrice?: boolean\n maxIntOfWhiteLabelSellers?: number\n maskFirstPurchaseData?: boolean\n recaptchaValidation?: boolean\n}\n\ninterface Settings {\n adminSetup: {\n cartLifeSpan: number\n allowManualPrice: boolean\n hasCron?: boolean\n cronExpression?: string\n cronWorkspace?: string\n quotesManagedBy?: string\n }\n schemaVersion: string\n schemaHash: string | null\n templateHash: string | null\n}\n\ninterface SessionData {\n namespaces: {\n profile: {\n id: { value: string }\n email: { value: string }\n firstName: { value: string }\n lastName: { value: string }\n }\n account: {\n accountName: { value: string }\n }\n 'storefront-permissions': {\n organization: { value: string }\n costcenter: { value: string }\n }\n }\n}\n\ninterface SellerQuoteInput {\n items: QuoteItem[]\n subtotal: number\n seller: string\n sellerName: string\n}\n\ntype SellerQuoteMap = Record<string, SellerQuoteInput>\n\ninterface VerifyQuoteSettingsResponse {\n receiveQuotes: boolean\n}\n\ninterface SellerQuoteNotifyInput {\n quoteId: string\n marketplaceAccount: string\n creationDate: string\n}\n\ninterface Seller {\n id: string\n name: string\n}\n\n```"
}
] |
code_b2b-quotes-graphql_4b5f9c54
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/package.json from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.b2b-quotes-graphql\",\n \"version\": \"4.0.1\",\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"graphql\": \"^14.0.0\",\n \"graphql-tools\": \"^4.0.0\",\n \"jsonwebtoken\": \"^8.5.0\",\n \"ramda\": \"^0.25.0\",\n \"atob\": \"^2.1.2\",\n \"axios\": \"0.27.2\",\n \"@vtex/api\": \"6.48.0\"\n },\n \"devDependencies\": {\n \"@types/atob\": \"^2.1.2\",\n \"@types/bluebird\": \"^3.5.25\",\n \"@types/co-body\": \"0.0.3\",\n \"@types/jsonwebtoken\": \"^8.5.0\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/prettier-config\": \"^0.3.1\",\n \"tslint\": \"^5.12.0\",\n \"tslint-config-prettier\": \"^1.18.0\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.b2b-quotes-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.b2b-quotes-graphql@2.0.2/public/@types/vtex.b2b-quotes-graphql\",\n \"vtex.orders-broadcast\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.orders-broadcast@0.3.0/public/_types/react\",\n \"vtex.storefront-permissions\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.storefront-permissions@1.23.0/public/@types/vtex.storefront-permissions\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit && tslint -c tslint.json './**/*.ts'\"\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_ebb24b41
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/constants.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const APP_NAME = 'b2b-quotes-graphql'\nexport const SCHEMA_VERSION = 'v1.3'\nexport const QUOTE_DATA_ENTITY = 'quotes'\nexport const B2B_USER_SCHEMA_VERSION = 'v0.1.2'\nexport const B2B_USER_DATA_ENTITY = 'b2b_users'\nexport const CRON_EXPRESSION = '0 */12 * * *'\n\nexport const QUOTE_FIELDS = [\n 'id',\n 'referenceName',\n 'creatorEmail',\n 'creatorName',\n 'creatorRole',\n 'creationDate',\n 'expirationDate',\n 'lastUpdate',\n 'updateHistory',\n 'items',\n 'subtotal',\n 'status',\n 'organization',\n 'costCenter',\n 'viewedBySales',\n 'viewedByCustomer',\n 'salesChannel',\n 'seller',\n 'sellerName',\n 'parentQuote',\n 'hasChildren',\n 'childrenQuantity',\n]\n\nexport const routes = {\n addCustomData: ({\n account,\n orderFormId,\n appId,\n property,\n }: {\n account: string\n orderFormId: string\n appId: string\n property?: string\n }) =>\n `${routes.orderForm(account)}/${orderFormId}/customData/${appId}/${\n property ?? ''\n }`,\n addPriceToItems: (account: string, orderFormId: string) =>\n `${routes.orderForm(account)}/${orderFormId}/items/update`,\n addToCart: (account: string, orderFormId: string) =>\n `${routes.orderForm(account)}/${orderFormId}/items/`,\n baseUrl: (account: string) =>\n `http://${account}.vtexcommercestable.com.br/api`,\n checkoutConfig: (account: string) =>\n `${routes.baseUrl(account)}/checkout/pvt/configuration/orderForm`,\n clearCart: (account: string, id: string) =>\n `${routes.orderForm(account)}/${id}/items/removeAll`,\n getQuote: (account: string, id: string) =>\n `${routes.quoteEntity(\n account\n )}/documents/${id}?_fields=id,email,cartName,status,description,items,creationDate,subtotal,discounts,shipping,taxes,total,customData,address`,\n listQuotes: (account: string, email: string) =>\n `${routes.quoteEntity(\n account\n )}/search?email=${email}&_schema=${SCHEMA_VERSION}&_fields=id,email,cartName,status,description,items,creationDate,subtotal,discounts,taxes,shipping,total,customData,address&_sort=creationDate DESC`,\n orderForm: (account: string) =>\n `${routes.baseUrl(account)}/checkout/pub/orderForm`,\n quoteEntity: (account: string) =>\n `${routes.baseUrl(account)}/dataentities/quote`,\n saveSchema: (account: string) =>\n `${routes.quoteEntity(account)}/schemas/${SCHEMA_VERSION}`,\n}\n\nexport const getAppId = (): string => {\n return process.env.VTEX_APP_ID ?? ''\n}\n\nexport const schema = {\n properties: {\n costCenter: {\n title: 'Cost Center',\n type: ['null', 'string'],\n },\n creationDate: {\n format: 'date-time',\n title: 'Creation Date',\n type: 'string',\n },\n creatorEmail: {\n title: 'Creator Email',\n type: 'string',\n },\n creatorName: {\n title: 'Creator Name',\n type: ['null', 'string'],\n },\n creatorRole: {\n title: 'Creator Role',\n type: 'string',\n },\n expirationDate: {\n format: 'date-time',\n title: 'Expiration Date',\n type: 'string',\n },\n items: {\n title: 'Cart',\n type: 'array',\n },\n lastUpdate: {\n format: 'date-time',\n title: 'Last Update',\n type: 'string',\n },\n organization: {\n title: 'Organization',\n type: ['null', 'string'],\n },\n referenceName: {\n title: 'Reference Name',\n type: 'string',\n },\n salesChannel: {\n title: 'Sales Channel',\n type: ['null', 'string'],\n },\n status: {\n title: 'Status',\n type: 'string',\n },\n subtotal: {\n title: 'Subtotal',\n type: 'number',\n },\n updateHistory: {\n title: 'Update History',\n type: 'array',\n },\n viewedByCustomer: {\n title: 'Viewed by Customer',\n type: 'boolean',\n },\n viewedBySales: {\n title: 'Viewed by Sales',\n type: 'boolean',\n },\n seller: {\n title: 'Seller',\n type: ['null', 'string'],\n },\n sellerName: {\n title: 'Seller Name',\n type: ['null', 'string'],\n },\n parentQuote: {\n title: 'Parent quote',\n type: ['null', 'string'],\n },\n hasChildren: {\n title: 'Has children',\n type: ['null', 'boolean'],\n },\n childrenQuantity: {\n title: 'Children Quantity',\n type: ['null', 'number'],\n },\n },\n 'v-cache': false,\n 'v-default-fields': [\n 'referenceName',\n 'creatorEmail',\n 'creatorName',\n 'creationDate',\n 'expirationDate',\n 'lastUpdate',\n 'items',\n 'subtotal',\n 'status',\n 'seller',\n 'sellerName',\n 'parentQuote',\n 'hasChildren',\n 'childrenQuantity',\n ],\n 'v-immediate-indexing': true,\n 'v-indexed': [\n 'creatorEmail',\n 'creatorName',\n 'creationDate',\n 'expirationDate',\n 'lastUpdate',\n 'referenceName',\n 'status',\n 'organization',\n 'costCenter',\n 'salesChannel',\n 'seller',\n 'sellerName',\n 'parentQuote',\n 'hasChildren',\n ],\n}\n\n```"
}
] |
code_b2b-quotes-graphql_b08a7b0d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/index.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n ClientsConfig,\n EventContext,\n IOContext,\n ParamsContext,\n RecorderState,\n ServiceContext,\n} from '@vtex/api'\nimport { LRUCache, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { orderHandler } from './middlewares/order'\nimport { resolvers } from './resolvers'\nimport { schemaDirectives } from './resolvers/directives'\nimport type SellerQuotesController from './resolvers/utils/sellerQuotesController'\n\nconst TIMEOUT_MS = 5000\n\n// Create a LRU memory cache for the Status client.\n// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.\nconst memoryCache = new LRUCache<string, any>({ max: 5000 })\n\nmetrics.trackCache('status', memoryCache)\n\n// This is the configuration for clients available in `ctx.clients`.\nconst clients: ClientsConfig<Clients> = {\n // We pass our custom implementation of the clients bag, containing the Status client.\n implementation: Clients,\n options: {\n // All IO Clients will be initialized with these options, unless otherwise specified.\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n // This key will be merged with the default options and add this cache to our Status client.\n status: {\n memoryCache,\n },\n },\n}\n\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\n type Context = ServiceContext<Clients> & {\n vtex: IOContext & {\n sellerQuotesController?: SellerQuotesController\n }\n }\n\n type NextFn = () => Promise<unknown>\n\n // The shape of our State object found in `ctx.state`. This is used as state bag to communicate between middlewares.\n interface State {\n code: number\n }\n type EventBroadcastContext = EventContext<Clients, RecorderState>\n}\n// Export a service that defines route handlers and client options.\nexport default new Service<Clients, RecorderState, ParamsContext>({\n clients,\n events: {\n broadcasterOrder: [orderHandler],\n },\n graphql: {\n resolvers: {\n Mutation: resolvers.Mutation,\n Query: resolvers.Query,\n Quote: resolvers.Quote,\n },\n schemaDirectives,\n },\n routes: resolvers.Routes,\n})\n\n```"
}
] |
code_b2b-quotes-graphql_4b56a46f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/metrics/createQuote.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Metric } from '../clients/analytics'\nimport { B2B_METRIC_NAME } from '../clients/analytics'\n\ntype UserData = {\n orgId: string\n costId: string\n roleId: string\n}\n\ntype CreateQuoteMetricParam = {\n sessionData: SessionData\n sendToSalesRep: boolean\n userData: UserData\n quoteId: string\n quoteReferenceName: string\n creationDate: string\n}\n\ntype CreateQuoteFieldsMetric = {\n cost_center_id: string\n buyer_org_id: string\n member_email: string\n role: string\n creation_date: string\n quote_id: string\n quote_reference_name: string\n send_to_sales_rep: boolean\n}\n\nexport class CreateQuoteMetric implements Metric {\n public readonly description: string\n public readonly kind: string\n public readonly account: string\n public readonly fields: CreateQuoteFieldsMetric\n public readonly name = B2B_METRIC_NAME\n\n constructor(account: string, fields: CreateQuoteFieldsMetric) {\n this.account = account\n this.fields = fields\n this.kind = 'create-quote-graphql-event'\n this.description = 'Create Quotation Action - Graphql'\n }\n}\n\nconst buildQuoteMetric = (\n metricsParam: CreateQuoteMetricParam\n): CreateQuoteMetric => {\n const { namespaces } = metricsParam.sessionData\n const accountName = namespaces?.account?.accountName?.value\n const userEmail = namespaces?.profile?.email?.value\n\n return new CreateQuoteMetric(accountName, {\n buyer_org_id: metricsParam.userData?.orgId,\n cost_center_id: metricsParam.userData?.costId,\n member_email: userEmail,\n role: metricsParam.userData?.roleId,\n creation_date: metricsParam.creationDate,\n quote_id: metricsParam.quoteId,\n quote_reference_name: metricsParam.quoteReferenceName,\n send_to_sales_rep: metricsParam.sendToSalesRep,\n })\n}\n\nexport const sendCreateQuoteMetric = async (\n ctx: Context,\n metricsParam: CreateQuoteMetricParam\n) => {\n const {\n clients: { analytics },\n } = ctx\n\n try {\n const metric = buildQuoteMetric(metricsParam)\n\n await analytics.sendMetric(metric)\n } catch (error) {\n console.warn('Unable to log Create Quote Metrics', error)\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_bccf7271
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/metrics/sendMessage.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Metric } from '../clients/analytics'\nimport { B2B_METRIC_NAME } from '../clients/analytics'\n\ntype Quote = {\n costCenter: string\n id: string\n organization: string\n}\n\ntype SendMessageMetricParam = {\n quote: Quote\n account: string\n sentTo: string\n templateName: string\n}\n\ntype SendMessageFieldsMetric = {\n cost_center_name: string\n quote_id: string\n buyer_org_name: string\n template_name: string\n sent_to: string\n sent_date: string\n}\n\nexport class SendMessageMetric implements Metric {\n public readonly description: string\n public readonly kind: string\n public readonly account: string\n public readonly fields: SendMessageFieldsMetric\n public readonly name = B2B_METRIC_NAME\n\n constructor(account: string, fields: SendMessageFieldsMetric) {\n this.account = account\n this.fields = fields\n this.kind = 'send-message-graphql-event'\n this.description = 'Send Message Action - Graphql'\n }\n}\n\nconst buildSendMessageMetric = (\n metricParam: SendMessageMetricParam\n): SendMessageMetric => {\n return new SendMessageMetric(metricParam.account, {\n buyer_org_name: metricParam.quote?.organization,\n cost_center_name: metricParam.quote?.costCenter,\n quote_id: metricParam.quote?.id,\n template_name: metricParam.templateName,\n sent_to: metricParam.sentTo,\n sent_date: new Date().toISOString(),\n })\n}\n\nexport const sendMessageMetric = async (\n ctx: Context,\n metricsParam: SendMessageMetricParam\n) => {\n const {\n clients: { analytics },\n } = ctx\n\n try {\n const metric = buildSendMessageMetric(metricsParam)\n\n await analytics.sendMetric(metric)\n } catch (error) {\n console.warn('Unable to log Send Quote Message Metrics', error)\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_8089761f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/metrics/useQuote.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Metric } from '../clients/analytics'\nimport { B2B_METRIC_NAME } from '../clients/analytics'\n\ntype UseQuoteFieldsMetric = {\n quote_id: string\n quote_reference_name: string\n order_form_id: string\n quote_creation_date: string\n quote_use_date: string\n creator_email: string\n user_email: string\n cost_center_id: string\n buyer_org_id: string\n quote_last_update: string\n}\n\nexport class UseQuoteMetric implements Metric {\n public readonly description: string\n public readonly kind: string\n public readonly account: string\n public readonly fields: UseQuoteFieldsMetric\n public readonly name = B2B_METRIC_NAME\n\n constructor(account: string, fields: UseQuoteFieldsMetric) {\n this.account = account\n this.fields = fields\n this.kind = 'use-quote-graphql-event'\n this.description = 'Use Quotation Action - Graphql'\n }\n}\n\nexport type UseQuoteMetricsParams = {\n quote: Quote\n orderFormId: string\n account: string\n userEmail: string\n}\n\nconst buildUseQuoteMetric = (\n metricsParam: UseQuoteMetricsParams\n): UseQuoteMetric => {\n const { quote, orderFormId, account, userEmail } = metricsParam\n\n return new UseQuoteMetric(account, {\n buyer_org_id: quote.organization,\n cost_center_id: quote.costCenter,\n quote_id: quote.id,\n quote_reference_name: quote.referenceName,\n order_form_id: orderFormId,\n quote_creation_date: quote.creationDate,\n quote_use_date: new Date().toISOString(),\n creator_email: quote.creatorEmail,\n user_email: userEmail,\n quote_last_update: quote.lastUpdate,\n })\n}\n\nexport const sendUseQuoteMetric = async (\n ctx: Context,\n metricsParam: UseQuoteMetricsParams\n) => {\n const {\n clients: { analytics },\n } = ctx\n\n try {\n const metric = buildUseQuoteMetric(metricsParam)\n\n await analytics.sendMetric(metric)\n } catch (error) {\n console.warn('Unable to log metrics', error)\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_0100d51d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/metrics/auth.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Logger } from '@vtex/api/lib/service/logger/logger'\n\nimport type { Metric } from '../clients/analytics'\nimport { B2B_METRIC_NAME } from '../clients/analytics'\n\nexport interface AuthAuditMetric {\n operation: string\n forwardedHost: string\n caller: string\n userAgent: string\n role?: string\n permissions?: string[]\n hasAdminToken?: boolean\n hasValidAdminToken?: boolean\n hasStoreToken?: boolean\n hasCurrentValidStoreToken?: boolean\n hasValidStoreToken?: boolean\n hasApiToken?: boolean\n hasValidApiToken?: boolean\n hasAdminTokenOnHeader?: boolean\n hasValidAdminTokenOnHeader?: boolean\n}\n\nexport class AuthMetric implements Metric {\n public readonly description: string\n public readonly kind: string\n public readonly account: string\n public readonly fields: AuthAuditMetric\n public readonly name = B2B_METRIC_NAME\n\n constructor(account: string, fields: AuthAuditMetric, description?: string) {\n this.account = account\n this.fields = fields\n this.kind = 'b2b-quotes-graphql-auth-event'\n this.description = description ?? 'Auth metric event'\n }\n}\n\nconst sendAuthMetric = async (\n ctx: Context,\n logger: Logger,\n authMetric: AuthMetric\n) => {\n const {\n clients: { analytics },\n } = ctx\n\n try {\n await analytics.sendMetric(authMetric)\n } catch (error) {\n logger.error({\n error,\n message: `Error to send metrics from auth metric`,\n })\n }\n}\n\nexport default sendAuthMetric\n\n```"
}
] |
code_b2b-quotes-graphql_3b92631a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/SellerQuotesClient.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nconst SELLER_CLIENT_OPTIONS: InstanceOptions = {\n retries: 5,\n timeout: 5000,\n exponentialTimeoutCoefficient: 2,\n exponentialBackoffCoefficient: 2,\n initialBackoffDelay: 100,\n}\n\nconst BASE_PATH = 'b2b-seller-quotes/_v/0'\n\nconst ROUTES = {\n verifyQuoteSettings: 'verify-quote-settings',\n notifyNewQuote: 'notify-new-quote',\n}\n\nexport default class SellerQuotesClient extends ExternalClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super('', ctx, {\n ...options,\n ...SELLER_CLIENT_OPTIONS,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n VtexIdclientAutCookie: ctx.authToken,\n },\n })\n }\n\n private getRoute(sellerAccount: string, path: string) {\n const subdomain = this.context.production\n ? sellerAccount\n : `${this.context.workspace}--${sellerAccount}`\n\n return `http://${subdomain}.myvtex.com/${BASE_PATH}/${path}`\n }\n\n public async verifyQuoteSettings(sellerAccount: string) {\n return this.http.get<VerifyQuoteSettingsResponse>(\n this.getRoute(sellerAccount, ROUTES.verifyQuoteSettings)\n )\n }\n\n public async notifyNewQuote(\n sellerAccount: string,\n quoteId: string,\n creationDate: string\n ) {\n const payload: SellerQuoteNotifyInput = {\n quoteId,\n creationDate,\n marketplaceAccount: this.context.account,\n }\n\n return this.http.postRaw(\n this.getRoute(sellerAccount, ROUTES.notifyNewQuote),\n payload\n )\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_65ecfe6b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/storefrontPermissions.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { AppGraphQLClient } from '@vtex/api'\n\nimport { getTokenToHeader } from './index'\n\nexport const QUERIES = {\n getPermission: `query permissions {\n checkUserPermission {\n role {\n id\n name\n slug\n }\n permissions\n }\n }`,\n getRole: `query role($id: ID!) {\n getRole(id: $id) {\n id\n name\n slug\n }\n }`,\n getUser: `query user($id: ID!) {\n getUser(id: $id) {\n id\n roleId\n userId\n clId\n orgId\n costId\n name\n email\n canImpersonate\n }\n }`,\n listRoles: `query roles {\n listRoles {\n id\n name\n slug\n }\n }`,\n getOrgSalesAdminEmail: `query users($organizationId: ID, $roleId: ID) {\n listUsersPaginated(organizationId: $organizationId, roleId: $roleId) {\n data {\n email\n }\n }\n }`,\n}\n\nexport default class StorefrontPermissions extends AppGraphQLClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super('vtex.storefront-permissions@3.x', ctx, options)\n }\n\n public checkUserPermission = async (): Promise<any> => {\n return this.query({\n extensions: this.getPersistedQuery(),\n query: QUERIES.getPermission,\n variables: {},\n })\n }\n\n public listRoles = async (): Promise<any> => {\n return this.query({\n extensions: this.getPersistedQuery(),\n query: QUERIES.listRoles,\n variables: {},\n })\n }\n\n public getOrgSalesAdminEmail = async ({\n roleId,\n organizationId,\n }: {\n roleId: string\n organizationId?: string\n }): Promise<any> => {\n return this.query({\n extensions: this.getPersistedQuery(),\n query: QUERIES.getOrgSalesAdminEmail,\n variables: {\n roleId,\n ...(organizationId && { organizationId }),\n },\n })\n }\n\n private readonly getPersistedQuery = () => {\n return {\n persistedQuery: {\n provider: 'vtex.storefront-permissions@3.x',\n sender: 'vtex.b2b-quotes@3.x',\n },\n }\n }\n\n private readonly query = async (param: {\n query: string\n variables: any\n extensions: any\n }): Promise<any> => {\n const { query, variables, extensions } = param\n\n return this.graphql.query(\n {\n extensions,\n query,\n variables,\n },\n {\n headers: getTokenToHeader(this.context),\n params: {\n locale: this.context.locale,\n },\n }\n )\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_b99833fe
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/analytics.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nconst ENDPOINT = 'http://rc.vtex.com'\nconst METRICS_PATH = '/api/analytics/schemaless-events'\nconst MAX_RETRIES = 2\nconst RETRY_INTERVAL = 1000 // 1 second\n\nexport const B2B_METRIC_NAME = 'b2b-suite-buyerorg-data'\n\nexport interface Metric {\n readonly account: string\n readonly kind: string\n readonly description: string\n readonly name: typeof B2B_METRIC_NAME\n}\n\nexport default class AnalyticsClient extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(ENDPOINT, context, {\n ...options,\n headers: {\n 'X-Vtex-Use-Https': 'true',\n },\n })\n }\n\n public async sendMetric(metric: Metric, retries = 0) {\n try {\n await this.http.post(METRICS_PATH, metric)\n } catch (error) {\n if (retries < MAX_RETRIES) {\n await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL))\n await this.sendMetric(metric, retries + 1)\n } else {\n throw new Error(`${error.message} - after ${MAX_RETRIES} retries.`)\n }\n }\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_b93ed692
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/organizations.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { AppGraphQLClient } from '@vtex/api'\n\nimport { getTokenToHeader } from './index'\n\nexport default class Organizations extends AppGraphQLClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super('vtex.b2b-organizations-graphql@2.x', ctx, options)\n }\n\n public getOrganizationById = async (id: string): Promise<any> => {\n const graphQLQuery = `query GetOrganizationById($id: ID!) {\n getOrganizationById(id: $id) {\n name\n }\n }\n `\n\n return this.query({\n extensions: this.getPersistedQuery(),\n query: graphQLQuery,\n variables: {\n id,\n },\n })\n }\n\n public getCostCenterById = async (id: string): Promise<any> => {\n const graphQLQuery = `query GetCostCenterById($id: ID!) {\n getCostCenterById(id: $id) {\n name\n }\n }\n `\n\n return this.query({\n extensions: this.getPersistedQuery(),\n query: graphQLQuery,\n variables: {\n id,\n },\n })\n }\n\n private readonly getPersistedQuery = () => {\n return {\n persistedQuery: {\n provider: 'vtex.b2b-organizations-graphql@2.x',\n sender: 'vtex.b2b-quotes@3.x',\n },\n }\n }\n\n private readonly query = async (param: {\n query: string\n variables: any\n extensions: any\n }): Promise<any> => {\n const { query, variables, extensions } = param\n\n return this.graphql.query(\n {\n extensions,\n query,\n variables,\n },\n {\n headers: getTokenToHeader(this.context),\n params: {\n locale: this.context.locale,\n },\n }\n )\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_24dd7516
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/HostClient.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nexport default class HostClient extends JanusClient {\n private readonly ctx: IOContext\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...(ctx.adminUserAuthToken\n ? {\n VtexIdclientAutCookie: ctx.adminUserAuthToken,\n }\n : {}),\n },\n })\n this.ctx = ctx\n }\n\n public getHost = async (): Promise<any> => {\n const { account, workspace } = this.ctx\n const link = `http://${workspace}--${account}.myvtex.com/b2b-quotes-graphql/_v/0/host`\n\n return this.http.get(link)\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_2c486f52
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/checkout.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n InstanceOptions,\n IOContext,\n RequestTracingConfig,\n} from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nimport { APP_NAME } from '../constants'\nimport { createTracing } from '../utils/index'\n\nconst CHECKOUT_ENDPOINT = 'api/checkout/pvt/configuration/orderForm'\n\nexport default class Checkout extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...(ctx.adminUserAuthToken\n ? {\n VtexIdclientAutCookie: ctx.adminUserAuthToken,\n }\n : {}),\n },\n })\n }\n\n public getOrderFormConfiguration(tracingConfig?: RequestTracingConfig) {\n const metric = `${APP_NAME}-getOrderForm`\n\n return this.http.get<OrderFormConfiguration>(CHECKOUT_ENDPOINT, {\n metric,\n tracing: createTracing(metric, tracingConfig),\n })\n }\n\n public setOrderFormConfiguration(\n body: OrderFormConfiguration,\n userToken: string,\n tracingConfig?: RequestTracingConfig\n ) {\n const metric = `${APP_NAME}-setOrderForm`\n\n return this.http.post(CHECKOUT_ENDPOINT, body, {\n headers: {\n VtexIdclientAutCookie: userToken,\n },\n metric,\n tracing: createTracing(metric, tracingConfig),\n })\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_b7df18e6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/email.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nconst MAIL_SERVICE_PATH = '/api/mail-service/pvt/sendmail'\nconst TEMPLATE_RENDER_PATH = '/api/template-render/pvt/templates'\n\nexport default class MailClient extends JanusClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n VtexIdClientAutCookie: context.authToken,\n },\n })\n }\n\n public async sendMail(mailData: MailData): Promise<string> {\n return this.http.post(MAIL_SERVICE_PATH, mailData, {\n metric: 'mail-post-send',\n })\n }\n\n public getTemplate(name: string) {\n return this.http.get<Template>(`${TEMPLATE_RENDER_PATH}/${name}`, {\n metric: 'mail-get-template',\n })\n }\n\n public publishTemplate(template: Template) {\n return this.http.post(TEMPLATE_RENDER_PATH, template, {\n metric: 'mail-post-template',\n })\n }\n}\n\nexport interface MailData {\n templateName: string\n jsonData: JsonData\n}\n\nexport interface JsonData {\n message: {\n to: string\n }\n quote: JsonDataQuote\n}\n\nexport type JsonDataQuote = {\n name: string\n id: string\n link: string\n organization: string\n costCenter: string\n lastUpdate: {\n email: string\n status: string\n note?: string\n }\n expired?: boolean\n}\n\ninterface Template {\n AccountId?: string\n AccountName?: string\n ApplicationId?: string\n Description?: string\n FriendlyName: string\n IsDefaultTemplate: boolean\n IsPersisted: boolean\n IsRemoved: boolean\n Name: string\n Type: string\n Templates: {\n email: {\n To: string\n CC?: string\n BCC?: string\n Subject: string\n Message: string\n Type: string\n ProviderId: string\n ProviderName?: string\n IsActive: boolean\n withError: boolean\n }\n sms: {\n Type: string\n ProviderId?: string\n ProviderName?: string\n IsActive: boolean\n withError: boolean\n Parameters: string[]\n }\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_474376c4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/vtexId.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\ninterface AuthenticatedUser {\n user: string\n}\n\nexport default class VtexId extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super('http://vtexid.vtex.com.br/api/', context, options)\n }\n\n public async getAuthenticatedUser(\n authToken: string\n ): Promise<AuthenticatedUser> {\n return this.http.get('vtexid/pub/authenticated/user/', {\n metric: 'authenticated-user-get',\n params: { authToken },\n })\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_e5ff325f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/OrdersClient.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nconst FOUR_SECONDS = 4 * 1000\n\nexport default class OrdersClient extends ExternalClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(`http://${ctx.account}.vtexcommercestable.com.br`, ctx, {\n ...options,\n timeout: FOUR_SECONDS,\n })\n }\n\n public getOrder = (orderId: string): Promise<Order> =>\n this.http.get(`/api/oms/pvt/admin/orders/${orderId}`, {\n headers: {\n VtexIdclientAutCookie: this.context.authToken,\n },\n metric: 'ordersClient-getOrder',\n })\n}\n\n```"
}
] |
code_b2b-quotes-graphql_ea9de08e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/LMClient.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nexport default class LMClient extends ExternalClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(`http://${ctx.account}.vtexcommercestable.com.br/`, ctx, {\n ...options,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n VtexIdclientAutCookie: ctx.authToken,\n },\n })\n }\n\n public getUserAdminPermissions = async (account: string, userId: string) => {\n return this.get(\n `/api/license-manager/pvt/accounts/${encodeURI(\n account\n )}/logins/${encodeURI(userId)}/granted`\n ).then((res: any) => {\n return res\n })\n }\n\n protected get = <T>(url: string) => {\n return this.http.get<T>(url)\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_241afb41
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/index.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { IOContext } from '@vtex/api'\nimport { IOClients } from '@vtex/api'\n\nimport AnalyticsClient from './analytics'\nimport RequestHub from '../utils/Hub'\nimport Identity from '../utils/Identity'\nimport { Scheduler } from '../utils/Scheduler'\nimport Checkout from './checkout'\nimport LMClient from './LMClient'\nimport MailClient from './email'\nimport HostClient from './HostClient'\nimport OrdersClient from './OrdersClient'\nimport Organizations from './organizations'\nimport StorefrontPermissions from './storefrontPermissions'\nimport VtexId from './vtexId'\nimport SellerQuotesClient from './SellerQuotesClient'\nimport SellerClient from './SellerClient'\n\nexport const getTokenToHeader = (ctx: IOContext) => {\n // provide authToken (app token) as an admin token as this is a call\n // between b2b suite apps and no further token validation is needed\n const adminToken = ctx.authToken\n const userToken = ctx.storeUserAuthToken ?? null\n const { sessionToken, account } = ctx\n\n let allCookies = `VtexIdclientAutCookie=${adminToken}`\n\n if (userToken) {\n allCookies += `; VtexIdclientAutCookie_${account}=${userToken}`\n }\n\n return {\n 'x-vtex-credential': ctx.authToken,\n VtexIdclientAutCookie: adminToken,\n cookie: allCookies,\n ...(sessionToken && {\n 'x-vtex-session': sessionToken,\n }),\n }\n}\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get analytics() {\n return this.getOrSet('analytics', AnalyticsClient)\n }\n\n public get hub() {\n return this.getOrSet('hub', RequestHub)\n }\n\n public get vtexId() {\n return this.getOrSet('vtexId', VtexId)\n }\n\n public get checkout() {\n return this.getOrSet('checkout', Checkout)\n }\n\n public get lm() {\n return this.getOrSet('lm', LMClient)\n }\n\n public get mail() {\n return this.getOrSet('mail', MailClient)\n }\n\n public get organizations() {\n return this.getOrSet('organizations', Organizations)\n }\n\n public get storefrontPermissions() {\n return this.getOrSet('storefrontPermissions', StorefrontPermissions)\n }\n\n public get scheduler() {\n return this.getOrSet('scheduler', Scheduler)\n }\n\n public get orders() {\n return this.getOrSet('orders', OrdersClient)\n }\n\n public get host() {\n return this.getOrSet('host', HostClient)\n }\n\n public get identity() {\n return this.getOrSet('identity', Identity)\n }\n\n public get sellerQuotes() {\n return this.getOrSet('sellerQuotes', SellerQuotesClient)\n }\n\n public get seller() {\n return this.getOrSet('seller', SellerClient)\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_c0e608c3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/clients/SellerClient.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { IOContext, InstanceOptions } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nexport default class SellerClient extends JanusClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n ...options?.headers,\n VtexIdclientAutcookie: context.authToken,\n },\n })\n }\n\n public async getSeller(sellerId: string) {\n return this.http.get<Seller>(`/api/seller-register/pvt/sellers/${sellerId}`)\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_f0e9fa8b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/typings/orders.d.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Order {\n followUpEmail?: string\n orderId: string\n clientProfileData: ClientProfileData\n creationDate: string\n items: OrderItem[]\n value: number\n totals: Total[]\n status: string\n statusDescription: string\n sequence: string\n salesChannel: string\n affiliateId: string | null\n origin: string | null\n authorizedDate: string | null\n invoicedDate: string | null\n marketingData?: MarketingData\n shippingData: ShippingData\n paymentData: PaymentData\n checkedInPickupPointId: number\n fulfillment?: Fulfillment\n customData: { customApps: any[] }\n}\n\ninterface ClientProfileData {\n email: string\n firstName: string\n lastName: string\n documentType: string\n document: string\n phone: string\n corporateName: string | null\n tradeName: string | null\n corporateDocument: string | null\n stateInscription: string | null\n corporatePhone: string | null\n isCorporate: boolean\n userProfileId: string | null\n}\n\ninterface OrderItem {\n seller: string\n quantity: number\n description: string | null\n ean: string | null\n refId: string | null\n id: string\n productId: string | null\n sellingPrice: number\n listPrice: number\n price: number\n imageUrl: string | null\n skuName: string | null\n name: string\n bundleItems: Bundle[]\n additionalInfo: ItemAdditionalInfo\n}\n\ninterface Bundle {\n id: string\n attachments: Attachment[]\n name: string\n price: number\n quantity: number\n imageUrl: string | null\n measurementUnit: string\n unitMultiplier: number\n}\n\ninterface Total {\n id: string\n name: string\n value: number\n}\n\ninterface MarketingData {\n coupon: string\n}\n\n```"
}
] |
code_b2b-quotes-graphql_ca4a1f96
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/middlewares/order.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { QUOTE_DATA_ENTITY, QUOTE_FIELDS, SCHEMA_VERSION } from '../constants'\nimport SellerQuotesController from '../resolvers/utils/sellerQuotesController'\nimport { isEmail, NO_REPLY_EMAIL } from '../utils'\nimport message from '../utils/message'\n\nexport async function orderHandler(\n ctx: EventBroadcastContext,\n next: () => Promise<unknown>\n) {\n const {\n clients: { orders, masterdata, host: hostClient },\n vtex: { logger },\n body,\n } = ctx\n\n let order: Order = {} as Order\n\n if (body.currentState !== 'order-created') {\n return next()\n }\n\n const { host } = await hostClient.getHost()\n\n ctx.vtex.host = host\n let id\n\n try {\n order = await orders.getOrder(body.orderId)\n if (!order || !order.status || !order.items) {\n return\n }\n\n // update to placed order\n const { customData } = order\n const index = customData?.customApps?.findIndex(\n (item) => item.id === 'b2b-quotes-graphql'\n )\n\n if (index !== -1 && customData && customData.customApps) {\n const { quoteId } = customData?.customApps[index].fields\n\n id = quoteId\n\n if (quoteId && quoteId.length > 1) {\n const item = (await masterdata.getDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: QUOTE_FIELDS,\n id: quoteId,\n })) as Quote\n\n const quotes: Quote[] = []\n\n quotes.push(item)\n\n if (item.hasChildren) {\n const sellerQuotesController = new SellerQuotesController(ctx)\n const childrenQuotes = await sellerQuotesController.getAllChildrenQuotes(\n quoteId\n )\n\n quotes.push(...childrenQuotes)\n }\n\n await Promise.all(\n quotes.map((quote) => processQuote(ctx, order, quote))\n )\n }\n }\n } catch (error) {\n logger.error({\n data: ctx.body,\n error,\n message: 'OrderHandler-updateQuoteStatusError',\n id,\n })\n }\n\n return next()\n}\n\nasync function processQuote(\n ctx: EventBroadcastContext,\n order: Order,\n quote: Quote\n) {\n const { orderId } = order\n\n const mustAddUpdateHistory =\n !quote.seller ||\n (quote.seller && order.items.some((item) => item.seller === quote.seller))\n\n if (mustAddUpdateHistory) {\n quote.updateHistory.push({\n date: new Date().toISOString(),\n email: NO_REPLY_EMAIL,\n note: `Order ID: ${orderId}`,\n role: 'order-notification-system',\n status: 'placed',\n })\n }\n\n const quoteUpdated = {\n ...quote,\n status: 'placed',\n updateHistory: quote.updateHistory,\n }\n\n await ctx.clients.masterdata.updateEntireDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: quoteUpdated,\n id: quote.id,\n schema: SCHEMA_VERSION,\n })\n\n // just users from single or children quotes need to be notified\n if (quote.hasChildren) return\n\n const users = quoteUpdated.updateHistory.map((anUpdate) => anUpdate.email)\n\n const uniqueUsers = [\n ...new Set(users.filter((userEmail: string) => isEmail.test(userEmail))),\n ]\n\n message(ctx)\n .quoteUpdated({\n costCenter: quoteUpdated.costCenter,\n id: quote.id,\n lastUpdate: {\n email: 'order-notification-system',\n note: `Order ID: ${orderId}`,\n status: 'PLACED',\n },\n name: quoteUpdated.referenceName,\n orderId,\n organization: quoteUpdated.organization,\n templateName: 'quote-order-placed',\n users: uniqueUsers,\n })\n .then(() => {\n ctx.vtex.logger.info({\n message: `[Quote placed] E-mail sent ${uniqueUsers.join(', ')}`,\n })\n })\n}\n\n```"
}
] |
code_b2b-quotes-graphql_a2627639
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/utils/Identity.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nexport default class Identity extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n },\n })\n }\n\n public async validateToken(token: string): Promise<any> {\n return this.http.post('/api/vtexid/credential/validate', { token })\n }\n\n public async getToken({\n appkey,\n apptoken,\n }: {\n appkey: string\n apptoken: string\n }): Promise<any> {\n return this.http.post('/api/vtexid/apptoken/login', { appkey, apptoken })\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_70399723
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/utils/readFile.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport fs from 'fs'\nimport path from 'path'\n\nconst readFile = (filePath: string) =>\n fs.readFileSync(path.resolve(__dirname, filePath), 'utf8')\n\nexport default readFile\n\n```"
}
] |
code_b2b-quotes-graphql_e91c65fa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/utils/Scheduler.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { JanusClient } from '@vtex/api'\nimport type { InstanceOptions, IOContext } from '@vtex/api'\n\nconst VERSION = 4\n\nconst routes = {\n getQueueSchedule: (workspace: string, account: string) =>\n `/api/scheduler/${workspace}/${account}/b2b-quotes-queue-schedule?version=${VERSION}`,\n getSyncSchedule: (workspace: string, account: string) =>\n `/api/scheduler/${workspace}/${account}/b2b-quotes-sync-schedule?version=${VERSION}`,\n scheduler: (workspace: string, account: string) =>\n `/api/scheduler/${workspace}/${account}?version=${VERSION}`,\n}\n\nexport class Scheduler extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n VtexIdclientAutCookie: ctx.authToken,\n },\n })\n }\n\n public createOrUpdate = (scheduler: any) => {\n return this.http.put(\n routes.scheduler(this.context.workspace, this.context.account),\n scheduler,\n {\n metric: 'b2b-quotes-scheduler-createupdate',\n }\n )\n }\n\n public getQueue = () => {\n return this.http.get(\n routes.getQueueSchedule(this.context.workspace, this.context.account),\n {\n metric: 'b2b-quotes-scheduler-get',\n }\n )\n }\n\n public deleteQueue = () => {\n return this.http.delete(\n routes.getQueueSchedule(this.context.workspace, this.context.account),\n {\n metric: 'b2b-quotes-scheduler-delete',\n }\n )\n }\n\n public getSync = () => {\n return this.http.get(\n routes.getSyncSchedule(this.context.workspace, this.context.account),\n {\n metric: 'b2b-quotes-scheduler-get',\n }\n )\n }\n\n public deleteSync = () => {\n return this.http.delete(\n routes.getSyncSchedule(this.context.workspace, this.context.account),\n {\n metric: 'b2b-quotes-scheduler-delete',\n }\n )\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_7fa306f2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/utils/Hub.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nexport default class RequestHub extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(\n `http://${context.account}.vtexcommercestable.com.br/api/`,\n context,\n options\n )\n }\n\n public authToken() {\n return this.context.authToken\n }\n\n public account() {\n return this.context.account\n }\n\n public get(url: string, headers: any, data?: any) {\n return this.http.getRaw(url, {\n data,\n headers,\n })\n }\n\n public post(url: string, data: any, headers?: any) {\n return this.http.postRaw(url, data, {\n headers,\n })\n }\n\n public put(url: string, data: any, headers?: any) {\n return this.http.putRaw(url, data, {\n headers,\n })\n }\n\n public delete(url: string) {\n return this.http.delete(url)\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_78ac0da1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/utils/message.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { JsonDataQuote } from '../clients/email'\nimport type MailClient from '../clients/email'\nimport type StorefrontPermissions from '../clients/storefrontPermissions'\nimport { sendMessageMetric } from '../metrics/sendMessage'\n\ninterface QuoteUpdate {\n email: string\n status: string\n note: string\n}\n\n// As this is currently used only to get the sales-admin users to\n// send an email notification when a quote is created, we only get\n// the first page of users (25) and return them.\nconst getOrgSalesAdminEmail = async (\n storefrontPermissions: StorefrontPermissions,\n organizationId?: string\n) => {\n const {\n data: { listRoles },\n }: any = await storefrontPermissions.listRoles()\n\n const role = listRoles.find((r: any) => r.slug === 'sales-admin')\n\n if (!role) {\n return []\n }\n\n const {\n data: { listUsersPaginated },\n }: any = await storefrontPermissions.getOrgSalesAdminEmail({\n roleId: role.id,\n ...(organizationId && { organizationId }),\n })\n\n // we only return the first page of sales-admin users (25)\n return listUsersPaginated.data\n}\n\nconst getOrgAndCostCenterNames = async (\n ctx: Context | EventBroadcastContext,\n organizationId: string,\n costCenterId: string\n) => {\n const {\n clients: { organizations },\n vtex: { logger },\n } = ctx\n\n try {\n const {\n data: {\n getOrganizationById: { name: organizationName },\n },\n } = await organizations.getOrganizationById(organizationId)\n\n const {\n data: {\n getCostCenterById: { name: costCenterName },\n },\n } = await organizations.getCostCenterById(costCenterId)\n\n return { organizationName, costCenterName }\n } catch (error) {\n logger.error({\n error,\n message: 'quoteUpdatedMessage-getOrgNamesError',\n })\n\n return { organizationName: null, costCenterName: null }\n }\n}\n\nconst sendNotificationToUser = async (\n ctx: Context,\n mailClient: MailClient,\n user: string,\n quote: JsonDataQuote,\n templateName: string,\n account: string\n) => {\n await mailClient.sendMail({\n jsonData: {\n message: { to: user },\n quote,\n },\n templateName,\n })\n\n sendMessageMetric(ctx, {\n quote,\n account,\n sentTo: user,\n templateName,\n })\n}\n\nconst sendMailNotificationToUsers = async (\n ctx: Context | EventBroadcastContext,\n { quote, mail: sender, users }: any,\n templateName: string\n) => {\n const {\n vtex: { logger },\n } = ctx\n\n try {\n const promises = []\n\n for (const user of users) {\n promises.push(\n sendNotificationToUser(\n ctx as Context,\n sender,\n user,\n quote,\n templateName,\n sender.context.account\n )\n )\n }\n\n return Promise.all(promises)\n } catch (error) {\n logger.error({\n error,\n message: 'sendMailNotificationToUsers-Error',\n })\n }\n\n return false\n}\n\nconst message = (ctx: Context | EventBroadcastContext) => {\n const {\n clients: { mail, storefrontPermissions },\n vtex: { logger, host },\n } = ctx\n\n let rootPath = 'get' in ctx ? ctx.get('x-vtex-root-path') : '/'\n\n // Defend against malformed root path. It should always start with `/`.\n if (rootPath && !rootPath.startsWith('/')) {\n rootPath = `/${rootPath}`\n }\n\n if (rootPath === '/') {\n rootPath = ''\n }\n\n const quoteCreated = async ({\n name,\n id,\n organization,\n costCenter,\n lastUpdate,\n }: {\n name: string\n id: string\n organization: string\n costCenter: string\n lastUpdate: QuoteUpdate\n }) => {\n let users = []\n\n try {\n users = (\n await getOrgSalesAdminEmail(storefrontPermissions, organization)\n ).map((user: any) => user.email)\n } catch (error) {\n logger.error({\n error,\n message: 'quoteCreatedMessage-getOrgSalesAdminEmailError',\n })\n }\n\n const { organizationName, costCenterName } = await getOrgAndCostCenterNames(\n ctx,\n organization,\n costCenter\n )\n\n if (!organizationName || !costCenterName || users.length === 0) {\n return\n }\n\n const link = `https://${host}${rootPath}/b2b-quotes/${id}`\n const quote = {\n costCenter: costCenterName,\n id,\n lastUpdate,\n link,\n name,\n organization: organizationName,\n }\n\n return sendMailNotificationToUsers(\n ctx,\n { quote, mail, users },\n 'quote-created'\n )\n }\n\n const quoteUpdated = async ({\n users,\n name,\n id,\n organization,\n costCenter,\n lastUpdate,\n templateName = 'quote-updated',\n orderId = '',\n }: {\n users: string[]\n name: string\n id: string\n organization: string\n costCenter: string\n lastUpdate: QuoteUpdate\n templateName?: string\n orderId?: string\n }) => {\n const { organizationName, costCenterName } = await getOrgAndCostCenterNames(\n ctx,\n organization,\n costCenter\n )\n\n if (!organizationName || !costCenterName) {\n return\n }\n\n const link = `https://${host}${rootPath}/b2b-quotes/${id}`\n const quote = {\n costCenter: costCenterName,\n id,\n lastUpdate,\n link,\n name,\n orderId,\n organization: organizationName,\n }\n\n return sendMailNotificationToUsers(\n ctx,\n { quote, mail, users, ctx },\n templateName\n )\n }\n\n return {\n quoteCreated,\n quoteUpdated,\n }\n}\n\nexport default message\n\n```"
}
] |
code_b2b-quotes-graphql_0776f91b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/utils/GraphQLError.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport default class GraphQLError extends Error {\n public extensions: any\n\n constructor(message: string, details?: any) {\n super(message)\n this.extensions = { message, ...details }\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_ec8df217
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/utils/index.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport * as crypto from 'crypto'\n\nimport type { RequestTracingConfig } from '@vtex/api'\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\nimport type { AxiosError } from 'axios'\n\nexport const toHash = (obj: any) => {\n return crypto.createHash('md5').update(JSON.stringify(obj)).digest('hex')\n}\n\nexport const NO_REPLY_EMAIL = 'noreply@vtexcommerce.com.br'\n\nexport function statusToError(e: any) {\n if (!e.response) {\n throw e\n }\n\n const { response } = e as AxiosError\n const { status } = response!\n\n if (status === 401) {\n throw new AuthenticationError(e)\n }\n\n if (status === 403) {\n throw new ForbiddenError(e)\n }\n\n if (status === 400) {\n throw new UserInputError(e)\n }\n\n throw e\n}\n\nexport const isEmail = new RegExp(/[a-z0-9]+@[a-z]+.[a-z]{2,3}/)\n\nexport const createTracing = (\n metric: string,\n tracingConfig?: RequestTracingConfig\n) => ({\n requestSpanNameSuffix: metric,\n ...tracingConfig?.tracing,\n})\n\n```"
}
] |
code_b2b-quotes-graphql_2724065a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/utils/Queue.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { QUOTE_DATA_ENTITY, QUOTE_FIELDS, SCHEMA_VERSION } from '../constants'\nimport { NO_REPLY_EMAIL } from './index'\nimport message from './message'\n\nconst processItem = ({\n ctx,\n item,\n baseDate,\n index,\n}: {\n ctx: Context\n item: Quote\n baseDate: Date\n index: number\n}) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const { id, referenceName, organization, costCenter, updateHistory } = item\n\n if (item.status === 'placed' || item.status === 'declined') {\n return\n }\n\n const status = 'expired'\n const now = new Date(baseDate)\n\n now.setSeconds(now.getSeconds() + index)\n\n const nowISO = now.toISOString()\n\n const users = updateHistory.map((anUpdate) => anUpdate.email)\n const uniqueUsers = [...new Set(users)]\n\n const lastUpdate = nowISO\n const update = {\n date: nowISO,\n email: NO_REPLY_EMAIL,\n note: '',\n role: 'expiration-system',\n status,\n }\n\n updateHistory.push(update)\n\n masterdata\n .updatePartialDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: { lastUpdate, updateHistory, status },\n id,\n schema: SCHEMA_VERSION,\n })\n .then(() => {\n message(ctx).quoteUpdated({\n costCenter,\n id,\n lastUpdate: {\n email: 'expiration-system',\n note: '',\n status: status.toUpperCase(),\n },\n name: referenceName,\n organization,\n users: uniqueUsers,\n })\n })\n .catch((error) => {\n logger.error({ message: 'quoteExpired-Error', error })\n })\n}\n\nexport const processQueue = (ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const now = new Date()\n const nowISO = now.toISOString()\n\n masterdata\n .searchDocuments({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: QUOTE_FIELDS,\n pagination: {\n page: 1,\n pageSize: 500,\n },\n schema: SCHEMA_VERSION,\n sort: 'creationDate ASC',\n where: `status <> 'expired' AND expirationDate < ${nowISO}`,\n })\n .then((data: any) => {\n if (Array.isArray(data)) {\n logger.info({\n itemsToBeProcessed: data.length,\n message: `expirationQueue-foundItems`,\n })\n\n data.forEach((item, index) => {\n processItem({ ctx, item, index, baseDate: now })\n })\n }\n })\n .catch((error) => {\n logger.error({ message: 'expirationQueue-error', error })\n throw error\n })\n}\n\n```"
}
] |
code_b2b-quotes-graphql_1d539efa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/directives.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { AuditAccess } from './directives/auditAccess'\nimport { ValidateAdminUserAccess } from './directives/validateAdminUserAccess'\nimport { ValidateStoreUserAccess } from './directives/validateStoreUserAccess'\nimport { WithPermissions } from './directives/withPermissions'\nimport { WithSegment } from './directives/withSegment'\nimport { WithSession } from './directives/withSession'\n\nexport const schemaDirectives = {\n withPermissions: WithPermissions as any,\n withSession: WithSession as any,\n withSegment: WithSegment as any,\n validateAdminUserAccess: ValidateAdminUserAccess as any,\n validateStoreUserAccess: ValidateStoreUserAccess as any,\n auditAccess: AuditAccess as any,\n}\n\n```"
}
] |
code_b2b-quotes-graphql_4fc7fb03
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/fieldResolvers.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const organizationName = async (\n { organization }: { organization: string },\n _: any,\n ctx: Context | EventBroadcastContext\n) => {\n const {\n clients: { organizations },\n vtex: { logger },\n } = ctx\n\n try {\n const organizationData = await organizations.getOrganizationById(\n organization\n )\n\n return organizationData?.data?.getOrganizationById?.name ?? null\n } catch (error) {\n logger.warn({\n error,\n message: 'getOrganizationName-error',\n })\n }\n}\n\nexport const costCenterName = async (\n { costCenter }: { costCenter: string },\n _: any,\n ctx: Context | EventBroadcastContext\n) => {\n const {\n clients: { organizations },\n vtex: { logger },\n } = ctx\n\n try {\n const costCenterData = await organizations.getCostCenterById(costCenter)\n\n return costCenterData?.data?.getCostCenterById?.name ?? null\n } catch (error) {\n logger.warn({\n error,\n message: 'getCostCenterName-error',\n })\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_b579628f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/index.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Routes } from './routes'\nimport { Query } from './queries'\nimport { Mutation } from './mutations'\nimport { costCenterName, organizationName } from './fieldResolvers'\n\nexport const resolvers = {\n Mutation,\n Query,\n Quote: {\n costCenterName,\n organizationName,\n },\n Routes,\n}\n\n```"
}
] |
code_b2b-quotes-graphql_f67350d0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/templates/quotePlaced.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport readFile from '../utils/readFile'\n\nconst MESSAGE_BODY = readFile('../assets/quotePlaced.html')\n\nexport const quotePlacedMessage = {\n FriendlyName: 'Quote Placed',\n IsDefaultTemplate: false,\n IsPersisted: true,\n IsRemoved: false,\n Name: 'quote-order-placed',\n // Description: null,\n // AccountId: null,\n // AccountName: null,\n // ApplicationId: null,\n Templates: {\n email: {\n IsActive: true,\n Message: MESSAGE_BODY,\n ProviderId: '00000000-0000-0000-0000-000000000000',\n Subject: '[{{quote.organization}}] Quote Placed',\n // CC: null,\n // BCC: null,\n To: '{{message.to}}',\n Type: 'E',\n // ProviderName: null,\n withError: false,\n },\n sms: {\n // ProviderId: null,\n // ProviderName: null,\n IsActive: false,\n Parameters: [],\n Type: 'S',\n withError: false,\n },\n },\n Type: '',\n}\n\n```"
}
] |
code_b2b-quotes-graphql_feab79d5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/templates/quoteUpdated.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport readFile from '../utils/readFile'\n\nconst MESSAGE_BODY = readFile('../assets/quoteUpdated.html')\n\nexport const quoteUpdatedMessage = {\n FriendlyName: 'Quote Updated',\n IsDefaultTemplate: false,\n IsPersisted: true,\n IsRemoved: false,\n Name: 'quote-updated',\n // Description: null,\n // AccountId: null,\n // AccountName: null,\n // ApplicationId: null,\n Templates: {\n email: {\n // CC: null,\n // BCC: null,\n IsActive: true,\n Message: MESSAGE_BODY,\n ProviderId: '00000000-0000-0000-0000-000000000000',\n Subject:\n '[{{quote.organization}}] Quote {{#if quote.expired}}Expired{{else}}Updated{{/if}}',\n To: '{{message.to}}',\n Type: 'E',\n // ProviderName: null,\n withError: false,\n },\n sms: {\n IsActive: false,\n Parameters: [],\n Type: 'S',\n // ProviderId: null,\n // ProviderName: null,\n withError: false,\n },\n },\n Type: '',\n}\n\n```"
}
] |
code_b2b-quotes-graphql_0b668422
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/templates/quoteCreated.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport readFile from '../utils/readFile'\n\nconst MESSAGE_BODY = readFile('../assets/quoteCreated.html')\n\nexport const quoteCreatedMessage = {\n FriendlyName: 'Quote Created',\n IsDefaultTemplate: false,\n IsPersisted: true,\n IsRemoved: false,\n Name: 'quote-created',\n // Description: null,\n // AccountId: null,\n // AccountName: null,\n // ApplicationId: null,\n Templates: {\n email: {\n // CC: null,\n // BCC: null,\n IsActive: true,\n Message: MESSAGE_BODY,\n ProviderId: '00000000-0000-0000-0000-000000000000',\n Subject: '[{{quote.organization}}] Request for Quotation',\n To: '{{message.to}}',\n Type: 'E',\n // ProviderName: null,\n withError: false,\n },\n sms: {\n IsActive: false,\n Parameters: [],\n Type: 'S',\n // ProviderId: null,\n // ProviderName: null,\n withError: false,\n },\n },\n Type: '',\n}\n\n```"
}
] |
code_b2b-quotes-graphql_c46d4bf2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/templates/index.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { quoteCreatedMessage } from './quoteCreated'\nimport { quotePlacedMessage } from './quotePlaced'\nimport { quoteUpdatedMessage } from './quoteUpdated'\n\nconst templates = [quoteCreatedMessage, quotePlacedMessage, quoteUpdatedMessage]\n\nexport default templates\n\n```"
}
] |
code_b2b-quotes-graphql_7ee639c8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/directives/auditAccess.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nimport sendAuthMetric, { AuthMetric } from '../../metrics/auth'\nimport {\n validateAdminToken,\n validateAdminTokenOnHeader,\n validateApiToken,\n validateStoreToken,\n} from './helper'\n\nexport class AuditAccess extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (\n root: any,\n args: any,\n context: Context,\n info: any\n ) => {\n this.sendAuthMetric(field, context)\n\n return resolve(root, args, context, info)\n }\n }\n\n private async sendAuthMetric(field: GraphQLField<any, any>, context: any) {\n const {\n vtex: { adminUserAuthToken, storeUserAuthToken, logger },\n } = context\n\n const { hasAdminToken, hasValidAdminToken } = await validateAdminToken(\n context,\n adminUserAuthToken as string\n )\n\n const {\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n } = await validateAdminTokenOnHeader(context)\n\n const { hasApiToken, hasValidApiToken } = await validateApiToken(context)\n\n const { hasStoreToken, hasValidStoreToken } = await validateStoreToken(\n context,\n storeUserAuthToken as string\n )\n\n // now we emit a metric with all the collected data before we proceed\n const operation = field?.astNode?.name?.value ?? context?.request?.url\n const userAgent = context?.request?.headers['user-agent'] as string\n const caller = context?.request?.headers['x-vtex-caller'] as string\n const forwardedHost = context?.request?.headers[\n 'x-forwarded-host'\n ] as string\n\n const auditMetric = new AuthMetric(context?.vtex?.account, {\n operation,\n forwardedHost,\n caller,\n userAgent,\n hasAdminToken,\n hasValidAdminToken,\n hasApiToken,\n hasValidApiToken,\n hasStoreToken,\n hasValidStoreToken,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n })\n\n await sendAuthMetric(context, logger, auditMetric)\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_255ee333
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/directives/helper.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { isUserPartOfBuyerOrg } from '../queries/index'\n\nexport const validateAdminToken = async (\n context: Context,\n adminUserAuthToken: string\n): Promise<{\n hasAdminToken: boolean\n hasValidAdminToken: boolean\n hasCurrentValidAdminToken: boolean\n}> => {\n const {\n clients: { identity, lm },\n vtex: { account, logger },\n } = context\n\n // check if has admin token and if it is valid\n const hasAdminToken = !!adminUserAuthToken\n let hasValidAdminToken = false\n // this is used to check if the token is valid by current standards\n let hasCurrentValidAdminToken = false\n\n if (hasAdminToken) {\n try {\n const authUser = await identity.validateToken(adminUserAuthToken)\n\n // we set this flag to true if the token is valid by current standards\n // in the future we should remove this line\n hasCurrentValidAdminToken = true\n\n if (authUser?.audience === 'admin' && authUser?.account === account) {\n hasValidAdminToken = await lm.getUserAdminPermissions(\n account,\n authUser.id\n )\n }\n } catch (err) {\n // noop so we leave hasValidAdminToken as false\n logger.warn({\n message: 'Error validating admin token',\n err,\n })\n }\n }\n\n return { hasAdminToken, hasValidAdminToken, hasCurrentValidAdminToken }\n}\n\nexport const validateApiToken = async (\n context: Context\n): Promise<{\n hasApiToken: boolean\n hasValidApiToken: boolean\n hasCurrentValidApiToken: boolean\n}> => {\n const {\n clients: { identity, lm },\n vtex: { account, logger },\n } = context\n\n // check if has api token and if it is valid\n const apiToken = context?.headers['vtex-api-apptoken'] as string\n const appKey = context?.headers['vtex-api-appkey'] as string\n const hasApiToken = !!(apiToken?.length && appKey?.length)\n let hasValidApiToken = false\n\n // this is used to check if the token is valid by current standards\n let hasCurrentValidApiToken = false\n\n if (hasApiToken) {\n try {\n const { token } = await identity.getToken({\n appkey: appKey,\n apptoken: apiToken,\n })\n\n const authUser = await identity.validateToken(token)\n\n // we set this flag to true if the token is valid by current standards\n // in the future we should remove this line\n hasCurrentValidApiToken = true\n // keeping this behavior for now, but we should remove it in the future as well\n context.cookies.set('VtexIdclientAutCookie', token)\n context.vtex.adminUserAuthToken = token\n\n if (authUser?.audience === 'admin' && authUser?.account === account) {\n hasValidApiToken = await lm.getUserAdminPermissions(\n account,\n authUser.id\n )\n }\n } catch (err) {\n // noop so we leave hasValidApiToken as false\n logger.warn({\n message: 'Error validating API token',\n err,\n })\n }\n }\n\n return { hasApiToken, hasValidApiToken, hasCurrentValidApiToken }\n}\n\nexport const validateStoreToken = async (\n context: Context,\n storeUserAuthToken: string\n): Promise<{\n hasStoreToken: boolean\n hasValidStoreToken: boolean\n hasCurrentValidStoreToken: boolean\n}> => {\n const {\n clients: { vtexId },\n vtex: { logger },\n } = context\n\n // check if has store token and if it is valid\n const hasStoreToken = !!storeUserAuthToken\n let hasValidStoreToken = false\n // this is used to check if the token is valid by current standards\n let hasCurrentValidStoreToken = false\n\n if (hasStoreToken) {\n try {\n const authUser = await vtexId.getAuthenticatedUser(storeUserAuthToken)\n\n if (authUser?.user) {\n // we set this flag to true if the token is valid by current standards\n // in the future we should remove this line\n hasCurrentValidStoreToken = true\n\n const userIsPartOfBuyerOrg = await isUserPartOfBuyerOrg(\n authUser?.user,\n context\n )\n\n if (userIsPartOfBuyerOrg) {\n hasValidStoreToken = true\n }\n\n // adding log to better understand invalid store token use cases\n // in the future we should remove this log\n if (hasCurrentValidStoreToken && !hasValidStoreToken) {\n logger.warn({\n message: 'Invalid store token:',\n operation: context?.request?.url,\n userAgent: context?.request?.headers['user-agent'] as string,\n caller: context?.request?.headers['x-vtex-caller'] as string,\n forwardedHost: context?.request?.headers[\n 'x-forwarded-host'\n ] as string,\n authUser,\n })\n }\n }\n } catch (err) {\n // noop so we leave hasValidStoreToken as false\n logger.warn({\n message: 'Error validating store token:',\n err,\n })\n }\n }\n\n return { hasStoreToken, hasValidStoreToken, hasCurrentValidStoreToken }\n}\n\nexport const validateAdminTokenOnHeader = async (\n context: Context\n): Promise<{\n hasAdminTokenOnHeader: boolean\n hasValidAdminTokenOnHeader: boolean\n hasCurrentValidAdminTokenOnHeader: boolean\n}> => {\n const adminUserAuthToken = context?.headers.vtexidclientautcookie as string\n const hasAdminTokenOnHeader = !!adminUserAuthToken?.length\n\n if (!hasAdminTokenOnHeader) {\n return {\n hasAdminTokenOnHeader: false,\n hasValidAdminTokenOnHeader: false,\n hasCurrentValidAdminTokenOnHeader: false,\n }\n }\n\n const {\n hasAdminToken,\n hasCurrentValidAdminToken,\n hasValidAdminToken,\n } = await validateAdminToken(context, adminUserAuthToken)\n\n return {\n hasAdminTokenOnHeader: hasAdminToken,\n hasValidAdminTokenOnHeader: hasValidAdminToken,\n hasCurrentValidAdminTokenOnHeader: hasCurrentValidAdminToken,\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_aaa9c262
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/directives/validateAdminUserAccess.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\nimport { AuthenticationError, ForbiddenError } from '@vtex/api'\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\n\nimport type { AuthAuditMetric } from '../../metrics/auth'\nimport sendAuthMetric, { AuthMetric } from '../../metrics/auth'\nimport {\n validateAdminToken,\n validateAdminTokenOnHeader,\n validateApiToken,\n} from './helper'\n\nexport class ValidateAdminUserAccess extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (\n root: any,\n args: any,\n context: Context,\n info: any\n ) => {\n const {\n vtex: { adminUserAuthToken, logger },\n } = context\n\n // get metrics data\n const operation = field?.astNode?.name?.value ?? context?.request?.url\n const userAgent = context?.request?.headers['user-agent'] as string\n const caller = context?.request?.headers['x-vtex-caller'] as string\n const forwardedHost = context?.request?.headers[\n 'x-forwarded-host'\n ] as string\n\n // set metric fields with initial data\n let metricFields: AuthAuditMetric = {\n operation,\n forwardedHost,\n caller,\n userAgent,\n }\n\n const { hasAdminToken, hasValidAdminToken } = await validateAdminToken(\n context,\n adminUserAuthToken as string\n )\n\n // add admin token metrics\n metricFields = {\n ...metricFields,\n hasAdminToken,\n hasValidAdminToken,\n }\n\n // allow access if has valid admin token\n if (hasValidAdminToken) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateAdminUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // If there's no valid admin token on context, search for it on header\n const {\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n } = await validateAdminTokenOnHeader(context)\n\n // add admin header token metrics\n metricFields = {\n ...metricFields,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n }\n\n // allow access if has valid admin token\n if (hasValidAdminTokenOnHeader) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateAdminUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n const { hasApiToken, hasValidApiToken } = await validateApiToken(context)\n\n // add API token metrics\n metricFields = {\n ...metricFields,\n hasApiToken,\n hasValidApiToken,\n }\n\n // allow access if has valid API token\n if (hasValidApiToken) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateAdminUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // deny access if no tokens were provided\n if (!hasAdminToken && !hasAdminTokenOnHeader && !hasApiToken) {\n logger.warn({\n message: 'ValidateAdminUserAccess: No token provided',\n ...metricFields,\n })\n throw new AuthenticationError('No token was provided')\n }\n\n // deny access if no valid tokens were provided\n logger.warn({\n message: 'ValidateAdminUserAccess: Invalid token',\n ...metricFields,\n })\n throw new ForbiddenError('Unauthorized Access')\n }\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_4b58605f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/directives/withSegment.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable max-params */\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\nimport atob from 'atob'\n\nexport class WithSegment extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root: any, args: any, context: any, info: any) => {\n const {\n clients: { segment },\n vtex: { segmentToken },\n } = context\n\n context.vtex.segmentData = segmentToken\n ? JSON.parse(atob(segmentToken))\n : await segment.getSegment()\n\n return resolve(root, args, context, info)\n }\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_f82fdaef
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/directives/validateStoreUserAccess.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\nimport { AuthenticationError, ForbiddenError } from '@vtex/api'\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\n\nimport type { AuthAuditMetric } from '../../metrics/auth'\nimport sendAuthMetric, { AuthMetric } from '../../metrics/auth'\nimport {\n validateAdminToken,\n validateAdminTokenOnHeader,\n validateApiToken,\n validateStoreToken,\n} from './helper'\n\nexport class ValidateStoreUserAccess extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (\n root: any,\n args: any,\n context: Context,\n info: any\n ) => {\n const {\n vtex: { adminUserAuthToken, storeUserAuthToken, logger },\n } = context\n\n // get metrics data\n const operation = field?.astNode?.name?.value ?? context?.request?.url\n const userAgent = context?.request?.headers['user-agent'] as string\n const caller = context?.request?.headers['x-vtex-caller'] as string\n const forwardedHost = context?.request?.headers[\n 'x-forwarded-host'\n ] as string\n\n // set metric fields with initial data\n let metricFields: AuthAuditMetric = {\n operation,\n forwardedHost,\n caller,\n userAgent,\n }\n\n const { hasAdminToken, hasValidAdminToken } = await validateAdminToken(\n context,\n adminUserAuthToken as string\n )\n\n // add admin token metrics\n metricFields = {\n ...metricFields,\n hasAdminToken,\n hasValidAdminToken,\n }\n\n // allow access if has valid admin token\n if (hasValidAdminToken) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // If there's no valid admin token on context, search for it on header\n const {\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n } = await validateAdminTokenOnHeader(context)\n\n // add admin header token metrics\n metricFields = {\n ...metricFields,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n }\n\n // allow access if has valid admin token\n if (hasValidAdminTokenOnHeader) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n const { hasApiToken, hasValidApiToken } = await validateApiToken(context)\n\n // add API token metrics\n metricFields = {\n ...metricFields,\n hasApiToken,\n hasValidApiToken,\n }\n\n // allow access if has valid API token\n if (hasValidApiToken) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n const { hasStoreToken, hasValidStoreToken } = await validateStoreToken(\n context,\n storeUserAuthToken as string\n )\n\n // add store token metrics\n metricFields = {\n ...metricFields,\n hasStoreToken,\n hasValidStoreToken,\n }\n\n // allow access if has valid store token\n if (hasValidStoreToken) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // deny access if no tokens were provided\n if (!hasAdminToken && !hasApiToken && !hasStoreToken) {\n logger.warn({\n message: 'ValidateStoreUserAccess: No token provided',\n ...metricFields,\n })\n throw new AuthenticationError('No token was provided')\n }\n\n // deny access if no valid tokens were provided\n logger.warn({\n message: `ValidateStoreUserAccess: Invalid token`,\n ...metricFields,\n })\n throw new ForbiddenError('Unauthorized Access')\n }\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_bec0abab
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/directives/withSession.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable max-params */\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nexport class WithSession extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root: any, args: any, context: any, info: any) => {\n const {\n clients: { session },\n vtex: { sessionToken },\n } = context\n\n context.vtex.sessionData = await session\n .getSession(sessionToken as string, ['*'])\n .then((currentSession: any) => {\n return currentSession.sessionData\n })\n .catch(() => null)\n\n return resolve(root, args, context, info)\n }\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_a4591ec7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/directives/withPermissions.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable max-params */\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nexport class WithPermissions extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root: any, args: any, context: any, info: any) => {\n const {\n clients: { storefrontPermissions },\n vtex: { logger },\n } = context\n\n context.vtex.storefrontPermissions = await storefrontPermissions\n .checkUserPermission()\n .then((result: any) => {\n return result.data.checkUserPermission\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'getPermissionsError',\n })\n })\n\n return resolve(root, args, context, info)\n }\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_b87d983b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/mutations/index.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { indexBy, map, prop } from 'ramda'\n\nimport {\n APP_NAME,\n QUOTE_DATA_ENTITY,\n QUOTE_FIELDS,\n routes,\n SCHEMA_VERSION,\n} from '../../constants'\nimport { sendCreateQuoteMetric } from '../../metrics/createQuote'\nimport type { UseQuoteMetricsParams } from '../../metrics/useQuote'\nimport { sendUseQuoteMetric } from '../../metrics/useQuote'\nimport { isEmail } from '../../utils'\nimport GraphQLError from '../../utils/GraphQLError'\nimport message from '../../utils/message'\nimport {\n checkAndCreateQuotesConfig,\n checkConfig,\n defaultSettings,\n} from '../utils/checkConfig'\nimport {\n checkOperationsForUpdateQuote,\n checkPermissionsForUpdateQuote,\n checkQuoteStatus,\n checkSession,\n} from '../utils/checkPermissions'\nimport {\n createItemComparator,\n createQuoteObject,\n splitItemsBySeller,\n} from '../utils/quotes'\nimport SellerQuotesController from '../utils/sellerQuotesController'\n\nexport const Mutation = {\n clearCart: async (_: any, params: any, ctx: Context) => {\n const {\n vtex: { account, logger },\n clients: { hub },\n } = ctx\n\n try {\n await hub.post(routes.clearCart(account, params.orderFormId), {\n expectedOrderFormSections: ['items'],\n })\n } catch (error) {\n logger.error({\n error,\n message: 'clearCart-error',\n })\n if (error.message) {\n throw new GraphQLError(error.message)\n } else if (error.response?.data?.message) {\n throw new GraphQLError(error.response.data.message)\n } else {\n throw new GraphQLError(error)\n }\n }\n },\n createQuote: async (\n _: any,\n {\n input: { referenceName, items, subtotal, note, sendToSalesRep },\n }: {\n input: {\n referenceName: string\n items: QuoteItem[]\n subtotal: number\n note: string\n sendToSalesRep: boolean\n }\n },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex,\n vtex: { logger },\n } = ctx\n\n const settings = await checkConfig(ctx)\n const { sessionData, storefrontPermissions, segmentData } = vtex as any\n\n checkSession(sessionData)\n\n if (!storefrontPermissions?.permissions?.includes('create-quotes')) {\n throw new GraphQLError('operation-not-permitted')\n }\n\n try {\n let quoteBySeller: SellerQuoteMap = {}\n\n if (settings?.adminSetup.quotesManagedBy === 'SELLER') {\n const sellerItems = items.filter(\n ({ seller }) => seller && seller !== '1'\n )\n\n quoteBySeller = await splitItemsBySeller({\n ctx,\n items: sellerItems,\n })\n }\n\n const sellerQuotesQuantity = Object.keys(quoteBySeller).length\n\n const remainingItems = items.filter(\n (item) =>\n !Object.values(quoteBySeller).some((quote) =>\n quote.items.some(createItemComparator(item))\n )\n )\n\n const oneSellerQuoteAndNoRemainingItems =\n sellerQuotesQuantity === 1 && !remainingItems.length\n\n const isOnlyOneQuote =\n !sellerQuotesQuantity || oneSellerQuoteAndNoRemainingItems\n\n const [firstSellerQuote] = Object.values(quoteBySeller)\n\n let parentQuoteItems = sellerQuotesQuantity ? remainingItems : items\n\n if (isOnlyOneQuote && firstSellerQuote) {\n parentQuoteItems = firstSellerQuote.items\n }\n\n const quoteCommonFields = {\n sessionData,\n storefrontPermissions,\n segmentData,\n settings,\n referenceName,\n note,\n sendToSalesRep,\n sellerQuotesQuantity,\n }\n\n const parentQuote = createQuoteObject({\n ...quoteCommonFields,\n items: parentQuoteItems,\n subtotal,\n ...(isOnlyOneQuote &&\n firstSellerQuote && {\n seller: firstSellerQuote.seller,\n sellerName: firstSellerQuote.sellerName,\n }),\n })\n\n const { DocumentId: parentQuoteId } = await masterdata.createDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: parentQuote,\n schema: SCHEMA_VERSION,\n })\n\n if (isOnlyOneQuote && firstSellerQuote) {\n await ctx.clients.sellerQuotes.notifyNewQuote(\n firstSellerQuote.seller,\n parentQuoteId,\n parentQuote.creationDate\n )\n }\n\n if (!isOnlyOneQuote) {\n const childrenQuoteIds: string[] = []\n\n if (parentQuoteItems.length) {\n const marketplaceSubtotal = parentQuoteItems.reduce(\n (acc, item) => acc + item.sellingPrice * item.quantity,\n 0\n )\n\n const marketplaceSeller = await ctx.clients.seller.getSeller('1')\n\n const marketplaceQuote = createQuoteObject({\n ...quoteCommonFields,\n items: parentQuoteItems,\n subtotal: marketplaceSubtotal,\n seller: '1',\n sellerName: marketplaceSeller?.name ?? ctx.vtex.account,\n parentQuote: parentQuoteId,\n })\n\n const {\n DocumentId: markerplaceQuoteId,\n } = await masterdata.createDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: marketplaceQuote,\n schema: SCHEMA_VERSION,\n })\n\n childrenQuoteIds.push(markerplaceQuoteId)\n }\n\n const sellerQuoteIds = await Promise.all(\n Object.entries(quoteBySeller).map(async ([seller, sellerQuote]) => {\n const sellerQuoteObject = createQuoteObject({\n ...quoteCommonFields,\n ...sellerQuote,\n parentQuote: parentQuoteId,\n })\n\n const data = await masterdata.createDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: sellerQuoteObject,\n schema: SCHEMA_VERSION,\n })\n\n await ctx.clients.sellerQuotes.notifyNewQuote(\n seller,\n data.DocumentId,\n sellerQuoteObject.creationDate\n )\n\n return data.DocumentId\n })\n )\n\n childrenQuoteIds.push(...sellerQuoteIds)\n\n if (childrenQuoteIds.length) {\n await masterdata.updatePartialDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: {\n hasChildren: true,\n childrenQuantity: childrenQuoteIds.length,\n },\n id: parentQuoteId,\n schema: SCHEMA_VERSION,\n })\n }\n }\n\n if (sendToSalesRep) {\n message(ctx)\n .quoteCreated({\n costCenter: parentQuote.costCenter,\n id: parentQuoteId,\n lastUpdate: {\n email: parentQuote.creatorEmail,\n note,\n status: parentQuote.status.toUpperCase(),\n },\n name: referenceName,\n organization: parentQuote.organization,\n })\n .then(() => {\n logger.info({\n message: `[Quote created] E-mail sent to sales reps`,\n })\n })\n }\n\n const metricsParam = {\n sessionData,\n userData: {\n orgId: parentQuote.organization,\n costId: parentQuote.costCenter,\n roleId: parentQuote.creatorRole,\n },\n costCenterName: 'costCenterData?.getCostCenterById?.name',\n buyerOrgName: 'organizationData?.getOrganizationById?.name',\n quoteId: parentQuoteId,\n quoteReferenceName: referenceName,\n sendToSalesRep,\n creationDate: parentQuote.creationDate,\n }\n\n sendCreateQuoteMetric(ctx, metricsParam)\n\n return parentQuoteId\n } catch (error) {\n logger.error({\n error,\n message: 'createQuote-error ',\n })\n\n const errorMessage =\n error.message || error.response?.data?.message || error\n\n throw new GraphQLError(errorMessage)\n }\n },\n updateQuote: async (\n _: any,\n {\n input: { id, items, subtotal, note, decline, expirationDate },\n }: {\n input: {\n id: string\n items: QuoteItem[]\n subtotal: number\n note: string\n decline: boolean\n expirationDate: string\n }\n },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex,\n vtex: { logger },\n } = ctx\n\n const { sessionData, storefrontPermissions } = vtex as any\n\n checkSession(sessionData)\n\n const email = sessionData.namespaces.profile.email.value\n const {\n permissions,\n role: { slug },\n } = storefrontPermissions\n\n const isCustomer = slug.includes('customer')\n const isSales = slug.includes('sales')\n const itemsChanged = items?.length > 0\n\n checkPermissionsForUpdateQuote({\n permissions,\n itemsChanged,\n decline,\n })\n\n const {\n organization: { value: userOrganizationId },\n costcenter: { value: userCostCenterId },\n } = sessionData.namespaces['storefront-permissions']\n\n const now = new Date()\n const nowISO = now.toISOString()\n\n try {\n const existingQuote: Quote = await masterdata.getDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: QUOTE_FIELDS,\n id,\n })\n\n checkQuoteStatus(existingQuote)\n\n const expirationChanged = expirationDate !== existingQuote.expirationDate\n\n checkOperationsForUpdateQuote({\n permissions,\n expirationChanged,\n itemsChanged,\n existingQuote,\n userCostCenterId,\n userOrganizationId,\n declineQuote: decline,\n })\n\n const readyOrRevised = itemsChanged ? 'ready' : 'revised'\n const status = decline ? 'declined' : readyOrRevised\n\n const lastUpdate = nowISO\n const update = {\n date: nowISO,\n email,\n note,\n role: slug,\n status,\n }\n\n const { updateHistory } = existingQuote\n\n updateHistory.push(update)\n\n const updatedQuote: Quote = {\n ...existingQuote,\n expirationDate: expirationChanged\n ? expirationDate\n : existingQuote.expirationDate,\n items: itemsChanged ? items : existingQuote.items,\n lastUpdate,\n status,\n subtotal: subtotal ?? existingQuote.subtotal,\n updateHistory,\n viewedByCustomer: !!(decline || isCustomer),\n viewedBySales: !!(decline || isSales),\n }\n\n const data = await masterdata\n .updateEntireDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: updatedQuote,\n id,\n schema: SCHEMA_VERSION,\n })\n .then((res: any) => res)\n\n const sellerQuotesController = new SellerQuotesController(ctx)\n\n if (existingQuote.parentQuote) {\n sellerQuotesController.handleParentQuoteSubtotalAndStatus(\n existingQuote.parentQuote\n )\n }\n\n const users = updateHistory.map((anUpdate) => anUpdate.email)\n const uniqueUsers = [\n ...new Set(\n users.filter((userEmail: string) => isEmail.test(userEmail))\n ),\n ]\n\n message(ctx)\n .quoteUpdated({\n costCenter: existingQuote.costCenter,\n id: existingQuote.id,\n lastUpdate: {\n email,\n note,\n status: status.toUpperCase(),\n },\n name: existingQuote.referenceName,\n organization: existingQuote.organization,\n users: uniqueUsers,\n })\n .then(() => {\n logger.info({\n message: `[Quote updated] E-mail sent ${uniqueUsers.join(', ')}`,\n })\n })\n\n return data.id\n } catch (error) {\n logger.warn({\n error,\n message: 'updateQuote-warning',\n })\n throw new GraphQLError(error)\n }\n },\n useQuote: async (\n _: any,\n { id, orderFormId }: { id: string; orderFormId: string },\n ctx: Context\n ) => {\n const {\n clients: { masterdata, hub },\n vtex,\n vtex: { account, logger, authToken },\n } = ctx\n\n const { sessionData, storefrontPermissions } = vtex as any\n\n checkSession(sessionData)\n\n const { permissions } = storefrontPermissions\n\n if (!permissions.includes('use-quotes')) {\n throw new GraphQLError('operation-not-permitted')\n }\n\n const useHeaders = {\n 'Content-Type': 'application/json',\n Cookie: `VtexIdclientAutCookie=${authToken};`,\n }\n\n try {\n // GET QUOTE DATA\n const mainQuote: Quote = await masterdata.getDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: QUOTE_FIELDS,\n id,\n })\n\n const quotes: Quote[] = []\n const items: QuoteItem[] = []\n\n if (mainQuote.hasChildren) {\n const sellerQuotesController = new SellerQuotesController(ctx)\n const childrenQuotes = await sellerQuotesController.getAllChildrenQuotes(\n id\n )\n\n let errorsCount = 0\n\n for (const quote of childrenQuotes) {\n try {\n checkQuoteStatus(quote)\n quotes.push(quote)\n } catch (e) {\n if (++errorsCount === childrenQuotes.length) {\n throw e\n }\n\n continue\n }\n }\n } else {\n checkQuoteStatus(mainQuote)\n quotes.push(mainQuote)\n }\n\n for (const quote of quotes) {\n items.push(...quote.items)\n }\n\n const { salesChannel } = mainQuote\n\n // CLEAR CURRENT CART\n if (orderFormId !== 'default-order-form') {\n await hub.post(\n routes.clearCart(account, orderFormId),\n {\n expectedOrderFormSections: ['items'],\n },\n useHeaders\n )\n }\n\n // CREATE CART IF IT DOESN'T EXIST YET\n if (orderFormId === 'default-order-form') {\n const newOrderForm = await hub.get(\n routes.orderForm(account),\n useHeaders\n )\n\n orderFormId = (newOrderForm.data as any).orderFormId\n }\n\n await checkAndCreateQuotesConfig(ctx)\n await hub\n .put(\n routes.addCustomData({\n account,\n orderFormId,\n appId: APP_NAME,\n property: 'quoteId',\n }),\n {\n value: id,\n },\n useHeaders\n )\n .then((res: any) => {\n return res.data\n })\n .catch((error) =>\n logger.error({\n error,\n message: 'useQuote-addCustomDataError',\n })\n )\n\n const salesChannelQueryString = salesChannel ? `?sc=${salesChannel}` : ''\n\n // ADD ITEMS TO CART\n const data = await hub\n .post(\n `${routes.addToCart(account, orderFormId)}${salesChannelQueryString}`,\n {\n expectedOrderFormSections: ['items'],\n orderItems: items.map((item) => {\n return {\n id: item.id,\n quantity: item.quantity,\n seller: item.seller || '1',\n }\n }),\n }\n )\n .then((res: any) => {\n return res.data\n })\n\n const { items: itemsAdded } = data\n\n const sellingPriceMap = indexBy(\n prop('id'),\n map(\n (item: any) => ({\n id: item.id,\n price: item.sellingPrice,\n }),\n items\n )\n )\n\n const orderItems: any[] = []\n\n itemsAdded.forEach((item: any, key: number) => {\n orderItems.push({\n index: key,\n price: prop(item.id, sellingPriceMap).price,\n quantity: null,\n })\n })\n\n await hub.post(\n routes.addPriceToItems(account, orderFormId),\n {\n orderItems,\n },\n useHeaders\n )\n\n for (const quote of quotes) {\n const metricParams: UseQuoteMetricsParams = {\n quote,\n orderFormId,\n account,\n userEmail: sessionData?.namespaces?.profile?.email?.value,\n }\n\n sendUseQuoteMetric(ctx, metricParams)\n }\n } catch (error) {\n logger.error({\n error,\n message: 'useQuote-error',\n })\n if (error.message) {\n throw new GraphQLError(error.message)\n } else if (error.response?.data?.message) {\n throw new GraphQLError(error.response.data.message)\n } else {\n throw new GraphQLError(error)\n }\n }\n },\n saveAppSettings: async (\n _: void,\n {\n input: { cartLifeSpan, quotesManagedBy = 'MARKETPLACE' },\n }: { input: { cartLifeSpan: number; quotesManagedBy: string } },\n ctx: Context\n ) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n let settings = null\n let noSettingsFound = false\n\n try {\n settings = await vbase.getJSON<Settings | null>(\n APP_NAME,\n 'settings',\n true\n )\n } catch (error) {\n logger.error({\n error,\n message: 'saveAppSettings-getAppSettingsError',\n })\n\n return null\n }\n\n if (!settings) {\n settings = defaultSettings\n noSettingsFound = true\n }\n\n const newSettings = {\n ...settings,\n adminSetup: {\n ...settings.adminSetup,\n cartLifeSpan,\n quotesManagedBy,\n },\n }\n\n try {\n await vbase.saveJSON(APP_NAME, 'settings', newSettings)\n } catch (error) {\n logger.error({\n error,\n message: 'saveAppSettings-saveAppSettingsError',\n })\n\n return noSettingsFound ? null : settings\n }\n\n return newSettings\n },\n}\n\n```"
}
] |
code_b2b-quotes-graphql_a6fb6278
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/queries/index.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n APP_NAME,\n B2B_USER_DATA_ENTITY,\n B2B_USER_SCHEMA_VERSION,\n QUOTE_DATA_ENTITY,\n QUOTE_FIELDS,\n SCHEMA_VERSION,\n} from '../../constants'\nimport GraphQLError from '../../utils/GraphQLError'\nimport { checkConfig } from '../utils/checkConfig'\nimport SellerQuotesController from '../utils/sellerQuotesController'\n\n// This function checks if given email is an user part of a buyer org.\nexport const isUserPartOfBuyerOrg = async (email: string, ctx: Context) => {\n const {\n clients: { masterdata },\n } = ctx\n\n const where = `email=${email}`\n const resp = await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: B2B_USER_DATA_ENTITY,\n fields: ['id'], // we don't need to fetch all fields, only if there is an entry or not\n pagination: {\n page: 1,\n pageSize: 1, // we only need to know if there is at least one user entry\n },\n schema: B2B_USER_SCHEMA_VERSION,\n ...(where ? { where } : {}),\n })\n\n const { data } = (resp as unknown) as {\n data: any\n }\n\n if (data.length > 0) {\n return true\n }\n\n return false\n}\n\nconst buildWhereStatement = async ({\n permissions,\n organization,\n costCenter,\n status,\n search,\n userOrganizationId,\n userCostCenterId,\n userSalesChannel,\n}: {\n permissions: string[]\n organization?: string[]\n costCenter?: string[]\n status?: string[]\n search?: string\n userOrganizationId: string\n userCostCenterId: string\n userSalesChannel?: string\n}) => {\n // only the main quotes must be fetched\n const whereArray = ['(parentQuote is null)']\n\n // if user only has permission to access their organization's quotes,\n // hard-code that organization into the masterdata search\n if (!permissions.includes('access-quotes-all')) {\n whereArray.push(`organization=${userOrganizationId}`)\n } else if (organization?.length) {\n const orgArray = organization.map((org) => `organization=${org}`)\n const organizationsStatement = `(${orgArray.join(' OR ')})`\n\n whereArray.push(organizationsStatement)\n }\n\n // similarly, if user only has permission to see their cost center's quotes,\n // hard-code its ID into the search\n if (\n !permissions.includes('access-quotes-all') &&\n !permissions.includes('access-quotes-organization')\n ) {\n whereArray.push(`costCenter=${userCostCenterId}`)\n } else if (costCenter?.length) {\n const ccArray = costCenter.map((cc) => `costCenter=${cc}`)\n const costCenters = `(${ccArray.join(' OR ')})`\n\n whereArray.push(costCenters)\n }\n\n // similarly, if user only has permission to see their quotes from their sales channel,\n // hard-code its value into the search\n // allow all users to view quotes without a sales channel\n if (\n !permissions.includes('access-quotes-all') &&\n !permissions.includes('access-quotes-all-saleschannel') &&\n userSalesChannel\n ) {\n whereArray.push(\n `((salesChannel is null) OR salesChannel=\"${userSalesChannel}\")`\n )\n }\n\n if (status?.length) {\n const statusArray = status.map((stat) => `status=${stat}`)\n const statuses = `(${statusArray.join(' OR ')})`\n\n whereArray.push(statuses)\n }\n\n if (search) {\n const searchArray = [] as string[]\n\n searchArray.push(`referenceName=\"*${search}*\"`)\n searchArray.push(`creatorEmail=\"*${search}*\"`)\n const searches = `(${searchArray.join(' OR ')})`\n\n whereArray.push(searches)\n }\n\n return whereArray.join(' AND ')\n}\n\nexport const Query = {\n getQuote: async (_: any, { id }: { id: string }, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex,\n vtex: { logger },\n } = ctx\n\n const { sessionData, storefrontPermissions, segmentData } = vtex as any\n\n if (\n !storefrontPermissions?.permissions?.length ||\n !sessionData?.namespaces['storefront-permissions']?.organization?.value ||\n !sessionData?.namespaces['storefront-permissions']?.costcenter?.value\n ) {\n return null\n }\n\n const { permissions } = storefrontPermissions\n const userOrganizationId =\n sessionData.namespaces['storefront-permissions'].organization.value\n\n const userCostCenterId =\n sessionData.namespaces['storefront-permissions'].costcenter.value\n\n const userSalesChannel = segmentData?.channel\n\n if (\n !permissions.some(\n (permission: string) => permission.indexOf('access-quotes') >= 0\n )\n ) {\n return null\n }\n\n await checkConfig(ctx)\n\n try {\n const quote: Quote = await masterdata.getDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: QUOTE_FIELDS,\n id,\n })\n\n // if user only has permission to view their organization's quotes, check that the org matches\n if (\n !permissions.includes('access-quotes-all') &&\n permissions.includes('access-quotes-organization') &&\n userOrganizationId !== quote.organization\n ) {\n return null\n }\n\n // if user only has permission to view their cost center's quotes, check that the cost center matches\n if (\n !permissions.includes('access-quotes-all') &&\n !permissions.includes('access-quotes-organization') &&\n userCostCenterId !== quote.costCenter\n ) {\n return null\n }\n\n // if user only has permission to view quotes from their sales channel, check that the sales channel matches or is null\n if (\n !permissions.includes('access-quotes-all') &&\n !permissions.includes('access-quotes-all-saleschannel') &&\n quote.salesChannel &&\n userSalesChannel !== quote.salesChannel\n ) {\n return null\n }\n\n return quote\n } catch (error) {\n logger.error({\n error,\n message: 'getQuote-error',\n })\n if (error.message) {\n throw new GraphQLError(error.message)\n } else if (error.response?.data?.message) {\n throw new GraphQLError(error.response.data.message)\n } else {\n throw new GraphQLError(error)\n }\n }\n },\n getQuotes: async (\n _: any,\n {\n organization,\n costCenter,\n status,\n search,\n page,\n pageSize,\n sortOrder,\n sortedBy,\n }: {\n organization: string[]\n costCenter: string[]\n status: string[]\n search: string\n page: number\n pageSize: number\n sortOrder: string\n sortedBy: string\n },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex,\n vtex: { logger },\n } = ctx\n\n const { sessionData, storefrontPermissions, segmentData } = vtex as any\n\n if (\n !storefrontPermissions?.permissions?.length ||\n !sessionData?.namespaces['storefront-permissions']?.organization?.value ||\n !sessionData?.namespaces['storefront-permissions']?.costcenter?.value\n ) {\n return null\n }\n\n const { permissions } = storefrontPermissions\n const userOrganizationId =\n sessionData.namespaces['storefront-permissions'].organization.value\n\n const userCostCenterId =\n sessionData.namespaces['storefront-permissions'].costcenter.value\n\n if (\n !permissions.some(\n (permission: string) => permission.indexOf('access-quotes') >= 0\n )\n ) {\n return null\n }\n\n const userSalesChannel = segmentData?.channel\n\n await checkConfig(ctx)\n\n const where = await buildWhereStatement({\n permissions,\n organization,\n costCenter,\n status,\n search,\n userOrganizationId,\n userCostCenterId,\n userSalesChannel,\n })\n\n try {\n return await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: QUOTE_DATA_ENTITY,\n fields: QUOTE_FIELDS,\n pagination: { page, pageSize },\n schema: SCHEMA_VERSION,\n sort: `${sortedBy} ${sortOrder}`,\n ...(where && { where }),\n })\n } catch (error) {\n logger.error({\n error,\n message: 'getQuotes-error',\n })\n throw new GraphQLError(error)\n }\n },\n getChildrenQuotes: async (\n _: any,\n {\n id,\n sortOrder,\n sortedBy,\n }: {\n id: string\n sortOrder: string\n sortedBy: string\n },\n ctx: Context\n ) => {\n const {\n vtex: { logger },\n } = ctx\n\n await checkConfig(ctx)\n const sellerQuotesController = new SellerQuotesController(ctx)\n\n try {\n return await sellerQuotesController.getAllChildrenQuotes(\n id,\n sortOrder,\n sortedBy\n )\n } catch (error) {\n logger.error({\n error,\n message: 'getQuotes-error',\n })\n throw new GraphQLError(error)\n }\n },\n getQuoteEnabledForUser: async (\n _: any,\n { email }: { email: string },\n ctx: Context\n ) => {\n const {\n vtex: { logger },\n } = ctx\n\n try {\n // if user is part of a buyer org, quote functionality is enabled\n return await isUserPartOfBuyerOrg(email, ctx)\n } catch (error) {\n logger.error({\n error,\n message: 'getQuoteEnabledForUser-error',\n })\n throw new GraphQLError(error)\n }\n },\n getAppSettings: async (_: void, __: void, ctx: Context) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n await checkConfig(ctx)\n let settings = null\n\n try {\n settings = await vbase.getJSON<Settings | null>(\n APP_NAME,\n 'settings',\n true\n )\n } catch (error) {\n logger.error({\n error,\n message: 'getAppSettings-getVbaseError',\n })\n\n return null\n }\n\n if (settings && !settings?.adminSetup.quotesManagedBy) {\n settings.adminSetup.quotesManagedBy = 'MARKETPLACE'\n }\n\n return settings\n },\n checkSellerQuotes: async (\n _: void,\n { sellers }: { sellers: string[] },\n ctx: Context\n ) => {\n // guarantee at least the marketplace seller to use your name if necessary\n const allSellers = sellers.filter((seller) => seller !== '1')\n\n allSellers.push('1')\n\n const verifiedSellers = await Promise.all(\n allSellers.map(async (seller) => {\n if (seller === '1') {\n return ctx.clients.seller.getSeller(seller)\n }\n\n const verifyResponse = await ctx.clients.sellerQuotes\n .verifyQuoteSettings(seller)\n .catch(() => null)\n\n if (verifyResponse?.receiveQuotes) {\n return ctx.clients.seller.getSeller(seller)\n }\n\n return null\n })\n )\n\n return verifiedSellers.filter(Boolean)\n },\n}\n\n```"
}
] |
code_b2b-quotes-graphql_89a4c193
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/utils/quotes.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport async function splitItemsBySeller({\n ctx,\n items,\n quoteBySeller = {},\n index = 0,\n}: {\n ctx: Context\n items: QuoteItem[]\n quoteBySeller?: SellerQuoteMap\n index?: number\n}): Promise<SellerQuoteMap> {\n if (index >= items.length) return quoteBySeller\n\n const item = items[index]\n const { seller } = item\n\n const next = async () =>\n splitItemsBySeller({\n ctx,\n items,\n quoteBySeller,\n index: index + 1,\n })\n\n // The ternary check is to not request again from the same seller\n const verifyResponse = quoteBySeller[seller]\n ? { receiveQuotes: true }\n : await ctx.clients.sellerQuotes\n .verifyQuoteSettings(seller)\n .catch(() => null)\n\n if (!verifyResponse?.receiveQuotes) {\n await next()\n\n return quoteBySeller\n }\n\n if (!quoteBySeller[seller]) {\n const sellerData = await ctx.clients.seller.getSeller(seller)\n\n quoteBySeller[seller] = {\n items: [],\n subtotal: 0,\n seller,\n sellerName: sellerData?.name,\n }\n }\n\n quoteBySeller[seller].items.push(item)\n quoteBySeller[seller].subtotal += item.sellingPrice * item.quantity\n\n await next()\n\n return quoteBySeller\n}\n\nexport function createItemComparator<T extends QuoteItem>(item: T) {\n return ({ id, seller }: T) => item.id === id && item.seller === seller\n}\n\nexport const createQuoteObject = ({\n sessionData,\n storefrontPermissions,\n segmentData,\n settings,\n items,\n referenceName,\n subtotal,\n note,\n sendToSalesRep,\n seller,\n sellerName,\n parentQuote,\n hasChildren,\n sellerQuotesQuantity,\n}: {\n sessionData: SessionData\n storefrontPermissions: { role: { slug: string } }\n segmentData?: { channel?: string }\n settings?: Settings | null\n items: QuoteItem[]\n referenceName: string\n subtotal: number\n note: string\n sendToSalesRep: boolean\n seller?: string\n sellerName?: string\n parentQuote?: string | null\n hasChildren?: boolean | null\n sellerQuotesQuantity?: number\n}): Omit<Quote, 'id'> => {\n const { email, firstName, lastName } = sessionData.namespaces.profile\n const { value: creatorEmail } = email\n const creatorName = `${firstName?.value ?? ''}${\n lastName?.value ? ` ${lastName.value}` : ''\n }`.trim()\n\n const {\n role: { slug },\n } = storefrontPermissions\n\n const {\n organization: { value: organizationId },\n costcenter: { value: costCenterId },\n } = sessionData.namespaces['storefront-permissions']\n\n const now = new Date()\n const nowISO = now.toISOString()\n const expirationDate = new Date()\n\n expirationDate.setDate(\n expirationDate.getDate() + (settings?.adminSetup?.cartLifeSpan ?? 30)\n )\n const expirationDateISO = expirationDate.toISOString()\n\n const isSellerQuote = seller && seller !== '1'\n const status =\n sendToSalesRep || isSellerQuote || (!seller && sellerQuotesQuantity)\n ? 'pending'\n : 'ready'\n\n const lastUpdate = nowISO\n const updateHistory = [\n {\n date: nowISO,\n email: creatorEmail,\n note,\n role: slug,\n status,\n },\n ]\n\n const salesChannel: string = segmentData?.channel ?? ''\n\n return {\n costCenter: costCenterId,\n creationDate: nowISO,\n creatorEmail,\n creatorName,\n creatorRole: slug,\n expirationDate: expirationDateISO,\n items,\n lastUpdate,\n organization: organizationId,\n referenceName,\n status,\n subtotal,\n updateHistory,\n viewedByCustomer: !!sendToSalesRep,\n viewedBySales: !sendToSalesRep,\n salesChannel,\n seller,\n sellerName,\n parentQuote,\n hasChildren,\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_c82e5f41
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/utils/checkPermissions.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport GraphQLError from '../../utils/GraphQLError'\n\nexport const checkSession = (sessionData: any) => {\n if (!sessionData?.namespaces['storefront-permissions']) {\n throw new GraphQLError('organization-data-not-found')\n }\n\n if (!sessionData?.namespaces?.profile?.email?.value) {\n throw new GraphQLError('email-not-found')\n }\n}\n\nexport const checkPermissionsForUpdateQuote = ({\n permissions,\n itemsChanged,\n decline,\n}: {\n permissions: string[]\n itemsChanged: boolean\n decline: boolean\n}) => {\n if (\n (itemsChanged &&\n !permissions.some((permission: string) =>\n permission.includes('edit-quotes')\n )) ||\n (!itemsChanged &&\n !permissions.some((permission: string) =>\n permission.includes('access-quotes')\n )) ||\n (decline && !permissions.includes('decline-quotes'))\n ) {\n throw new GraphQLError('operation-not-permitted')\n }\n}\n\nexport const checkQuoteStatus = (existingQuote: Quote) => {\n if (!existingQuote) {\n throw new GraphQLError('quote-not-found')\n }\n\n if (\n existingQuote.status === 'expired' ||\n existingQuote.status === 'declined'\n ) {\n throw new GraphQLError('quote-cannot-be-updated-or-used')\n }\n}\n\nconst checkIfOrgMatches = ({\n permissions,\n existingQuote,\n itemsOrExpirationChanged,\n neitherItemsNorExpirationChanged,\n userOrganizationId,\n}: {\n permissions: string[]\n itemsOrExpirationChanged: boolean\n neitherItemsNorExpirationChanged: boolean\n existingQuote: Quote\n userOrganizationId: string\n}) => {\n // if user only has permission to edit their organization's quotes, check that the org matches\n\n if (\n (itemsOrExpirationChanged &&\n !permissions.includes('edit-quotes-all') &&\n permissions.includes('edit-quotes-organization')) ||\n (neitherItemsNorExpirationChanged &&\n !permissions.includes('access-quotes-all') &&\n permissions.includes('access-quotes-organization'))\n ) {\n if (userOrganizationId !== existingQuote.organization) {\n throw new GraphQLError('operation-not-permitted')\n }\n }\n}\n\nconst checkIfCostCenterMatches = ({\n permissions,\n existingQuote,\n itemsOrExpirationChanged,\n neitherItemsNorExpirationChanged,\n userCostCenterId,\n}: {\n permissions: string[]\n itemsOrExpirationChanged: boolean\n neitherItemsNorExpirationChanged: boolean\n existingQuote: Quote\n userCostCenterId: string\n}) => {\n // if user only has permission to edit their organization's quotes, check that the org matches\n\n if (\n (itemsOrExpirationChanged &&\n !permissions.includes('edit-quotes-all') &&\n !permissions.includes('edit-quotes-organization')) ||\n (neitherItemsNorExpirationChanged &&\n !permissions.includes('access-quotes-all') &&\n !permissions.includes('access-quotes-organization'))\n ) {\n if (userCostCenterId !== existingQuote.costCenter) {\n throw new GraphQLError('operation-not-permitted')\n }\n }\n}\n\nexport const checkOperationsForUpdateQuote = ({\n permissions,\n expirationChanged,\n itemsChanged,\n existingQuote,\n userOrganizationId,\n userCostCenterId,\n declineQuote,\n}: {\n permissions: string[]\n expirationChanged: boolean\n itemsChanged: boolean\n existingQuote: Quote\n userOrganizationId: string\n userCostCenterId: string\n declineQuote: boolean\n}) => {\n const itemsOrExpirationChanged = itemsChanged || expirationChanged\n const neitherItemsNorExpirationChanged = !itemsChanged && !expirationChanged\n\n if (\n expirationChanged &&\n !declineQuote &&\n !permissions.some((permission: string) =>\n permission.includes('edit-quotes')\n )\n ) {\n throw new GraphQLError('operation-not-permitted')\n }\n\n checkIfOrgMatches({\n permissions,\n existingQuote,\n itemsOrExpirationChanged,\n neitherItemsNorExpirationChanged,\n userOrganizationId,\n })\n\n checkIfCostCenterMatches({\n permissions,\n existingQuote,\n itemsOrExpirationChanged,\n neitherItemsNorExpirationChanged,\n userCostCenterId,\n })\n\n // if user only has permission to edit their cost center's quotes, check that the cost center matches\n}\n\n```"
}
] |
code_b2b-quotes-graphql_76c2b01d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/utils/sellerQuotesController.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { NotFoundError } from '@vtex/api'\nimport pLimit from 'p-limit'\n\nimport {\n QUOTE_DATA_ENTITY,\n QUOTE_FIELDS,\n SCHEMA_VERSION,\n} from '../../constants'\nimport {\n costCenterName as getCostCenterName,\n organizationName as getOrganizationName,\n} from '../fieldResolvers'\n\ntype GetQuotesArgs = {\n page?: number\n pageSize?: number\n where?: string\n sort?: string\n}\n\nexport default class SellerQuotesController {\n constructor(\n private readonly ctx: Context | EventBroadcastContext,\n private readonly seller?: string\n ) {}\n\n private async getSellerQuotes({\n page = 1,\n pageSize = 1,\n where = '',\n sort = '',\n }: GetQuotesArgs) {\n return this.ctx.clients.masterdata.searchDocumentsWithPaginationInfo<Quote>(\n {\n dataEntity: QUOTE_DATA_ENTITY,\n fields: QUOTE_FIELDS,\n schema: SCHEMA_VERSION,\n pagination: { page, pageSize },\n where: `seller=${this.seller} AND (${where})`,\n sort,\n }\n )\n }\n\n private async getSellerQuote(id: string) {\n const { data } = await this.getSellerQuotes({ where: `id=${id}` })\n const [quote] = data\n\n if (!quote) {\n throw new NotFoundError('seller-quote-not-found')\n }\n\n return quote\n }\n\n private async getOrganizationData(quote: Quote) {\n const [organizationName, costCenterName] = await Promise.all([\n getOrganizationName({ organization: quote.organization }, null, this.ctx),\n getCostCenterName({ costCenter: quote.costCenter }, null, this.ctx),\n ])\n\n return { organizationName, costCenterName }\n }\n\n public async getAllChildrenQuotes(\n parentQuote: string,\n sortOrder = 'DESC',\n sortedBy = 'lastUpdate'\n ) {\n const result: Quote[] = []\n\n const getQuotes = async (page = 1) => {\n const quotes = await this.ctx.clients.masterdata.searchDocuments<Quote>({\n dataEntity: QUOTE_DATA_ENTITY,\n schema: SCHEMA_VERSION,\n pagination: { page, pageSize: 100 },\n fields: QUOTE_FIELDS,\n where: `parentQuote=${parentQuote}`,\n sort: `${sortedBy} ${sortOrder}`,\n })\n\n if (quotes.length) {\n result.push(...quotes)\n\n await getQuotes(page + 1)\n }\n }\n\n await getQuotes()\n\n return result\n }\n\n public async getFullSellerQuote(id: string) {\n const quote = await this.getSellerQuote(id)\n const { organizationName, costCenterName } = await this.getOrganizationData(\n quote\n )\n\n return { ...quote, organizationName, costCenterName }\n }\n\n public async getSellerQuotesPaginated({\n page,\n pageSize,\n where,\n sort = 'lastUpdate DESC',\n }: {\n page: number\n pageSize: number\n where?: string\n sort?: string\n }) {\n const { data, pagination } = await this.getSellerQuotes({\n page,\n pageSize,\n where,\n sort,\n })\n\n const limit = pLimit(15)\n const enrichedQuotes = await Promise.all(\n data.map((quote) =>\n limit(async () => {\n const {\n organizationName,\n costCenterName,\n } = await this.getOrganizationData(quote)\n\n return { ...quote, organizationName, costCenterName }\n })\n )\n )\n\n return {\n data: enrichedQuotes,\n pagination,\n }\n }\n\n public async handleParentQuoteSubtotalAndStatus(parentQuote: string) {\n const childrenQuotes = await this.getAllChildrenQuotes(parentQuote)\n\n if (!childrenQuotes?.length) return\n\n const sumSubtotal = childrenQuotes.reduce(\n (acc, quote) => acc + quote.subtotal,\n 0\n )\n\n const isEverySameStatus = childrenQuotes.every(\n (quote) => quote.status === childrenQuotes[0].status\n )\n\n const quotesExceptDeclined = childrenQuotes.filter(\n (quote) => quote.status !== 'declined'\n )\n\n const isEverySameStatusExceptDeclined =\n !!quotesExceptDeclined.length &&\n quotesExceptDeclined.every(\n (quote) => quote.status === quotesExceptDeclined[0].status\n )\n\n const isSomeRevised = childrenQuotes.some(\n (quote) => quote.status === 'revised'\n )\n\n const isSomePending = childrenQuotes.some(\n (quote) => quote.status === 'pending'\n )\n\n let status: string | undefined\n\n if (isEverySameStatus) {\n status = childrenQuotes[0].status\n } else if (isEverySameStatusExceptDeclined) {\n status = quotesExceptDeclined[0].status\n } else if (isSomePending) {\n status = 'pending'\n } else if (isSomeRevised) {\n status = 'revised'\n }\n\n const lastUpdate = new Date().toISOString()\n\n this.ctx.clients.masterdata.updatePartialDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n schema: SCHEMA_VERSION,\n fields: { subtotal: sumSubtotal, status, lastUpdate },\n id: parentQuote,\n })\n }\n\n public async saveSellerQuote(id: string, fields: Partial<Quote>) {\n await this.ctx.clients.masterdata.updatePartialDocument({\n dataEntity: QUOTE_DATA_ENTITY,\n schema: SCHEMA_VERSION,\n fields,\n id,\n })\n\n const { parentQuote } = fields\n\n if (parentQuote) {\n this.handleParentQuoteSubtotalAndStatus(parentQuote)\n }\n }\n}\n\n```"
}
] |
code_b2b-quotes-graphql_4b70b42f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/utils/checkConfig.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport templates from '../../templates'\nimport { toHash } from '../../utils'\nimport {\n APP_NAME,\n CRON_EXPRESSION,\n QUOTE_DATA_ENTITY,\n SCHEMA_VERSION,\n routes,\n schema,\n} from '../../constants'\n\nexport const defaultSettings: Settings = {\n adminSetup: {\n allowManualPrice: false,\n cartLifeSpan: 30,\n quotesManagedBy: 'MARKETPLACE',\n hasCron: false,\n },\n schemaVersion: '',\n schemaHash: null,\n templateHash: null,\n}\n\nconst defaultHeaders = (authToken: string) => ({\n Accept: 'application/vnd.vtex.ds.v10+json',\n 'Content-Type': 'application/json',\n 'Proxy-Authorization': authToken,\n VtexIdclientAutCookie: authToken,\n})\n\n// checks and configure the OrderForm based on quoteId\nexport const checkAndCreateQuotesConfig = async (\n ctx: Context\n): Promise<any> => {\n const {\n clients: { checkout, vbase },\n vtex: { logger, authToken },\n } = ctx\n\n let hasQuoteConfig = false\n\n const saveQuotesConfig = async (flag: boolean) => {\n return vbase\n .saveJSON(APP_NAME, 'quotes', { quote: flag })\n .then(() => true)\n .catch((error) =>\n logger.error({\n error,\n message: 'vBaseSaveJson-error',\n })\n )\n }\n\n try {\n hasQuoteConfig =\n (await vbase.getJSON<{ quote: boolean }>(APP_NAME, 'quotes'))?.quote ??\n false\n } catch (error) {\n const errStr = error.toString()\n\n if (errStr.match(/404/gm)) {\n await saveQuotesConfig(false)\n } else {\n logger.error({\n error,\n message: 'vBaseSaveGet-error',\n })\n }\n }\n\n if (!hasQuoteConfig) {\n const checkoutConfig: any = await checkout\n .getOrderFormConfiguration()\n .catch((error) => {\n logger.error({\n error,\n message: 'getOrderFormConfiguration-error',\n })\n })\n\n if (\n checkoutConfig?.apps.findIndex(\n (currApp: any) => currApp.id === APP_NAME\n ) === -1\n ) {\n checkoutConfig.apps.push({\n fields: ['quoteId'],\n id: APP_NAME,\n major: 1,\n })\n const setCheckoutConfig: any = await checkout\n .setOrderFormConfiguration(checkoutConfig, authToken)\n .then(() => true)\n .catch((error) => {\n logger.error({\n error,\n message: 'setOrderFormConfiguration-error',\n })\n\n return false\n })\n\n if (setCheckoutConfig) {\n await saveQuotesConfig(true)\n }\n } else {\n saveQuotesConfig(true)\n }\n }\n}\n\nconst initializeCron = async (settings: Settings, ctx: Context) => {\n const {\n vtex: { account, workspace },\n clients: { scheduler },\n } = ctx\n\n const cronQueue = await scheduler\n .getQueue()\n .then((data: any) => {\n return data\n })\n .catch(() => {\n return null\n })\n\n if (cronQueue?.expression === CRON_EXPRESSION) return settings\n\n const time = new Date().getTime()\n const QueueSchedule = {\n id: 'b2b-quotes-graphql-queue-schedule',\n request: {\n body: null,\n headers: {\n 'cache-control': 'no-cache',\n pragma: 'no-cache',\n },\n method: 'GET',\n uri: `https://${workspace}--${account}.myvtex.com/b2b-quotes-graphql/_v/0/process-queue?v=${time}`,\n },\n scheduler: {\n endDate: '2031-12-30T23:29:00',\n expression: CRON_EXPRESSION,\n },\n }\n\n await scheduler\n .createOrUpdate(QueueSchedule)\n .then(() => {\n if (!settings) {\n return\n }\n\n settings.adminSetup.hasCron = true\n settings.adminSetup.cronExpression = CRON_EXPRESSION\n settings.adminSetup.cronWorkspace = workspace\n })\n .catch((error) => {\n if (error.response.status !== 304) {\n settings.adminSetup.hasCron = false\n } else {\n settings.adminSetup.hasCron = true\n settings.adminSetup.cronExpression = CRON_EXPRESSION\n settings.adminSetup.cronWorkspace = workspace\n }\n })\n\n return settings\n}\n\nconst initializeSchema = async (settings: Settings, ctx: Context) => {\n const {\n clients: { masterdata },\n } = ctx\n\n try {\n await masterdata.createOrUpdateSchema({\n dataEntity: QUOTE_DATA_ENTITY,\n schemaBody: schema,\n schemaName: SCHEMA_VERSION,\n })\n\n settings.schemaVersion = SCHEMA_VERSION\n settings.schemaHash = toHash(schema)\n } catch (error) {\n if (error.response.status >= 400) {\n settings.schemaVersion = ''\n } else {\n settings.schemaVersion = SCHEMA_VERSION\n }\n }\n\n return settings\n}\n\nconst initializeManualPrice = async (settings: Settings, ctx: Context) => {\n const {\n vtex: { account, authToken, logger },\n clients: { hub },\n } = ctx\n\n try {\n const url = routes.checkoutConfig(account)\n const headers = defaultHeaders(authToken)\n\n const { data: checkoutConfig } = await hub.get(url, headers, schema)\n\n if (checkoutConfig.allowManualPrice !== true) {\n await hub.post(\n url,\n JSON.stringify({\n ...checkoutConfig,\n allowManualPrice: true,\n }),\n headers\n )\n settings.adminSetup.allowManualPrice = true\n }\n } catch (error) {\n settings.adminSetup.allowManualPrice = false\n logger.warn({\n error,\n message: 'initializeManualPrice-error',\n })\n }\n\n return settings\n}\n\nconst initializeTemplates = async (\n settings: Settings,\n currTemplateHash: string,\n ctx: Context\n) => {\n const {\n vtex: { logger },\n clients: { mail },\n } = ctx\n\n const updates: Array<Promise<any>> = []\n\n templates.forEach((template) => {\n updates.push(mail.publishTemplate(template))\n })\n\n await Promise.all(updates)\n .then(() => {\n settings.templateHash = currTemplateHash\n })\n .catch((error) => {\n logger.error({\n error,\n message: 'checkConfig-publishTemplateError',\n })\n throw new Error(error)\n })\n\n return settings\n}\n\nconst checkInitializations = async ({\n settings,\n currTemplateHash,\n changed,\n ctx,\n}: {\n settings: Settings\n currTemplateHash: string\n changed: boolean\n ctx: Context\n}) => {\n const {\n vtex: { workspace },\n } = ctx\n\n if (\n !settings?.adminSetup?.hasCron ||\n settings?.adminSetup?.cronExpression !== CRON_EXPRESSION ||\n settings?.adminSetup?.cronWorkspace !== workspace\n ) {\n if (!settings?.adminSetup?.hasCron) {\n settings.adminSetup = {\n ...defaultSettings.adminSetup,\n }\n }\n\n const oldCronSetting = settings.adminSetup.hasCron\n\n settings = await initializeCron(settings, ctx)\n\n if (settings.adminSetup.hasCron !== oldCronSetting) {\n changed = true\n }\n }\n\n const currentSchemaHash = toHash(schema)\n\n if (\n settings?.schemaVersion !== SCHEMA_VERSION ||\n settings?.schemaHash !== currentSchemaHash\n ) {\n const oldSchemaVersion = settings?.schemaVersion\n const oldSchemaHash = settings?.schemaHash\n\n settings = await initializeSchema(settings, ctx)\n\n const mustUpdateSettings =\n settings.schemaVersion !== oldSchemaVersion ||\n settings.schemaHash !== oldSchemaHash\n\n if (mustUpdateSettings) {\n changed = true\n }\n }\n\n if (!settings?.adminSetup?.allowManualPrice) {\n const oldManualPriceSetting = settings?.adminSetup?.allowManualPrice\n\n settings = await initializeManualPrice(settings, ctx)\n\n if (settings.adminSetup.allowManualPrice !== oldManualPriceSetting) {\n changed = true\n }\n }\n\n if (settings?.templateHash !== currTemplateHash) {\n const oldTemplateHash = settings?.templateHash\n\n settings = await initializeTemplates(settings, currTemplateHash, ctx)\n\n if (settings.templateHash !== oldTemplateHash) {\n changed = true\n }\n }\n\n return { settings, changed }\n}\n\nexport const checkConfig = async (ctx: Context) => {\n const {\n vtex: { logger },\n clients: { vbase },\n } = ctx\n\n let settings: Settings | null = null\n let changed = false\n\n const currTemplateHash = toHash(templates)\n\n try {\n settings = await vbase.getJSON<Settings | null>(APP_NAME, 'settings', true)\n } catch (error) {\n logger.error({\n error,\n message: 'checkConfig-getAppSettingsError',\n })\n\n return null\n }\n\n if (\n !settings?.adminSetup?.cartLifeSpan &&\n !settings?.adminSetup?.quotesManagedBy\n ) {\n settings = defaultSettings\n changed = true\n }\n\n const initializationResult = await checkInitializations({\n settings,\n currTemplateHash,\n changed,\n ctx,\n })\n\n settings = initializationResult.settings\n changed = initializationResult.changed\n\n if (changed) {\n await vbase.saveJSON(APP_NAME, 'settings', settings)\n }\n\n await checkAndCreateQuotesConfig(ctx)\n\n return settings\n}\n\n```"
}
] |
code_b2b-quotes-graphql_b2e7055c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/routes/index.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { method } from '@vtex/api'\n\nimport { getAppId } from '../../constants'\nimport { processQueue } from '../../utils/Queue'\nimport { getSellerQuote } from './seller/getSellerQuote'\nimport { getSellerQuotesPaginated } from './seller/getSellerQuotesPaginated'\nimport { saveSellerQuote } from './seller/saveSellerQuote'\nimport {\n setSellerResponseMetadata,\n validateSellerRequest,\n} from './seller/utils'\n\nfunction createSellerHandlers(\n mainHandler: (ctx: Context, next: NextFn) => Promise<void>\n) {\n return [validateSellerRequest, mainHandler, setSellerResponseMetadata]\n}\n\nexport const Routes = {\n host: async (ctx: Context) => {\n ctx.set('Content-Type', 'application/json')\n ctx.set('Cache-Control', 'no-cache, no-store')\n ctx.response.body = {\n host: ctx.vtex.host,\n }\n },\n queueHandler: async (ctx: Context) => {\n const date = new Date().toISOString()\n\n processQueue(ctx)\n ctx.set('Content-Type', 'application/json')\n ctx.set('Cache-Control', 'no-cache, no-store')\n ctx.response.body = { date, appId: getAppId() }\n ctx.response.status = 200\n },\n getSellerQuote: method({\n GET: createSellerHandlers(getSellerQuote),\n }),\n getSellerQuotesPaginated: method({\n GET: createSellerHandlers(getSellerQuotesPaginated),\n }),\n saveSellerQuote: method({\n POST: createSellerHandlers(saveSellerQuote),\n }),\n}\n\n```"
}
] |
code_b2b-quotes-graphql_1a9293c0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/routes/seller/utils.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ForbiddenError } from '@vtex/api'\n\nimport SellerQuotesController from '../../utils/sellerQuotesController'\n\nconst USER_AGENT_REGEX = /^vtex\\.b2b-seller-quotes@\\d+\\.\\d+\\.\\d+$/\n\nexport function invalidParam(\n param?: string | string[]\n): param is string[] | undefined {\n return !param || Array.isArray(param)\n}\n\nexport async function validateSellerRequest(ctx: Context, next: NextFn) {\n const { seller } = ctx.vtex.route.params\n\n if (\n invalidParam(seller) ||\n seller !== ctx.headers['x-vtex-origin-account'] ||\n !ctx.headers['user-agent']?.match(USER_AGENT_REGEX)\n ) {\n throw new ForbiddenError('request-not-allowed')\n }\n\n ctx.vtex.sellerQuotesController = new SellerQuotesController(ctx, seller)\n\n await next()\n}\n\nexport async function setSellerResponseMetadata(ctx: Context) {\n ctx.set('Access-Control-Allow-Origin', '*')\n ctx.set('Content-Type', 'application/json')\n ctx.status = 200\n}\n\n```"
}
] |
code_b2b-quotes-graphql_d9cd7fab
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/routes/seller/getSellerQuote.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\n\nimport { invalidParam } from './utils'\n\nexport async function getSellerQuote(ctx: Context, next: NextFn) {\n const { id } = ctx.vtex.route.params\n\n if (invalidParam(id)) {\n throw new UserInputError('get-seller-quote-invalid-params')\n }\n\n const quote = await ctx.vtex.sellerQuotesController?.getFullSellerQuote(id)\n\n ctx.body = quote\n\n await next()\n}\n\n```"
}
] |
code_b2b-quotes-graphql_0508949e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/routes/seller/getSellerQuotesPaginated.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { invalidParam } from './utils'\n\nexport async function getSellerQuotesPaginated(ctx: Context, next: NextFn) {\n const { query } = ctx\n const {\n page,\n pageSize,\n search,\n status,\n where: customWhere = '',\n sort,\n } = query\n\n const pageNumber = parseInt(Array.isArray(page) ? page[0] : page || '1', 10)\n const pageSizeNumber = parseInt(\n Array.isArray(pageSize) ? pageSize[0] : pageSize || '25',\n 10\n )\n\n const filters: string[] = []\n\n if (!invalidParam(search)) {\n const searchTerm = `*${search.replace(/'/g, '').split(/\\s+/).join('*')}*`\n\n filters.push(\n `(referenceName='${searchTerm}' OR creatorEmail='${searchTerm}' OR creatorName='${searchTerm}')`\n )\n }\n\n if (!invalidParam(status)) {\n filters.push(`(status=${status})`)\n }\n\n if (!invalidParam(customWhere)) {\n filters.push(`(${customWhere})`)\n }\n\n const where = filters.join(' AND ')\n const validPage = pageNumber >= 0 ? pageNumber : 1\n const validPageSize = pageSizeNumber >= 0 ? pageSizeNumber : 25\n\n ctx.body = await ctx.vtex.sellerQuotesController?.getSellerQuotesPaginated({\n page: validPage,\n pageSize: validPageSize,\n where,\n ...(!invalidParam(sort) && { sort }),\n })\n\n await next()\n}\n\n```"
}
] |
code_b2b-quotes-graphql_6ec6c8f9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of b2b-quotes-graphql/node/resolvers/routes/seller/saveSellerQuote.ts from the b2b-quotes-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\nimport { json } from 'co-body'\n\nimport { invalidParam } from './utils'\n\nfunction throwsInputError(): never {\n throw new UserInputError('save-seller-quote-invalid-params')\n}\n\nexport async function saveSellerQuote(ctx: Context, next: NextFn) {\n const { id } = ctx.vtex.route.params\n\n if (invalidParam(id)) {\n throwsInputError()\n }\n\n const payload: Partial<Quote> = await json(ctx.req)\n\n if (!payload) {\n throwsInputError()\n }\n\n await ctx.vtex.sellerQuotesController?.saveSellerQuote(id, payload)\n\n await next()\n}\n\n```"
}
] |
code_product-quantity_b63c3540
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/messages/pt.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-quantity.quantity\": \"Quantidade\",\n \"store/product-quantity.quantity-available\": \"{availableQuantity, plural, one {# disponível} other {# disponíveis}}\",\n \"admin/editor.product-quantity.title\": \"Componente da quantidade do produto\",\n \"admin/editor.product-quantity.description\": \"Componente que permite aos usuários selecionar o número de itens a serem adicionados ao carrinho\",\n \"admin/editor.product-quantity.warningQuantityThreshold.title\": \"Limite para aviso de quantidade disponível\",\n \"admin/editor.product-quantity.warningQuantityThreshold.description\": \"Exibir apenas a quantidade de itens restantes em estoque se a quantidade disponível for menor ou igual ao valor informado nesta propriedade\",\n \"admin/editor.product-quantity.showUnit.title\": \"Unidade de medida no seletor de quantidade\",\n \"admin/editor.product-quantity.showUnit.description\": \"Mostrar ou ocultar a unidade de medida no seletor de quantidade\"\n}\n\n```"
}
] |
code_product-quantity_0b93d021
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/messages/en.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-quantity.quantity\": \"Quantity\",\n \"store/product-quantity.quantity-available\": \"{availableQuantity, plural, one {# available} other {# available}}\",\n \"admin/editor.product-quantity.title\": \"Product quantity component\",\n \"admin/editor.product-quantity.description\": \"A component that allows users to select the number of items to add to cart\",\n \"admin/editor.product-quantity.warningQuantityThreshold.title\": \"Threshold for available quantity warning\",\n \"admin/editor.product-quantity.warningQuantityThreshold.description\": \"Only show the quantity of remaining items in stock if available item quantity is less than or equal to the value passed in this property\",\n \"admin/editor.product-quantity.showUnit.title\": \"Unit of measure in quantity selector\",\n \"admin/editor.product-quantity.showUnit.description\": \"Show or hide unit of measure in quantity selector\"\n}\n\n```"
}
] |
code_product-quantity_7802e6a8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/messages/fr.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-quantity.quantity\": \"Quantité\",\n \"store/product-quantity.quantity-available\": \"{availableQuantity, plural, one {# disponible} other {# disponibles}}\",\n \"admin/editor.product-quantity.title\": \"Composant de la quantité de produit\",\n \"admin/editor.product-quantity.description\": \"Un composant qui permet aux utilisateurs de sélectionner le nombre d’articles à ajouter au panier\",\n \"admin/editor.product-quantity.warningQuantityThreshold.title\": \"Seuil d'alerte pour la quantité disponible\",\n \"admin/editor.product-quantity.warningQuantityThreshold.description\": \"N'afficher la quantité d'articles restants en stock que si la quantité d'articles disponibles est inférieure ou égale à la valeur indiquée dans cette propriété\",\n \"admin/editor.product-quantity.showUnit.title\": \"Unité de mesure dans le sélecteur de quantité\",\n \"admin/editor.product-quantity.showUnit.description\": \"Afficher ou masquer l'unité de mesure dans le sélecteur de quantité\"\n}\n\n```"
}
] |
code_product-quantity_a206d9ba
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/messages/context.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-quantity.quantity\": \"Quantity\",\n \"store/product-quantity.quantity-available\": \"{availableQuantity, plural, one {# available} other {# available}}\",\n \"admin/editor.product-quantity.title\": \"Title of Product Quantity component\",\n \"admin/editor.product-quantity.description\": \"Description of Product Quantity component\",\n \"admin/editor.product-quantity.warningQuantityThreshold.title\": \"Title of warningQuantityThreshold property\",\n \"admin/editor.product-quantity.warningQuantityThreshold.description\": \"Description of warningQuantityThreshold property\",\n \"admin/editor.product-quantity.showUnit.title\": \"Title of showUnit property\",\n \"admin/editor.product-quantity.showUnit.description\": \"Description of showUnit property\"\n}\n\n```"
}
] |
code_product-quantity_b9e58e1e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/messages/id.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-quantity.quantity\": \"Jumlah\",\n \"store/product-quantity.quantity-available\": \"{availableQuantity, plural, one {# tersedia} other {# tersedia}}\",\n \"admin/editor.product-quantity.title\": \"Komponen Jumlah Produk\",\n \"admin/editor.product-quantity.description\": \"Komponen yang memungkinkan pengguna untuk memilih jumlah item untuk ditambahkan ke troli\",\n \"admin/editor.product-quantity.warningQuantityThreshold.title\": \"Peringatan ambang batas jumlah yang tersedia\",\n \"admin/editor.product-quantity.warningQuantityThreshold.description\": \"Hanya tampilkan jumlah item yang stoknya tersedia jika jumlah item yang tersedia kurang atau sama dengan nilai yang diteruskan dalam properti ini\",\n \"admin/editor.product-quantity.showUnit.title\": \"Satuan ukuran dalam pemilih jumlah\",\n \"admin/editor.product-quantity.showUnit.description\": \"Tampilkan atau sembunyikan satuan ukuran dalam pemilih jumlah\"\n}\n\n```"
}
] |
code_product-quantity_6fddbea8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/messages/no.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-quantity.quantity\": \"Antall\",\n \"store/product-quantity.quantity-available\": \"{availableQuantity, plural, one {# tilgjengelig} other {# tilgjengelig}}\",\n \"admin/editor.product-quantity.title\": \"Komponent for produktmengde\",\n \"admin/editor.product-quantity.description\": \"En komponent som lar brukeren velge antall varer å legge i handlekurven\",\n \"admin/editor.product-quantity.warningQuantityThreshold.title\": \"Terskeladvarsel for tilgjengelig mengde\",\n \"admin/editor.product-quantity.warningQuantityThreshold.description\": \"Vis kun antall gjenværende varer på lager dersom tilgjengelige antall er mindre enn eller lik verdien som passeres i denne egenskapen\",\n \"admin/editor.product-quantity.showUnit.title\": \"Måleenhet i mengdevelgeren\",\n \"admin/editor.product-quantity.showUnit.description\": \"Vis eller skjul måleenhet i mengdevelgeren\"\n}\n\n```"
}
] |
code_product-quantity_35785b45
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/messages/th.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-quantity.quantity\": \"จำนวน\",\n \"store/product-quantity.quantity-available\": \"{availableQuantity, plural, one {# พร้อมจำหน่่าย} other {# พร้อมจำหน่่าย}}\",\n \"admin/editor.product-quantity.title\": \"คอมโพเนนต์ของจำนวนผลิตภัณฑ์\",\n \"admin/editor.product-quantity.description\": \"คอมโพเนนต์ที่ทำให้ผู้ใช้สามารถเลือกจำนวนสินค้าเพื่อเพิ่มลงในรถเข็น\",\n \"admin/editor.product-quantity.warningQuantityThreshold.title\": \"เกณฑ์การเตือนจำนวนสินค้าพร้อมจำหน่าย\",\n \"admin/editor.product-quantity.warningQuantityThreshold.description\": \"แสดงเฉพาะจำนวนสินค้าคงเหลือในคลังสินค้า หากจำนวนสินค้าพร้อมจำหน่ายน้อยกว่าหรือเท่ากับค่าที่ส่งผ่านในคุณสมบัตินี้\",\n \"admin/editor.product-quantity.showUnit.title\": \"หน่วยวัดในตัวเลือกจำนวน\",\n \"admin/editor.product-quantity.showUnit.description\": \"แสดงหรือซ่อนหน่วยวัดในตัวเลือกจำนวน\"\n}\n\n```"
}
] |
code_product-quantity_3142fcd0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/messages/nn.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-quantity.quantity\": \"Antall\",\n \"store/product-quantity.quantity-available\": \"{availableQuantity, plural, one {# tilgjengelig} other {# tilgjengelig}}\",\n \"admin/editor.product-quantity.title\": \"Komponent for produktmengde\",\n \"admin/editor.product-quantity.description\": \"En komponent som lar brukeren velge antall varer å legge i handlekurven\",\n \"admin/editor.product-quantity.warningQuantityThreshold.title\": \"Terskeladvarsel for tilgjengelig mengde\",\n \"admin/editor.product-quantity.warningQuantityThreshold.description\": \"Vis kun antall gjenværende varer på lager dersom tilgjengelige antall er mindre enn eller lik verdien som passeres i denne egenskapen\",\n \"admin/editor.product-quantity.showUnit.title\": \"Måleenhet i mengdevelgeren\",\n \"admin/editor.product-quantity.showUnit.description\": \"Vis eller skjul måleenhet i mengdevelgeren\"\n}\n\n```"
}
] |
code_product-quantity_c0bc46e1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/messages/es.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-quantity.quantity\": \"Cantidad\",\n \"store/product-quantity.quantity-available\": \"{availableQuantity, plural, one {# disponible} other {# disponibles}}\",\n \"admin/editor.product-quantity.title\": \"Componente de cantidad de producto\",\n \"admin/editor.product-quantity.description\": \"Componente que permite a los usuarios seleccionar el número de ítems a agregar al carrito\",\n \"admin/editor.product-quantity.warningQuantityThreshold.title\": \"Límite para aviso de cantidad disponible\",\n \"admin/editor.product-quantity.warningQuantityThreshold.description\": \"Mostrar la cantidad de ítems restantes en stock solo si la cantidad disponible es menor o igual al valor definido en esta propiedad\",\n \"admin/editor.product-quantity.showUnit.title\": \"Unidad de medida en el selector de cantidad\",\n \"admin/editor.product-quantity.showUnit.description\": \"Mostrar u ocultar la unidad de medida en el selector de cantidad\"\n}\n\n```"
}
] |
code_product-quantity_16f17751
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/messages/ar.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-quantity.quantity\": \"الكمية\",\n \"store/product-quantity.quantity-available\": \"{availableQuantity, plural, one {# متاح} other {# متاحة}}\",\n \"admin/editor.product-quantity.title\": \"مكون كمية المنتج\",\n \"admin/editor.product-quantity.description\": \"مكون يسمح للمستخدم بتحديد كمية العناصر لإضافتها إلى سلة التسوق\",\n \"admin/editor.product-quantity.warningQuantityThreshold.title\": \"تحذير بعتبة الكمية المتاحة\",\n \"admin/editor.product-quantity.warningQuantityThreshold.description\": \"اعرض فقط كمية العناصر المتبقية في المخزون إذا كانت الكمية المتاحة للعنصر أقل من القيمة التي تم تمريرها في هذه المؤسسة أو تساويها\",\n \"admin/editor.product-quantity.showUnit.title\": \"وحدة القياس في منتقي الكمية\",\n \"admin/editor.product-quantity.showUnit.description\": \"إظهار أو إخفاء وحدة القياس في منتقي الكمية\"\n}\n\n```"
}
] |
code_product-quantity_2939f8d2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/docs/README.md from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Don't fork this project. Use, [contribute](https://github.com/vtex-apps/product-quantity), or open issues through [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Product Quantity\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\nThe Product Quantity allows users to a add a chosen amount of the displayed product in their cart.\n\n\n\n## Configuration \n\n1. Add the Product Quantity app to your dependencies in the theme's `manifest.json` file:\n\n```json\n \"dependencies\": {\n \"vtex.product-quantity\": \"1.x\"\n }\n```\n\nYou are now able to use all blocks that are exported by the Product Quantity app. Check out the full list below:\n\n| Block name | Description | \n| --------- | ------------ |\n| `product-quantity` | Displays a quantity selector on the product details page. This block must be declared in the theme's `store.product` page template. | \n| `product-summary-quantity` | Displays a quantity selector on [Product Summary](https://vtex.io/docs/components/all/vtex.product-summary/)'s blocks. This block must be declared as a children of the `product-summary.shelf` block. | \n\n2. According to your desired scenario, add the `product-quantity`/`product-summary-quantity` blocks to your theme. For example:\n\n```diff\n \"flex-layout.col#product-price\": {\n \"props\": {\n \"preventVerticalStretch\": true,\n \"rowGap\": 0\n },\n \"children\": [\n \"product-name\",\n \"product-price#product-details\",\n \"product-separator\",\n+ \"product-quantity\",\n \"sku-selector\",\n \"flex-layout.row#buy-button\",\n \"availability-subscriber\",\n \"shipping-simulator\",\n \"share\"\n ]\n },\n \"product-quantity\": {\n \"props\": {\n \"warningQuantityThreshold\": 9999999,\n \"showUnit\": true\n }\n },\n```\n\n*In the example above a Product Details Page is built using Flex Layout and the `product-quantity` block.*\n\n### `product-quantity` and `product-summary-quantity` props\n\n| Prop name | Type | Description | Default Value |\n| --- | --- | --- | --- |\n| `warningQuantityThreshold` | `number` | Displays the quantity of remaining items in stock if the available quantity is less than or equal to the value given to this property. | `0` (the quantity is not displayed) |\n| `showUnit` | `boolean` |Whether the unit of measurement should be displayed (`true`) or not (`false`). | `true` |\n| `size` | `enum`| Preset size values for `font-size` and `padding`. You can check these value measures by accessing the [VTEX Styleguide](https://styleguide.vtex.com/#/Components/Forms/NumericStepper). Possible values are: `small`, `regular`, and `large`. | `small` |\n| `showLabel` | `boolean` | Whether a label should be displayed (`true`) or not (`false`). | `true` |\n| `selectorType` | `enum` | Defines how the quantity selector should initially behave. Possible values are: `stepper` (displays an input field where the quantity can be directly defined, in addition to side buttons to increase or decrease the value) and `dropdown` (shows a list of predefined-quantity options. In case the last quantity option is selected by users, the component is replaced with an input). | `stepper` |\n| `quantitySelectorStep` | `enum` | Defines how the number of products that have unitMultiplier will works. Possible values are: `singleUnit` (the quantity will be not affected with the unitMultiplier) and `unitMultiplier` (the quantity will be affected with the unitMultiplier). | `unitMultiplier` |\n\n## Customization\n\nIn order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization). \n\n| CSS Handles |\n| ------------------------------------------ | \n| `availableQuantityContainer` |\n| `quantitySelectorContainer` |\n| `quantitySelectorDropdownContainer` |\n| `quantitySelectorDropdownMobileContainer` |\n| `quantitySelectorInputContainer` |\n| `quantitySelectorInputMobileContainer` |\n| `quantitySelectorStepper` |\n| `quantitySelectorTitle` |\n| `summaryContainer` |\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n <tr>\n <td align=\"center\"><a href=\"https://github.com/regis-samurai\"><img src=\"https://avatars0.githubusercontent.com/u/38638226?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Reginaldo</b></sub></a><br /><a href=\"https://github.com/vtex-apps/product-quantity/commits?author=regis-samurai\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n\n```"
}
] |
code_product-quantity_cc792452
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/react/ProductSummaryQuantity.tsx from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\nimport useProduct from 'vtex.product-context/useProduct'\nimport { useProductDispatch } from 'vtex.product-context/ProductDispatchContext'\n\nimport BaseProductQuantity, {\n BaseProps,\n} from './components/BaseProductQuantity'\n\nconst CSS_HANDLES = ['summaryContainer'] as const\n\nconst ProductSummaryQuantity: StorefrontFunctionComponent<BaseProps> = props => {\n const {\n warningQuantityThreshold,\n showLabel,\n size,\n selectorType,\n showUnit,\n quantitySelectorStep,\n } = props\n const handles = useCssHandles(CSS_HANDLES)\n const { selectedItem, selectedQuantity } = useProduct()\n const dispatch = useProductDispatch()\n\n const handleClick: React.MouseEventHandler<HTMLDivElement> = e => {\n e.preventDefault()\n // Stop propagation so it doesn't trigger the Link component above\n e.stopPropagation()\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions\n <div\n onClick={handleClick}\n className={`${handles.summaryContainer} center mw-100`}>\n <BaseProductQuantity\n showUnit={showUnit}\n size={size}\n dispatch={dispatch}\n showLabel={showLabel}\n selectedItem={selectedItem}\n selectedQuantity={selectedQuantity}\n selectorType={selectorType}\n warningQuantityThreshold={warningQuantityThreshold}\n quantitySelectorStep={quantitySelectorStep}\n />\n </div>\n )\n}\n\nProductSummaryQuantity.schema = {\n title: 'admin/editor.product-quantity.title',\n description: 'admin/editor.product-quantity.description',\n}\n\nexport default ProductSummaryQuantity\n\n```"
}
] |
code_product-quantity_a9174d57
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/react/package.json from the product-quantity 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 .\"\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-intl\": \"^2.7.2\",\n \"react-dom\": \"^16.8.3\"\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 \"typescript\": \"3.9.7\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.device-detector\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.device-detector@0.2.5/public/@types/vtex.device-detector\",\n \"vtex.native-types\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.native-types@0.7.1/public/@types/vtex.native-types\",\n \"vtex.product-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.9.2/public/@types/vtex.product-context\",\n \"vtex.product-summary-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-summary-context@0.5.0/public/@types/vtex.product-summary-context\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.122.2/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.133.0/public/@types/vtex.styleguide\"\n },\n \"version\": \"1.11.0\"\n}\n\n```"
}
] |
code_product-quantity_5d8e93b6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/react/ProductQuantity.tsx from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport useProduct from 'vtex.product-context/useProduct'\nimport { useProductDispatch } from 'vtex.product-context/ProductDispatchContext'\n\nimport BaseProductQuantity, {\n BaseProps,\n} from './components/BaseProductQuantity'\n\nconst ProductQuantity: StorefrontFunctionComponent<BaseProps> = props => {\n const {\n warningQuantityThreshold,\n showLabel,\n size,\n selectorType,\n showUnit,\n quantitySelectorStep,\n } = props\n const { selectedItem, selectedQuantity } = useProduct()\n const dispatch = useProductDispatch()\n\n return (\n <BaseProductQuantity\n showUnit={showUnit}\n size={size}\n dispatch={dispatch}\n showLabel={showLabel}\n selectedItem={selectedItem}\n selectedQuantity={selectedQuantity}\n selectorType={selectorType}\n warningQuantityThreshold={warningQuantityThreshold}\n quantitySelectorStep={quantitySelectorStep}\n />\n )\n}\n\nProductQuantity.schema = {\n title: 'admin/editor.product-quantity.title',\n description: 'admin/editor.product-quantity.description',\n}\n\nexport default ProductQuantity\n\n```"
}
] |
code_product-quantity_d5311267
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/store/contentSchemas.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"definitions\": {\n \"ProductQuantity\": {\n \"type\": \"object\",\n \"properties\": {\n \"warningQuantityThreshold\": {\n \"title\": \"admin/editor.product-quantity.warningQuantityThreshold.title\",\n \"description\": \"admin/editor.product-quantity.warningQuantityThreshold.title\",\n \"type\": \"number\",\n \"default\": 0\n },\n \"showUnit\": {\n \"title\": \"admin/editor.product-quantity.showUnit.title\",\n \"description\": \"admin/editor.product-quantity.showUnit.title\",\n \"type\": \"boolean\",\n \"default\": true\n }\n }\n },\n \"ProductSummaryQuantity\": {\n \"type\": \"object\",\n \"properties\": {\n \"warningQuantityThreshold\": {\n \"title\": \"admin/editor.product-quantity.warningQuantityThreshold.title\",\n \"description\": \"admin/editor.product-quantity.warningQuantityThreshold.title\",\n \"type\": \"number\",\n \"default\": 0\n },\n \"showUnit\": {\n \"title\": \"admin/editor.product-quantity.showUnit.title\",\n \"description\": \"admin/editor.product-quantity.showUnit.description\",\n \"type\": \"boolean\",\n \"default\": true\n }\n }\n }\n }\n}\n\n```"
}
] |
code_product-quantity_2a3f2d30
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/store/interfaces.json from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"product-quantity\": {\n \"component\": \"ProductQuantity\",\n \"content\": {\n \"$ref\": \"#/definitions/ProductQuantity\"\n }\n },\n \"product-summary-quantity\": {\n \"component\": \"ProductSummaryQuantity\",\n \"content\": {\n \"$ref\": \"#/definitions/ProductSummaryQuantity\"\n }\n }\n}\n\n```"
}
] |
code_product-quantity_382168de
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/react/typings/storefront.d.ts from the product-quantity 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_product-quantity_b11ff635
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/react/typings/vtex.css-handles.d.ts from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.css-handles' {\n type CssHandlesInput = readonly string[]\n type ValueOf<T extends readonly any[]> = T[number]\n type CssHandles<T extends CssHandlesInput> = Record<ValueOf<T>, string>\n interface CssHandlesOptions {\n migrationFrom?: string | string[]\n }\n\n export const useCssHandles: <T extends CssHandlesInput>(\n handles: T,\n options: CssHandlesOptions = {}\n ) => CssHandles<T>\n export const applyModifiers: (\n handles: string,\n modifier: string | string[]\n ) => string\n}\n\n```"
}
] |
code_product-quantity_a2808e95
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/react/typings/vtex.product-context.d.ts from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.product-context/useProduct' {\n const useProduct: () => ProductContext\n export default useProduct\n}\n\ndeclare module 'vtex.product-context' {\n export interface ProductContext {\n selectedQuantity: number\n selectedItem?: SelectedItem\n }\n\n interface SelectedItem {\n itemId: string\n unitMultiplier: number\n measurementUnit: string\n sellers: Array<{\n commertialOffer: {\n AvailableQuantity: number\n }\n sellerDefault: boolean\n }>\n }\n}\n\ndeclare module 'vtex.product-context/ProductDispatchContext' {\n type DispatchFunction = (payload: { type: string; args?: object }) => void\n export const useProductDispatch: () => DispatchFunction\n}\n\n```"
}
] |
code_product-quantity_cce5b2d2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/react/typings/css.d.ts from the product-quantity 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-quantity_e468e6b6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/react/typings/vtex.product-summary-context.d.ts from the product-quantity VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.product-summary-context/ProductSummaryContext' {\n export const useProductSummary: () => ProductSummaryContext\n interface ProductSummaryContext {\n selectedQuantity: number\n selectedItem?: SelectedItem\n }\n\n interface SelectedItem {\n unitMultiplier: number\n measurementUnit: string\n sellers: Array<{\n commertialOffer: {\n AvailableQuantity: number\n }\n }>\n }\n\n type DispatchFunction = (payload: { type: string; args?: object }) => void\n export const useProductSummaryDispatch: () => DispatchFunction\n}\n\n```"
}
] |
code_product-quantity_18ee6198
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-quantity/react/typings/graphql.d.ts from the product-quantity 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```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.