id
stringlengths
12
53
messages
listlengths
3
3
code_custom-stock-export_2fbfd631
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/package.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"custom-stock-export\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"lint\": \"eslint --ext js,jsx,ts,tsx .\",\n \"format\": \"prettier --write \\\"**/*.{ts,tsx,js,jsx,json}\\\"\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"lint-staged\": {\n \"*.{ts,js,tsx,jsx}\": [\n \"eslint --fix\",\n \"prettier --write\"\n ],\n \"*.{json,graphql,gql}\": [\n \"prettier --write\"\n ]\n },\n \"dependencies\": {\n \"@vtex/api\": \"^6.45.0\",\n \"@vtex/clients\": \"^2.13.0\"\n },\n \"devDependencies\": {\n \"@vtex/prettier-config\": \"^0.2.0\",\n \"eslint\": \"^6.8.0\",\n \"eslint-config-vtex\": \"^12.4.0\",\n \"eslint-config-vtex-react\": \"^6.4.0\",\n \"husky\": \"^4.2.5\",\n \"lint-staged\": \"^10.2.2\",\n \"prettier\": \"^2.0.5\",\n \"typescript\": \"^3.8.3\"\n }\n}\n\n```" } ]
code_custom-stock-export_298d6d6a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/manifest.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"vendor\": \"vtexarg\",\n \"name\": \"custom-stock-export\",\n \"version\": \"0.0.1\",\n \"title\": \"Custom Stock Export\",\n \"description\": \"Custom Stock Export\",\n \"builders\": {\n \"messages\": \"1.x\",\n \"admin\": \"0.x\",\n \"react\": \"3.x\",\n \"docs\": \"0.x\"\n },\n \"dependencies\": {\n \"vtex.styleguide\": \"9.x\",\n \"vtex.catalog-graphql\": \"1.x\",\n \"vtex.inventory-graphql\": \"0.x\",\n \"vtex.logistics-carrier-commons\": \"0.x\",\n \"vtex.logistics-carrier-graphql\": \"0.x\"\n },\n \"billingOptions\": {\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n },\n \"type\": \"free\",\n \"availableCountries\": [\"*\"]\n },\n \"policies\": [\n {\n \"name\": \"outbound-access\",\n \"attrs\": {\n \"host\": \"{{account}}.myvtex.com\",\n \"path\": \"/*\"\n }\n },\n {\n \"name\": \"outbound-access\",\n \"attrs\": {\n \"host\": \"portal.vtexcommercestable.com.br\",\n \"path\": \"/api/*\"\n }\n },\n {\n \"name\": \"outbound-access\",\n \"attrs\": {\n \"host\": \"portal.vtexcommercebeta.com.br\",\n \"path\": \"/api/*\"\n }\n },\n {\n \"name\": \"outbound-access\",\n \"attrs\": {\n \"host\": \"{{account}}.vtexcommercestable.com.br\",\n \"path\": \"/api/*\"\n }\n },\n {\n \"name\": \"Get_Account_By_Identifier\"\n },\n {\n \"name\": \"ADMIN_DS\"\n },\n {\n \"name\": \"POWER_USER_DS\"\n },\n {\n \"name\": \"AdminPortal\"\n },\n {\n \"name\": \"colossus-fire-event\"\n },\n {\n \"name\": \"colossus-write-logs\"\n }\n ],\n \"$schema\": \"https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema\"\n}\n\n```" } ]
code_custom-stock-export_164d1286
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/package.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"custom-stock-export-back\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"lint\": \"eslint --ext js,jsx,ts,tsx .\",\n \"format\": \"prettier --write \\\"**/*.{ts,tsx,js,jsx,json}\\\"\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"lint-staged\": {\n \"*.{ts,js,tsx,jsx}\": [\n \"eslint --fix\",\n \"prettier --write\"\n ],\n \"*.{json,graphql,gql}\": [\n \"prettier --write\"\n ]\n },\n \"devDependencies\": {\n \"@types/node\": \"^12.12.21\",\n \"@vtex/prettier-config\": \"^0.3.6\",\n \"eslint\": \"^7.16.0\",\n \"eslint-config-vtex\": \"^12.9.3\",\n \"husky\": \"^4.3.6\",\n \"lint-staged\": \"^10.5.3\",\n \"prettier\": \"^2.2.1\",\n \"typescript\": \"^3.7.5\"\n }\n}\n\n```" } ]
code_custom-stock-export_6794b0cf
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/manifest.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"custom-stock-export-back\",\n \"vendor\": \"vtexarg\",\n \"version\": \"0.0.1\",\n \"title\": \"Custom Stock Export Back\",\n \"description\": \"Custom Stock Export Back\",\n \"dependencies\": {},\n \"builders\": {\n \"node\": \"6.x\",\n \"docs\": \"0.x\"\n },\n \"billingOptions\": {\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n },\n \"type\": \"free\",\n \"availableCountries\": [\n \"*\"\n ]\n },\n \"scripts\": {\n \"prereleasy\": \"bash lint.sh\"\n },\n \"credentialType\": \"absolute\",\n \"policies\": [\n {\n \"name\": \"outbound-access\",\n \"attrs\": {\n \"host\": \"portal.vtexcommercestable.com.br\",\n \"path\": \"api/logistics/pvt/inventory/skus/*\"\n }\n },\n {\n \"name\": \"LogisticsAdmin\"\n },\n {\n \"name\": \"colossus-fire-event\"\n },\n {\n \"name\": \"colossus-write-logs\"\n }\n ],\n \"$schema\": \"https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema\"\n}\n\n```" } ]
code_custom-stock-export_642c3a97
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/messages/pt.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/admin.app.navigation.title\": \"Exportação de estoque personalizado\",\n \"admin/admin.app.navigation.search.kws\": \"personalizado, custom, estoque, exportação, export\",\n \"admin/admin.app.custom-stock-export.pageTitle\": \"Exportação de estoque personalizado\",\n \"admin/admin.app.custom-stock-export.exportButton\": \"Exportar\",\n \"admin/admin.app.custom-stock-export.columns.last-update\": \"Última atualização\",\n \"admin/admin.app.custom-stock-export.columns.reserved\": \"Reservados\",\n \"admin/admin.app.custom-stock-export.columns.available\": \"Disponível\",\n \"admin/admin.app.custom-stock-export.columns.warehouse\": \"Estoque\",\n \"admin/admin.app.custom-stock-export.commons.loading\": \"Carregando...\",\n \"admin/admin.app.custom-stock-export.filters.noOptionsFound\": \"Nenhum resultado encontrado\",\n \"admin/admin.app.custom-stock-export.filters.tryAgain\": \"Tente Novamente\",\n \"admin/admin.app.custom-stock-export.filters.category.loading\": \"Carregando…\",\n \"admin/admin.app.custom-stock-export.filters.category.placeholder\": \"Digite uma categoria…\",\n \"admin/admin.app.custom-stock-export.filters.category.error\": \"Algo deu errado ao tentar carregar as categorias\",\n \"admin/admin.app.custom-stock-export.filters.clear\": \"Filtros Claros\",\n \"admin/admin.app.custom-stock-export.filters.all\": \"Tudo\",\n \"admin/admin.app.custom-stock-export.filters.none\": \"Nenhum\",\n \"admin/admin.app.custom-stock-export.filters.any\": \"Algum\",\n \"admin/admin.app.custom-stock-export.filters.is\": \"igual\",\n \"admin/admin.app.custom-stock-export.filters.isNot\": \"não igual\",\n \"admin/admin.app.custom-stock-export.filters.contains\": \"contém\",\n \"admin/admin.app.custom-stock-export.filters.apply\": \"Aplique\",\n \"admin/admin.app.custom-stock-export.filters.and\": \"e\",\n \"admin/admin.app.custom-stock-export.filters.dropdown.between\": \"Entre\",\n \"admin/admin.app.custom-stock-export.filters.dropdown.greater-or-equal\": \"Maior que, ou igual a\",\n \"admin/admin.app.custom-stock-export.filters.dropdown.less-or-equal\": \"Menor que, ou igual a\",\n \"admin/admin.app.custom-stock-export.filters.label.between-values\": \"Entre {min} e {max}\",\n \"admin/admin.app.custom-stock-export.filters.label.greater-or-equal-value\": \"Maior que, ou igual a {value}\",\n \"admin/admin.app.custom-stock-export.filters.label.less-or-equal-value\": \"Menor que, ou igual a {value}\",\n \"admin/admin.app.custom-stock-export.filters.ok\": \"OK\",\n \"admin/admin.app.custom-stock-export.filters.search\": \"Buscar\",\n \"admin/admin.app.custom-stock-export.filters.warehouses-names-query-error\": \"Houve um erro ao carregar os estoques selecionados. Por favor, tente novamente.\",\n \"admin/admin.app.custom-stock-export.filters.warehouses-query-error\": \"Houve um erro ao carregar as opções restantes. Tentando novamente.\",\n \"admin/admin.app.custom-stock-export.filters.error.between\": \"Insira um valor máximo maior que o valor mínimo.\",\n \"admin/admin.app.custom-stock-export.filters.placeholder.maximum\": \"Máximo\",\n \"admin/admin.app.custom-stock-export.filters.placeholder.minimum\": \"Mínimo\"\n}\n\n```" } ]
code_custom-stock-export_b94fddd0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/messages/en.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/admin.app.navigation.title\": \"Custom Stock Export\",\n \"admin/admin.app.navigation.search.kws\": \"custom, stock, export\",\n \"admin/admin.app.custom-stock-export.pageTitle\": \"Custom Stock Export\",\n \"admin/admin.app.custom-stock-export.exportButton\": \"Export\",\n \"admin/admin.app.custom-stock-export.columns.last-update\": \"Last update\",\n \"admin/admin.app.custom-stock-export.columns.reserved\": \"Reserved\",\n \"admin/admin.app.custom-stock-export.columns.available\": \"Available\",\n \"admin/admin.app.custom-stock-export.columns.warehouse\": \"Warehouse\",\n \"admin/admin.app.custom-stock-export.commons.loading\": \"Loading...\",\n \"admin/admin.app.custom-stock-export.filters.noOptionsFound\": \"No results found\",\n \"admin/admin.app.custom-stock-export.filters.tryAgain\": \"Try Again\",\n \"admin/admin.app.custom-stock-export.filters.category.loading\": \"Loading…\",\n \"admin/admin.app.custom-stock-export.filters.category.placeholder\": \"Type a category…\",\n \"admin/admin.app.custom-stock-export.filters.category.error\": \"Something went wrong while trying to load categories\",\n \"admin/admin.app.custom-stock-export.filters.clear\": \"Clear Filters\",\n \"admin/admin.app.custom-stock-export.filters.all\": \"All\",\n \"admin/admin.app.custom-stock-export.filters.none\": \"None\",\n \"admin/admin.app.custom-stock-export.filters.any\": \"Any\",\n \"admin/admin.app.custom-stock-export.filters.is\": \"is\",\n \"admin/admin.app.custom-stock-export.filters.isNot\": \"is not\",\n \"admin/admin.app.custom-stock-export.filters.contains\": \"contains\",\n \"admin/admin.app.custom-stock-export.filters.apply\": \"Apply\",\n \"admin/admin.app.custom-stock-export.filters.and\": \"and\",\n \"admin/admin.app.custom-stock-export.filters.dropdown.between\": \"Between\",\n \"admin/admin.app.custom-stock-export.filters.dropdown.greater-or-equal\": \"Greater than, or equal to\",\n \"admin/admin.app.custom-stock-export.filters.dropdown.less-or-equal\": \"Less than, or equal to\",\n \"admin/admin.app.custom-stock-export.filters.label.between-values\": \"Between {min} and {max}\",\n \"admin/admin.app.custom-stock-export.filters.label.greater-or-equal-value\": \"Greater than, or equal to {value}\",\n \"admin/admin.app.custom-stock-export.filters.label.less-or-equal-value\": \"Less than, or equal to {value}\",\n \"admin/admin.app.custom-stock-export.filters.ok\": \"OK\",\n \"admin/admin.app.custom-stock-export.filters.search\": \"Search\",\n \"admin/admin.app.custom-stock-export.filters.warehouses-names-query-error\": \"There was an error loading selected warehouses. Please try again.\",\n \"admin/admin.app.custom-stock-export.filters.warehouses-query-error\": \"There was an error loading more options. Retrying.\",\n \"admin/admin.app.custom-stock-export.filters.error.between\": \"Insert a maximum value that is greater than the minimum value\",\n \"admin/admin.app.custom-stock-export.filters.placeholder.maximum\": \"Maximum\",\n \"admin/admin.app.custom-stock-export.filters.placeholder.minimum\": \"Minimum\"\n}\n\n```" } ]
code_custom-stock-export_b85a41a1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/messages/es.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/admin.app.navigation.title\": \"Custom Stock Export\",\n \"admin/admin.app.navigation.search.kws\": \"personalizado, custom, stock, exportación, export\",\n \"admin/admin.app.custom-stock-export.pageTitle\": \"Custom Stock Export\",\n \"admin/admin.app.custom-stock-export.exportButton\": \"Exportar\",\n \"admin/admin.app.custom-stock-export.columns.last-update\": \"Última actualización\",\n \"admin/admin.app.custom-stock-export.columns.reserved\": \"Reservado\",\n \"admin/admin.app.custom-stock-export.columns.available\": \"Disponible\",\n \"admin/admin.app.custom-stock-export.columns.warehouse\": \"Almacén\",\n \"admin/admin.app.custom-stock-export.commons.loading\": \"Cargando...\",\n \"admin/admin.app.custom-stock-export.filters.noOptionsFound\": \"No se encontró ningún resultado\",\n \"admin/admin.app.custom-stock-export.filters.tryAgain\": \"Inténtelo nuevamente\",\n \"admin/admin.app.custom-stock-export.filters.category.loading\": \"Cargando…\",\n \"admin/admin.app.custom-stock-export.filters.category.placeholder\": \"Digite una categoría…\",\n \"admin/admin.app.custom-stock-export.filters.category.error\": \"Algo salió mal al intentar cargar las categorías\",\n \"admin/admin.app.custom-stock-export.filters.clear\": \"Limpiar Filtros\",\n \"admin/admin.app.custom-stock-export.filters.all\": \"Todos\",\n \"admin/admin.app.custom-stock-export.filters.none\": \"Ninguno\",\n \"admin/admin.app.custom-stock-export.filters.any\": \"Cualquiera\",\n \"admin/admin.app.custom-stock-export.filters.is\": \"igual\",\n \"admin/admin.app.custom-stock-export.filters.isNot\": \"no igual\",\n \"admin/admin.app.custom-stock-export.filters.contains\": \"contiene\",\n \"admin/admin.app.custom-stock-export.filters.apply\": \"Aplicar\",\n \"admin/admin.app.custom-stock-export.filters.and\": \"y\",\n \"admin/admin.app.custom-stock-export.filters.dropdown.between\": \"Entre\",\n \"admin/admin.app.custom-stock-export.filters.dropdown.greater-or-equal\": \"Mayor o igual que\",\n \"admin/admin.app.custom-stock-export.filters.dropdown.less-or-equal\": \"Menor o igual que\",\n \"admin/admin.app.custom-stock-export.filters.label.between-values\": \"Entre {min} y {max}\",\n \"admin/admin.app.custom-stock-export.filters.label.greater-or-equal-value\": \"Mayor o igual que {value}\",\n \"admin/admin.app.custom-stock-export.filters.label.less-or-equal-value\": \"Menor o igual que {value}\",\n \"admin/admin.app.custom-stock-export.filters.ok\": \"OK\",\n \"admin/admin.app.custom-stock-export.filters.search\": \"Buscar\",\n \"admin/admin.app.custom-stock-export.filters.warehouses-names-query-error\": \"Se produjo un error al cargar los almacenes seleccionados. Por favor, intente de nuevo.\",\n \"admin/admin.app.custom-stock-export.filters.warehouses-query-error\": \"Se produjo un error al cargar más opciones. Intentando de nuevo.\",\n \"admin/admin.app.custom-stock-export.filters.error.between\": \"Ingrese un valor máximo que sea superior al valor mínimo\",\n \"admin/admin.app.custom-stock-export.filters.placeholder.maximum\": \"Máximo\",\n \"admin/admin.app.custom-stock-export.filters.placeholder.minimum\": \"Mínimo\"\n}\n\n```" } ]
code_custom-stock-export_73fc8368
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/admin/navigation.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"section\": \"orders\",\n \"subSection\": \"inventoryAndShipping\",\n \"subSectionItems\": [\n {\n \"isNew\": true,\n \"labelId\": \"admin/admin.app.navigation.title\",\n \"path\": \"/admin/custom-stock-export\"\n }\n ],\n \"searchKeyWordsHelpers\": \"admin/admin.app.navigation.search.kws\"\n}\n\n```" } ]
code_custom-stock-export_89348b59
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/admin/routes.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin.app.custom-stock-export\": {\n \"component\": \"CustomStockExport\",\n \"path\": \"/admin/app/custom-stock-export\"\n }\n}\n\n```" } ]
code_custom-stock-export_aa48d534
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/docs/README.md from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/qr-barcode-reader) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Qr & Barcode Reader\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nScan Qr codes and Barcodes with the Ean of a product embedded and do action with it.\n\n![Media Placeholder](https://user-images.githubusercontent.com/55905671/131380395-e39ce499-2efa-4aaa-9506-f934fe9af8cf.gif)\n\n:warning: **Supported Barcodes:**\n- Ean 13\n- Ean 14\n- Ean 8\n- UPC-A\n---\n## Configuration \n\n### Step 1 - Adding the Qr & Barcode Reader app to your theme's dependencies\n\n1. Using your terminal and the [VTEX IO Toolbelt](https://vtex.io/docs/recipes/development/vtex-io-cli-installment-and-command-reference), log into the desired VTEX account.\n2. Run `vtex install vtexarg.qr-barcode-reader` on the account you're working on.\n3. Add the app as a theme peerDependency in the `manifest.json` file;\n```json\n\"peerDependencies\": {\n \"vtexarg.qr-barcode-reader\": \"0.x\"\n}\n```\nNow, you are able to use all blocks exported by the `qr-barcode-reader` app. Check out the full list below:\n\n| Block name | Description | \n| -------------- | ----------- | \n| `qr-reader` | Renders a button that allows you to scan a qr code. | \n| `barcode-reader` | Renders a button that allows you to scan a barcode. | \n\n### Step 2 - Adding the Qr & Barcode Reader's blocks to your theme's templates\n\nTo add the Qr & Barcode Reader's blocks in your theme, you just need to declare them as block of any component, this is because all exported blocks are thinking to be added anywhere in the store.\n\n```json\n \"store.home\": {\n \"blocks\": [\n \"qr-reader\",\n \"barcode-reader\"\n ]\n },\n```\n\nThe `qr-reader` block in this app has two props:\n\n| Prop name | Type | Description | Default value |\n| --------------------| ----------|--------------|---------------|\n| `separator` | `string` | The `separator` is a pattern that describes where each division of the qr code should occur. |`X`|\n| `eanIndex` | `number` | The `eanIndex` is the index of the division made by the `separator` in which the Ean will be within the qr code. | `0` |\n\nFor example:\n\n```json\n\"qr-reader\":{\n \"props\":{\n \"separator\": \"X\",\n \"eanIndex\": 3\n }\n},\n```\n\nIf the qr code have this code embeded: `division0Xdivision1Xdivision2X33675134Xdivision4`, we will split by the `separator` in 5 division (0 to 4), and with the `eanIndex` we will get the division number 3 that in this case contains the Ean.\n\nEvery block in this app only has three props in common:\n\n| Prop name | Type | Description | Default value |\n| --------------------| ----------|--------------|---------------|\n| `action` | `string` | The `action` that will do after the scan. Possible values are: `go-to-pdp` and `add-to-cart` | `go-to-pdp` |\n| `mode` | `string` | The `mode` indicates if we will have 1 Ean for 1 Sku or Many Eans for 1 Sku. Possible values are: `singleEan` and `multipleEan` | `singleEan` |\n| `blockClass` | `string` | Block ID of your choosing to be used in [CSS customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization#using-the-blockclass-property). | \n\n---\n\n## Multiple Ean\n\n> ℹ️ _You need to do this configuration **only** if you want to use the `mode` `multipleEan`_\n\n1. Go _Catalog -> Categories_ and in the Category father of alls, create a new `Product Field`\n![Media Placeholder](https://user-images.githubusercontent.com/55905671/134919291-f4131fc6-2721-49c3-b4ef-9973a7394861.gif)\n\n2. Set it up like this\n- Name = `MultipleEan`\n- Text = `MultipleEan`\n- Type = `Text`\n- Group = `Multiple Ean Group`\n- Filter = ✅\n- Active = ✅\n![Media Placeholder](https://user-images.githubusercontent.com/55905671/134919558-8a56b9d7-6588-4200-b8cd-dd8ee75797de.png)\n\n\n3. Copy the `id` of the created field\n![Media Placeholder](https://user-images.githubusercontent.com/55905671/134921342-73a630cb-61dc-4fab-83b8-9e334b3f4a0c.png)\n\n4. Go to the setup of the `Qr & Barcode Reader` component in \n<https://{workspace}--{account}.myvtex.com/admin/apps/vtexarg.qr-barcode-reader@{version}/setup>\n![Media Placeholder](https://user-images.githubusercontent.com/55905671/134928031-687c9beb-0b21-4dde-bed0-60193ee95309.png)\n\n5. Complete the `Id of Product Field MultipleEan` with the `id` copied before\n![Media Placeholder](https://user-images.githubusercontent.com/55905671/134928287-3ca3df2f-066b-4f09-86bc-5ef3bc259900.png)\n\n6. Edit `MultipleEan` field of the products that you want to have it multiples Ean. \n![Media Placeholder](https://user-images.githubusercontent.com/55905671/134929068-9b42913a-aaee-4b5a-9821-c05cb1ba43b4.png)\nFor the app to correctly identify which SKU of a product corresponds to which EAN, you need to ingress like this: \n`--SKU:EAN-SKU:EAN-SKU:EAN-SKU:EAN--` \n> ℹ️ _It is important that start and end with `--`_\n\n### Clarifications\n\n* If an EAN corresponds to two products, a modal will be displayed listing them and suggesting that the catalog be reviewed. None will be added to the cart.\n\n* If an EAN corresponds to a SKU but that SKU does not exist in the product in which that product field is loaded, a modal will be displayed commenting on it. None will be added to the cart.\n\n* If an EAN corresponds to 2 SKUs of the same product, the first one loaded in the product field will be added.\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| `qrReaderWrapper` | \n| `qrContainer` | \n| `barcodeReaderWrapper` | \n| `barcodeContainer` | \n| `modalReaderMessagesSucces` | \n| `modalReaderMessagesSuccesText` | \n| `modalReaderMessagesError` | \n| `modalReaderMessagesErrorText` | \n| `listErrorMutipleProductText` | \n\n---\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n<table>\n <tr>\n <td align=\"center\"><a href=\"https://github.com/germanBonacchi\"><img src=\"https://avatars.githubusercontent.com/u/55905671?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Germán Bonacchi</b></sub></a><br /><a href=\"https://github.com/vtex-apps/quantity-on-cart/commits?author=germanBonacchi\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n```" } ]
code_custom-stock-export_f1cdef4f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/types.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { QueryResult } from 'react-apollo'\nimport type {\n InventoryProduct,\n Paging,\n InventoryProductQuantityUpdateInput,\n InventoryProductQuantityUpdateOutput,\n} from 'vtex.inventory-graphql'\nimport type {\n Warehouse,\n Paging as LogisticsPaging,\n} from 'vtex.logistics-carrier-graphql'\nimport type Maybe from 'graphql/tsutils/Maybe'\n\nexport type QueriedInventoryProduct = Pick<\n InventoryProduct,\n | 'id'\n | 'sku'\n | 'warehouseId'\n | 'cacheId'\n | 'name'\n | 'warehouseName'\n | 'quantity'\n | 'reservedQuantity'\n | 'availableQuantity'\n | 'unlimited'\n>\n\nexport interface QueriedInventoryProductsPage {\n products: QueriedInventoryProduct[]\n paging: Pick<Paging, 'total' | 'pages'>\n}\n\nexport type QueriedChangelog = Pick<\n InventoryProduct,\n 'name' | 'warehouseName' | 'changelog'\n>\n\nexport type QueriedWarehouse = Pick<Warehouse, 'id' | 'name'>\n\nexport type QueriedWarehousesNames = Array<Pick<QueriedWarehouse, 'name'>>\n\nexport interface QueriedWarehousesPage {\n items: QueriedWarehouse[]\n paging: Pick<LogisticsPaging, 'page' | 'pages'>\n}\n\nexport type InventoryProductIds = Pick<InventoryProduct, 'sku' | 'warehouseId'>\n\nexport type QueriedInventoryProductData = Pick<\n InventoryProduct,\n | 'quantity'\n | 'availableQuantity'\n | 'reservedQuantity'\n | 'dispatchedReservations'\n | 'unlimited'\n> & {\n catalogProduct: Pick<InventoryProduct['catalogProduct'], 'id'>\n}\n\nexport type InventoryProductUpdateData = Pick<\n InventoryProductQuantityUpdateInput,\n 'quantity' | 'unlimited'\n> &\n Partial<\n Pick<InventoryProductQuantityUpdateOutput, 'errorCode' | 'errorMessage'>\n >\n\nexport type RowStatus = Pick<QueryResult, 'loading' | 'refetch'> & {\n loadingError: QueryResult['error']\n savingErrorCode: InventoryProductQuantityUpdateOutput['errorCode']\n savingErrorMessage: InventoryProductQuantityUpdateOutput['errorMessage']\n available: boolean\n}\n\nexport interface LoadingInventoryProductRow {\n loading: true\n id: string\n}\n\nexport type InventoryProductRow = QueriedInventoryProduct &\n Omit<QueriedInventoryProductData, 'catalogProduct'> & {\n loading: false\n updatedQuantity: InventoryProductQuantityUpdateInput['quantity']\n updatedUnlimited?: Maybe<InventoryProductQuantityUpdateInput['unlimited']>\n status: RowStatus\n catalogProduct: Maybe<QueriedInventoryProductData['catalogProduct']>\n }\n\nexport interface Motion {\n willChange: string\n transition: string\n}\n\nexport interface RowRendererArgs<TData = unknown> {\n index: number\n key: string\n props: {\n data: TData\n motion: Motion\n height: React.HTMLProps<HTMLTableRowElement>['height']\n }\n}\n\nexport interface RowProps {\n height: React.HTMLProps<HTMLTableRowElement>['height']\n motion: Motion\n}\n\n```" } ]
code_custom-stock-export_3096bd69
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/package.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"custom-stock-export\",\n \"version\": \"0.0.12\",\n \"devDependencies\": {\n \"@types/node\": \"^11.12.1\",\n \"@types/ramda\": \"^0.27.57\",\n \"@types/react\": \"^16.8.10\",\n \"@types/react-intl\": \"^3.0.0\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-client\": \"^2.4.7\",\n \"graphql\": \"^14.0.2\",\n \"prop-types\": \"^15.7.2\",\n \"react\": \"^17.0.1\",\n \"react-dom\": \"^17.0.1\",\n \"react-intl\": \"^5.20.10\",\n \"typescript\": \"3.9.7\",\n \"@types/lodash.debounce\": \"^4.0.6\",\n \"vtex.admin-inventory\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.admin-inventory@0.46.0/public/@types/vtex.admin-inventory\",\n \"vtex.inventory-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.inventory-graphql@0.18.2/public/@types/vtex.inventory-graphql\",\n \"vtex.logistics-carrier-commons\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.logistics-carrier-commons@0.66.0/public/@types/vtex.logistics-carrier-commons\",\n \"vtex.logistics-carrier-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.logistics-carrier-graphql@0.41.0/public/@types/vtex.logistics-carrier-graphql\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.3/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.2/public/@types/vtex.styleguide\"\n },\n \"dependencies\": {\n \"@types/faker\": \"^4.1.5\",\n \"@vtex/styleguide\": \"^9.145.1\",\n \"faker\": \"^4.1.0\",\n \"fix\": \"0.0.6\",\n \"ramda\": \"^0.27.1\",\n \"react-apollo\": \"^3.1.5\",\n \"react-collapsed\": \"^3.2.2\",\n \"lodash.debounce\": \"^4.0.8\"\n }\n}\n\n```" } ]
code_custom-stock-export_aab1093d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/CustomStockExport.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Layout, PageHeader, PageBlock } from 'vtex.styleguide'\nimport { useIntl } from 'react-intl'\n\nimport { appMessages } from './utils/intl'\nimport Filters from './components/Filters'\n\nexport default function CustomStockExport() {\n const intl = useIntl()\n\n return (\n <Layout\n fullWidth\n pageHeader={\n <PageHeader title={intl.formatMessage(appMessages.pageTitle)} />\n }\n >\n <PageBlock variation=\"full\">\n <Filters />\n </PageBlock>\n </Layout>\n )\n}\n\n```" } ]
code_custom-stock-export_51f7f9c4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/public/metadata/messages/es-AR.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"QR & Barcode Reader\",\n \"headline\": \"Escanee Qr y código de barras y haga lo que quiera con ellos!\",\n \"overview\": \"La aplicación QR & Barcode Reader le permite escanear códigos con un EAN de un sku embebido , ¡luego puede ir a la PDP o agregarlo a su carrito!\",\n \"features\": [\n \"Escanear códigos Qr\",\n \"Escanear códigos de barras\",\n \"Redirigir a la PDP de los productos escaneados\",\n \"Integración con minicart para agregar productos rápidamente\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_custom-stock-export_e071663f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/public/metadata/messages/pt-BR.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"QR & Barcode Reader\",\n \"headline\": \"Digitalize Qr e código de barras e faça o que quiser com eles!\",\n \"overview\": \"O aplicativo QR & Barcode Reader permite que você escaneie códigos com um EAN sku embutido, então você pode ir para o PDP ou adicioná-lo ao seu carrinho!\",\n \"features\": [\n \"Ler códigos Qr\",\n \"Scan Barcodes\",\n \"Redirecionar para o PDP dos produtos que você digitaliza\",\n \"Integração com minicart para adicionar produtos rapidamente\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_custom-stock-export_66a960b8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/public/metadata/messages/en-US.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"QR & Barcode Reader\",\n \"headline\": \"Scan Qr and Barcode and do whatever you want with them!\",\n \"overview\": \"The QR & Barcode Reader app allows you to scan codes with an embedded sku EAN, then you can go to the PDP or add it to your cart!\",\n \"features\": [\n \"Scan Qr codes\",\n \"Scan Barcodes\",\n \"Redirect to the PDP of the products that you scan\",\n \"Integration with minicart for add products quickly\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_custom-stock-export_8d840ddd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/typings/vtex.render-runtime.d.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport 'vtex.render-runtime'\n\n// FIXME: remove uncessary typings declarations when vtex.render-runtime exports them properly.\n// Since we're using `import type`, these import statements are clear for now\ndeclare module 'vtex.render-runtime' {\n import type {\n RenderContext as _RenderContext,\n withRuntimeContext as _withRuntimeContext,\n } from 'vtex.render-runtime/react/components/RenderContext'\n\n export type RenderContext = _RenderContext\n\n export const withRuntimeContext: _withRuntimeContext\n}\n\n```" } ]
code_custom-stock-export_500a9457
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/typings/gql.d.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n import type { DocumentNode } from 'graphql'\n\n const Schema: DocumentNode\n\n export default Schema\n}\n\ndeclare module '*.graphql' {\n import type { DocumentNode } from 'graphql'\n\n const schema: DocumentNode\n\n export default Schema\n}\n\n```" } ]
code_custom-stock-export_55917f02
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/typings/vtex.styleguide.icons.d.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.store-icons'\n\ndeclare module '@vtex/styleguide/lib/*' {\n const Component: ComponentType<unknown>\n export default Component\n}\n\n```" } ]
code_custom-stock-export_c3ea6ab5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/typings/styleguide.d.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/naming-convention */\ndeclare module 'vtex.styleguide' {\n export const Alert\n export const Layout\n export const PageBlock\n export const PageHeader\n export const Table\n export const Input\n export const Spinner\n export const Button\n export const ButtonPlain\n export const ButtonWithIcon\n export const Collapsible\n export const Dropdown\n export const Toggle\n export const Modal\n export const NumericStepper\n export const ModalDialog\n export const ActionMenu\n export const EXPERIMENTAL_Select\n export const IconCheck\n export const IconOptionsDots\n export const IconSuccess\n export const IconClear\n export const IconArrowBack\n export const IconCaretLeft\n export const IconCaretRight\n export const IconCaretDown\n export const IconDelete\n export const IconGrid\n export const IconInlineGrid\n export const IconInfo\n export const IconSearch\n export const IconWarning\n export const IconFailure\n export const IconClose\n export const IconPlus\n export const IconExternalLink\n export const InputSearch\n export const Textarea\n export const DatePicker\n export const Checkbox\n export const ToastContext\n export const ToastProvider\n export const FloatingActionBar\n export const EmptyState\n export const Tooltip\n export const EXPERIMENTAL_Table\n export const EXPERIMENTAL_useTableMeasures\n export const EXPERIMENTAL_useTableProportion\n export interface CheckboxTree<T> {\n checkedItems: T[]\n disabledItems: T[]\n uncheck: (item: T | Tree<T>) => void\n isChecked: (item: T | Tree<T>) => boolean\n isPartiallyChecked: (item: T | Tree<T>) => boolean\n isDisabled: (item: T | Tree<T>) => boolean\n toggle: (item: T | Tree<T>) => boolean\n allChecked: boolean\n someChecked: boolean\n toggleAll: () => void\n uncheckAll: () => void\n }\n export const EXPERIMENTAL_useCheckboxTree: <T>(options: {\n items: T[] | Array<{ id: string; children: T[] }>\n comparator: (item: T) => (candidate: T) => boolean\n }) => CheckboxTree<T>\n export const EXPERIMENTAL_useTableVisibility\n export const EXPERIMENTAL_useTableSort\n export const RadioGroup\n export const Dropzone\n export const Progress\n export const AutocompleteOption\n export const Tab\n export const Tabs\n export const FilterBar\n\n export interface CellData<C> {\n rowHeight: number\n data: C\n motion: {\n transition?: string\n willChange?: string\n }\n density: Density\n }\n}\n\n```" } ]
code_custom-stock-export_446466fe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/typings/filters.d.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface SelectOption<T = string | Specification> {\n value: T\n label: string\n}\n\ninterface Specification {\n category: SelectOption\n specificationField: SelectOption\n specification: string\n}\n\ninterface Statement {\n error?: ApolloError\n object: SelectOption\n subject: string\n verb: string\n}\n\ninterface StatementOption {\n value: string\n label: string\n}\n\ninterface FilterProps {\n statements: Statement[]\n setStatements: (s: Statement[]) => void\n filteredByIsInCollection: boolean\n filterByIsInCollection: (id?: string) => void\n}\n\n```" } ]
code_custom-stock-export_86221e1f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/typings/css.d.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n type Styles = {\n [selector: string]: string\n }\n\n const styles: Styles\n\n export default styles\n}\n\n```" } ]
code_custom-stock-export_db6226f4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/typings/index.d.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ntype AutocompleteOption = string | StructuredAutocompleteOption\n\n```" } ]
code_custom-stock-export_62cc5f9e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/utils/autocomplete.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const MAX_ITEMS_AUTOCOMPLETE = 10\nexport const getTermFromOption = (option: AutocompleteOption): string =>\n typeof option === 'string' ? option : option.label\n\n```" } ]
code_custom-stock-export_26a3bd35
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/utils/pagination.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable vtex/prefer-early-return */\nimport { useState, useEffect } from 'react'\nimport { uniq, path } from 'ramda'\n\nimport { getTermFromOption } from './autocomplete'\n\nexport interface PaginatedData<T> {\n items: T[]\n paging: Paging\n}\n\nexport interface Paging {\n page: number\n perPage: number\n pages: number\n total: number\n}\n\nexport interface Pagination {\n page: number\n pageSize: number\n searchKey: string\n}\n\nexport type SetPagination = (pagination: Partial<Pagination>) => void\n\nexport const usePagination = (\n initialState: Pagination = { page: 1, pageSize: 5, searchKey: '' }\n): [Pagination, SetPagination] => {\n const [state, setState] = useState(initialState)\n\n return [\n state,\n (partialState: Partial<Pagination>) =>\n setState({ ...state, ...partialState }),\n ]\n}\n\ninterface UpdatePageArgs {\n oldPageSize: number\n pageSize: number\n from: number\n to: number\n}\n\nexport const newPage = ({\n oldPageSize,\n pageSize,\n from,\n to,\n}: UpdatePageArgs) => {\n return pageSize < oldPageSize\n ? Math.ceil(Math.max(from / pageSize, 1))\n : Math.ceil(Math.max(to / pageSize, 1))\n}\n\n/**\n * This function takes the Autocomplete options and only the unique options\n * will be structured. The options that appears multiple times will be turned into\n * a simple string so the term can be searched before going into the Collection page.\n */\nconst processAutocompleteOptions = (options: AutocompleteOption[]) => {\n const occurrences = options.reduce<{ [k: string]: number }>(\n (acc, option) => ({\n ...acc,\n [getTermFromOption(option)]: (acc[getTermFromOption(option)] || 0) + 1,\n }),\n {}\n )\n\n return options.map((option) =>\n occurrences[getTermFromOption(option)] > 1\n ? getTermFromOption(option)\n : option\n )\n}\n\nexport interface OptionsFetchMore {\n options: AutocompleteOption[]\n canFetchMore: boolean\n}\n\nexport interface Data {\n items: Item[]\n paging: Paging\n}\n\ninterface Item {\n id: Record<string, unknown>\n name: string\n}\n\nexport interface OptionsSource {\n data: Data\n pagination: Pagination\n loading: boolean\n}\nexport type SetOptions = (options: AutocompleteOption[]) => void\nexport type SetCanFetchMore = (canFetch: boolean) => void\n\nexport interface PaginatedOptions {\n options: AutocompleteOption[]\n setOptions: SetOptions\n canFetchMore: boolean\n setCanFetchMore: SetCanFetchMore\n}\n\nexport const usePaginatedOptions = (\n sourceState: OptionsSource,\n initialState: OptionsFetchMore = { options: [], canFetchMore: false }\n): PaginatedOptions => {\n const { pagination, data, loading } = sourceState\n const [options, setOptions] = useState(initialState.options)\n const [canFetchMore, setCanFetchMore] = useState(initialState.canFetchMore)\n\n useEffect(() => {\n if (!loading && path(['items'], data)) {\n const fetchedOptions = data.items.map(\n ({ id, name }: Item): AutocompleteOption => ({\n label: name,\n value: id,\n })\n )\n\n if (pagination.page === 1) {\n setOptions(uniq(processAutocompleteOptions(fetchedOptions)))\n } else {\n setOptions(\n uniq(processAutocompleteOptions(options.concat(fetchedOptions)))\n )\n }\n\n setCanFetchMore(data.paging?.pages > pagination.page)\n }\n }, [loading, data, pagination.searchKey, pagination.page])\n\n return {\n options,\n setOptions,\n canFetchMore,\n setCanFetchMore,\n }\n}\n\n```" } ]
code_custom-stock-export_54a5cb21
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/utils/inputs.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/**\n * Useful to avoid having to having to create another state for the input string,\n * because using type=\"number\" gives an empty ChangeEvent value when the\n * number is invalid, and it would clear the quantity variable as a consequence.\n */\nexport function isInteger(value: string) {\n return value.match(/^-?[0-9]*$/) != null\n}\n\n/**\n * Converts NaN to null, to make checks for invalid values easier.\n */\nexport function convertInteger(value: string) {\n return value === '' || Number.isNaN(+value) ? null : +value\n}\n\n```" } ]
code_custom-stock-export_88d7b8e4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/utils/intl.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { defineMessages } from 'react-intl'\n\nconst prefix = 'admin/admin.app.custom-stock-export.'\nconst prefixFilters = 'admin/admin.app.custom-stock-export.filters.'\n\nexport const appMessages = defineMessages({\n pageTitle: { id: `${prefix}pageTitle` },\n exportButton: { id: `${prefix}exportButton` },\n})\n\nexport const filtersMessages = defineMessages({\n clear: { id: `${prefixFilters}clear` },\n all: { id: `${prefixFilters}all` },\n none: { id: `${prefixFilters}none` },\n any: { id: `${prefixFilters}any` },\n is: { id: `${prefixFilters}is` },\n isNot: { id: `${prefixFilters}isNot` },\n contains: { id: `${prefixFilters}contains` },\n apply: { id: `${prefixFilters}apply` },\n loading: { id: `${prefixFilters}category.loading` },\n placeholder: { id: `${prefixFilters}category.placeholder` },\n error: { id: `${prefixFilters}category.error` },\n ok: { id: `${prefixFilters}ok` },\n and: { id: `${prefixFilters}and` },\n noOptionsFound: { id: `${prefixFilters}noOptionsFound` },\n tryAgain: { id: `${prefixFilters}tryAgain` },\n greaterOrEqualDropdown: { id: `${prefixFilters}dropdown.greater-or-equal` },\n greaterOrEqualLabel: { id: `${prefixFilters}label.greater-or-equal-value` },\n lessOrEqualDropdown: { id: `${prefixFilters}dropdown.less-or-equal` },\n lessOrEqualLabel: { id: `${prefixFilters}label.less-or-equal-value` },\n betweenDropdown: { id: `${prefixFilters}dropdown.between` },\n betweenLabel: { id: `${prefixFilters}label.between-values` },\n betweenInvalid: { id: `${prefixFilters}error.between` },\n maximumPlaceholder: { id: `${prefixFilters}placeholder.maximum` },\n minimumPlaceholder: { id: `${prefixFilters}placeholder.minimum` },\n search: { id: `${prefixFilters}search` },\n warehousesQueryError: { id: `${prefixFilters}warehouses-query-error` },\n warehousesNamesQueryError: {\n id: `${prefixFilters}warehouses-names-query-error`,\n },\n})\n\nexport const commonMessages = defineMessages({\n loading: { id: `${prefix}commons.loading` },\n})\n\nexport const columnsMessages = defineMessages({\n lastUpdate: { id: `${prefix}columns.last-update` },\n reserved: { id: `${prefix}columns.reserved` },\n available: { id: `${prefix}columns.available` },\n warehouse: { id: `${prefix}columns.warehouse` },\n})\n\n```" } ]
code_custom-stock-export_24231141
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/style/Loading.global.css from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.loading-container {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n}\n\n```" } ]
code_custom-stock-export_bb070123
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/LoadingSpinner.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { Spinner } from 'vtex.styleguide'\nimport React from 'react'\nimport '../style/Loading.global.css'\n\nexport default function LoadingSpinner() {\n return (\n <div className=\"loading-container\">\n <Spinner />\n </div>\n )\n}\n\n```" } ]
code_custom-stock-export_70c7d395
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/graphql/warehouses.graphql from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery warehouses($page: Int!, $perPage: Int!, $keyword: String) {\n warehouses(page: $page, perPage: $perPage, keyword: $keyword)\n @context(provider: \"vtex.logistics-carrier-graphql\") {\n items {\n id\n name\n }\n paging {\n page\n pages\n }\n }\n}\n\n```" } ]
code_custom-stock-export_05c58283
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/graphql/warehousesNames.graphql from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery warehousesNames($ids: [ID!]!) {\n warehousesList(ids: $ids)\n @context(provider: \"vtex.logistics-carrier-graphql\") {\n name\n }\n}\n\n```" } ]
code_custom-stock-export_01b0710a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/graphql/categories.gql from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery categories($searchKey: String!, $page: Int!, $pageSize: Int!) {\n categories(term: $searchKey, page: $page, pageSize: $pageSize, active: true) {\n items {\n id\n name\n }\n paging {\n page\n perPage\n pages\n total\n }\n }\n}\n\n```" } ]
code_custom-stock-export_523dd3ec
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/hooks/useQuantityFilters.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo, useCallback } from 'react'\nimport { useIntl } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport type {\n InventoryProductsPageFilterInput,\n QuantityFilterInput,\n} from 'vtex.inventory-graphql'\n\nimport QuantityFilterPopup from '../components/Filters/QuantityFilterPopup'\nimport type {\n Statement,\n StatementProps,\n Verb,\n FilterQuery,\n} from './useProductFilters'\nimport { filtersMessages as messages, columnsMessages } from '../utils/intl'\n\nexport type QuantityFilters = Pick<\n InventoryProductsPageFilterInput,\n 'quantity' | 'reservedQuantity' | 'availableQuantity'\n>\n\nexport type QuantitySubject = keyof QuantityFilters\n\nexport function useQuantityFilters(initialState?: QuantityFilters) {\n const { query } = useRuntime()\n const intl = useIntl()\n\n const getFromQuery = (queryValue?: string, initialValue?: number | null) =>\n queryValue != null && !Number.isNaN(+queryValue)\n ? +queryValue\n : initialValue\n\n const filter: QuantityFilters = {\n quantity: {\n min: getFromQuery(query?.minQuantity, initialState?.quantity?.min),\n max: getFromQuery(query?.maxQuantity, initialState?.quantity?.max),\n },\n reservedQuantity: {\n min: getFromQuery(\n query?.minReservedQuantity,\n initialState?.reservedQuantity?.min\n ),\n max: getFromQuery(\n query?.maxReservedQuantity,\n initialState?.reservedQuantity?.max\n ),\n },\n availableQuantity: {\n min: getFromQuery(\n query?.minAvailableQuantity,\n initialState?.availableQuantity?.min\n ),\n max: getFromQuery(\n query?.maxAvailableQuantity,\n initialState?.availableQuantity?.max\n ),\n },\n }\n\n const createQuantityFilterOption = useCallback(\n ({\n label,\n labelGender = 'male',\n }: {\n label: string\n labelGender?: string\n }) => {\n const dropdownOptions: Array<[Verb, string]> = [\n ['greaterOrEqual', intl.formatMessage(messages.greaterOrEqualDropdown)],\n ['lessOrEqual', intl.formatMessage(messages.lessOrEqualDropdown)],\n ['between', intl.formatMessage(messages.betweenDropdown)],\n ]\n\n return {\n label,\n renderFilterLabel: (\n statement?: Statement<QuantitySubject, QuantityFilterInput>\n ) => {\n if (statement?.verb === 'greaterOrEqual') {\n return intl.formatMessage(messages.greaterOrEqualLabel, {\n value: statement?.object?.min,\n })\n }\n\n if (statement?.verb === 'lessOrEqual') {\n return intl.formatMessage(messages.lessOrEqualLabel, {\n value: statement?.object?.max,\n })\n }\n\n if (statement?.verb === 'between') {\n return intl.formatMessage(messages.betweenLabel, {\n min: statement?.object?.min,\n max: statement?.object?.max,\n })\n }\n\n return intl.formatMessage(messages.all, {\n gender: labelGender,\n })\n },\n verbs: dropdownOptions.map(([option, title]) => ({\n label: title,\n value: option,\n object: (props: StatementProps<QuantityFilterInput>) => (\n <QuantityFilterPopup {...props} verb={option} />\n ),\n })),\n }\n },\n [intl]\n )\n\n const options = useMemo(\n () => ({\n quantity: createQuantityFilterOption({\n label: intl.formatMessage(columnsMessages.lastUpdate),\n labelGender: 'female',\n }),\n reservedQuantity: createQuantityFilterOption({\n label: intl.formatMessage(columnsMessages.reserved),\n }),\n availableQuantity: createQuantityFilterOption({\n label: intl.formatMessage(columnsMessages.available),\n }),\n }),\n [intl, createQuantityFilterOption]\n )\n\n const statements: Array<Statement<QuantitySubject, QuantityFilterInput>> = (\n Object.entries(filter) as Array<[QuantitySubject, QuantityFilterInput]>\n )\n .filter(([_, value]) => value?.min != null || value?.max != null)\n .map(([key, value]) => ({\n subject: key,\n verb:\n value?.min != null\n ? value?.max != null\n ? 'between'\n : 'greaterOrEqual'\n : 'lessOrEqual',\n error: null,\n object: value,\n }))\n\n function handleChange(\n statement: Statement<QuantitySubject, QuantityFilterInput>\n ) {\n // Can't pass null to setQuery because it will still put the property in\n // the url, but with an empty value\n const minQuery =\n (statement.verb === 'greaterOrEqual' || statement.verb === 'between') &&\n statement?.object?.min != null\n ? statement.object.min\n : undefined\n\n const maxQuery =\n (statement.verb === 'lessOrEqual' || statement.verb === 'between') &&\n statement?.object?.max != null\n ? statement.object.max\n : undefined\n\n const newQuery: Partial<FilterQuery> = {}\n\n if (statement.subject === 'quantity') {\n newQuery.minQuantity = minQuery\n newQuery.maxQuantity = maxQuery\n } else if (statement.subject === 'reservedQuantity') {\n newQuery.minReservedQuantity = minQuery\n newQuery.maxReservedQuantity = maxQuery\n } else if (statement.subject === 'availableQuantity') {\n newQuery.minAvailableQuantity = minQuery\n newQuery.maxAvailableQuantity = maxQuery\n }\n\n return newQuery\n }\n\n return {\n filter,\n statements,\n handleChange,\n options,\n }\n}\n\n```" } ]
code_custom-stock-export_d9c2fe80
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/hooks/useArrowNavigation.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable vtex/prefer-early-return */\nimport { useState, useEffect } from 'react'\n\nexport default function useArrowNavigation(\n ref: React.RefObject<HTMLElement> | null,\n optionsLength: number,\n initialSelectedOptionIndex: number\n): [number, (index: number) => void] {\n const [selectedOptionIndex, setSelectedOptionIndex] = useState(\n initialSelectedOptionIndex\n )\n\n const handleKeyDown = (e: KeyboardEvent) => {\n if (\n ref?.current &&\n e.target instanceof Node &&\n ref.current.contains(e.target)\n ) {\n let index\n\n switch (e.key) {\n case 'ArrowUp':\n e.preventDefault()\n index = Math.max(selectedOptionIndex - 1, initialSelectedOptionIndex)\n\n return setSelectedOptionIndex(index)\n\n case 'ArrowDown':\n e.preventDefault()\n index = Math.min(selectedOptionIndex + 1, optionsLength - 1)\n\n return setSelectedOptionIndex(index)\n\n default:\n }\n }\n }\n\n useEffect(() => {\n document.addEventListener('keydown', handleKeyDown)\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown)\n }\n })\n\n return [selectedOptionIndex, setSelectedOptionIndex]\n}\n\n```" } ]
code_custom-stock-export_ecbab75b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/hooks/useWarehouseFilter.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo, useState } from 'react'\nimport { useIntl } from 'react-intl'\nimport { useQuery } from 'react-apollo'\nimport { useRuntime } from 'vtex.render-runtime'\nimport type { InventoryProductsPageFilterInput } from 'vtex.inventory-graphql'\nimport type { QueryWarehousesListArgs } from 'vtex.logistics-carrier-graphql'\n\nimport WarehouseFilterPopup from '../components/Filters/WarehouseFilterPopup'\nimport type { Statement, StatementProps, Verb } from './useProductFilters'\nimport type { QueriedWarehouse, QueriedWarehousesNames } from '../types'\nimport {\n commonMessages,\n filtersMessages as messages,\n columnsMessages,\n} from '../utils/intl'\nimport WAREHOUSES_NAMES from '../graphql/warehousesNames.graphql'\n\nexport type WarehouseFilter = Pick<\n InventoryProductsPageFilterInput,\n 'warehouseIds'\n>\n\nexport type WarehouseSubject = keyof WarehouseFilter\n\nexport type WarehousesMap = Map<\n QueriedWarehouse['id'],\n QueriedWarehouse['name']\n>\n\nexport function useWarehouseFilter(initialState?: WarehouseFilter) {\n const { query } = useRuntime()\n const intl = useIntl()\n\n const filter: WarehouseFilter = {\n warehouseIds: query?.warehouseIds?.split(',') ?? initialState?.warehouseIds,\n }\n\n const [checked, setChecked] = useState<WarehousesMap>(new Map())\n // When loading url, we don't have warehouses names yet\n const [checkedWithoutName, setCheckedWithoutName] = useState(\n filter.warehouseIds ?? []\n )\n\n const { loading, error, refetch } = useQuery<\n { warehousesList: QueriedWarehousesNames },\n QueryWarehousesListArgs\n >(WAREHOUSES_NAMES, {\n notifyOnNetworkStatusChange: true,\n variables: {\n ids: checkedWithoutName,\n },\n skip: checkedWithoutName.length === 0,\n onCompleted: (data) =>\n setChecked((prevChecked) => {\n const newChecked = new Map(prevChecked)\n\n data?.warehousesList?.forEach((value, index) => {\n newChecked.set(checkedWithoutName[index], value.name)\n })\n\n return newChecked\n }),\n })\n\n const urlError =\n checkedWithoutName.length > 0 && error\n ? {\n message: intl.formatMessage(messages.warehousesNamesQueryError),\n refetch,\n dismiss: () => setCheckedWithoutName([]),\n }\n : null\n\n const options = useMemo(\n () => ({\n warehouseIds: {\n label: intl.formatMessage(columnsMessages.warehouse),\n renderFilterLabel: (\n statement?: Statement<WarehouseSubject, WarehousesMap>\n ) => {\n if (loading) return intl.formatMessage(commonMessages.loading)\n if (!statement?.object || statement.object.size === 0) {\n return intl.formatMessage(messages.all, { gender: 'male' })\n }\n\n return Array.from(statement.object.values()).join(', ')\n },\n verbs: [\n {\n label: '',\n value: 'includes' as Verb,\n object: (props: StatementProps<WarehousesMap>) => (\n <WarehouseFilterPopup {...props} />\n ),\n },\n ],\n },\n }),\n [intl, loading]\n )\n\n const statements: Array<Statement<WarehouseSubject, WarehousesMap>> = (\n Object.entries(filter) as Array<[WarehouseSubject, string[]]>\n )\n .filter(([_, value]) => Boolean(value?.length))\n .map(([key]) => ({\n subject: key,\n verb: 'includes',\n error: null,\n object: checked,\n }))\n\n function handleChange(statement: Statement<WarehouseSubject, WarehousesMap>) {\n setChecked(statement?.object ?? new Map())\n\n return {\n warehouseIds: statement?.object?.size\n ? Array.from(statement.object.keys()).join(',')\n : undefined,\n }\n }\n\n return {\n filter,\n statements,\n handleChange,\n options,\n urlError,\n }\n}\n\n```" } ]
code_custom-stock-export_e2dbd186
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/hooks/useClickOutside.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useEffect } from 'react'\n\nexport default function useClickOutside(\n ref: React.RefObject<HTMLElement> | null,\n onClickOutside: (e: Event) => void\n) {\n const handleClickOutside = (e: Event) => {\n if (\n ref?.current &&\n e.target instanceof Node &&\n !ref.current.contains(e.target)\n ) {\n onClickOutside(e)\n }\n }\n\n useEffect(() => {\n document.addEventListener('mousedown', handleClickOutside)\n\n return () => {\n document.removeEventListener('mousedown', handleClickOutside)\n }\n })\n}\n\n```" } ]
code_custom-stock-export_0abc7c27
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/hooks/useExponentialBackoff.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useState, useEffect, useCallback, useRef } from 'react'\nimport type { ApolloError } from 'apollo-client'\nimport type Maybe from 'graphql/tsutils/Maybe'\n\nconst INITIAL_DELAY = 200\nconst MAX_DELAY = 5_000\nconst COEFFICIENT = 2\n\nexport function useExponentialBackoff({\n queryLoading,\n queryError,\n refetch,\n}: {\n queryLoading: boolean\n queryError: Maybe<ApolloError>\n refetch: () => void\n}) {\n const [loading, setLoading] = useState(queryLoading)\n const [error, setError] = useState<Maybe<ApolloError>>(queryError)\n const [retryCount, setRetryCount] = useState(0)\n const [waitingTimeout, setWaitingTimeout] = useState(false)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const timerId: any = useRef(0)\n\n const stopBackoff = useCallback(() => {\n setLoading(false)\n setError(null)\n setRetryCount(0)\n clearTimeout(timerId.current)\n setWaitingTimeout(false)\n }, [setLoading, setError, setRetryCount, timerId])\n\n useEffect(() => {\n if (loading && !queryLoading) {\n if (!queryError) {\n stopBackoff()\n } else if (!waitingTimeout) {\n setError(queryError)\n setWaitingTimeout(true)\n timerId.current = setTimeout(() => {\n setWaitingTimeout(false)\n refetch()\n setRetryCount((prevRetryCount) => prevRetryCount + 1)\n }, Math.min(MAX_DELAY, INITIAL_DELAY * COEFFICIENT ** retryCount))\n }\n } else if (!loading && queryLoading) {\n setLoading(true)\n }\n\n // Effect should only be called when query state changes. Tried\n // doing it with useQuery's onCompleted and onError but there were\n // too many edge cases.\n }, [queryLoading])\n\n return { loading, error, stopBackoff }\n}\n\n```" } ]
code_custom-stock-export_25910868
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/hooks/useProductFilters.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useIntl } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport type { QuantityFilterInput } from 'vtex.inventory-graphql'\nimport type { usePagination } from 'vtex.logistics-carrier-commons'\nimport { useAmplitude } from 'vtex.logistics-carrier-commons'\nimport { useEffect } from 'react'\n\nimport type { QuantityFilters, QuantitySubject } from './useQuantityFilters'\nimport { useQuantityFilters } from './useQuantityFilters'\nimport type {\n WarehouseFilter,\n WarehouseSubject,\n WarehousesMap,\n} from './useWarehouseFilter'\nimport { useWarehouseFilter } from './useWarehouseFilter'\nimport { filtersMessages as messages } from '../utils/intl'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type DefaultFunctionType = (...args: any[]) => any\n\nexport type HandleVariablesChangeFunction<\n T extends DefaultFunctionType = DefaultFunctionType\n> = (\n onVariablesChange: T,\n onCancelChange?: () => void\n) => (...args: Parameters<T>) => ReturnType<T> | void\n\nexport interface FilterQuery {\n minQuantity: QuantityFilterInput['min']\n maxQuantity: QuantityFilterInput['max']\n minReservedQuantity: QuantityFilterInput['min']\n maxReservedQuantity: QuantityFilterInput['max']\n minAvailableQuantity: QuantityFilterInput['min']\n maxAvailableQuantity: QuantityFilterInput['max']\n warehouseIds?: string\n}\n\nexport type Verb = 'lessOrEqual' | 'greaterOrEqual' | 'between' | 'includes'\n\nexport interface Statement<S, T> {\n label?: string\n error?: unknown\n verb: Verb | null\n subject?: S\n object?: T\n}\n\nexport interface StatementProps<T> {\n value: T | null\n error: unknown\n onChange: (newValue: T | null) => void\n}\n\ntype FilterStatements = Array<\n | Statement<QuantitySubject, QuantityFilterInput>\n | Statement<WarehouseSubject, WarehousesMap>\n>\n\nfunction useFilterUsageEvents() {\n const { query = {} } = useRuntime()\n const { logEvent } = useAmplitude()\n\n useEffect(() => {\n if (query.minQuantity != null || query.maxQuantity != null) {\n logEvent('Inventory Filtered', {\n 'Filter Type': 'Last Update',\n })\n }\n }, [logEvent, query.maxQuantity, query.minQuantity])\n\n useEffect(() => {\n if (\n query.minReservedQuantity != null ||\n query.maxReservedQuantity != null\n ) {\n logEvent('Inventory Filtered', {\n 'Filter Type': 'Reserved',\n })\n }\n }, [logEvent, query.minReservedQuantity, query.maxReservedQuantity])\n\n useEffect(() => {\n if (\n query.minAvailableQuantity != null ||\n query.maxAvailableQuantity != null\n ) {\n logEvent('Inventory Filtered', {\n 'Filter Type': 'Available',\n })\n }\n }, [logEvent, query.minAvailableQuantity, query.maxAvailableQuantity])\n\n useEffect(() => {\n if (query.warehouseIds != null) {\n logEvent('Inventory Filtered', {\n 'Filter Type': 'Warehouse',\n })\n }\n }, [logEvent, query.warehouseIds])\n}\n\ninterface ProductFiltersHookParameters {\n resetPaginationVariables: ReturnType<\n typeof usePagination\n >['resetPaginationVariables']\n onStatementsChange?: HandleVariablesChangeFunction<\n (statements: FilterStatements) => void\n >\n initialState?: QuantityFilters & WarehouseFilter\n}\n\nexport function useProductFilters({\n resetPaginationVariables,\n onStatementsChange,\n initialState,\n}: ProductFiltersHookParameters) {\n const { setQuery } = useRuntime()\n\n const intl = useIntl()\n\n const quantityFilters = useQuantityFilters(initialState)\n const warehouseFilter = useWarehouseFilter(initialState)\n\n function handleStatementsChange(statements: FilterStatements = []) {\n const newQuery: FilterQuery = {\n minQuantity: undefined,\n maxQuantity: undefined,\n minReservedQuantity: undefined,\n maxReservedQuantity: undefined,\n minAvailableQuantity: undefined,\n maxAvailableQuantity: undefined,\n warehouseIds: undefined,\n }\n\n for (const statement of statements) {\n if (\n statement.subject === 'quantity' ||\n statement.subject === 'reservedQuantity' ||\n statement.subject === 'availableQuantity'\n ) {\n Object.assign(newQuery, quantityFilters.handleChange(statement))\n } else if (statement.subject === 'warehouseIds') {\n Object.assign(newQuery, warehouseFilter.handleChange(statement))\n }\n }\n\n setQuery({ ...newQuery, ...resetPaginationVariables })\n }\n\n const filter = { ...warehouseFilter.filter, ...quantityFilters.filter }\n\n const props = {\n submitFilterLabel: intl.formatMessage(messages.ok),\n alwaysVisibleFilters: Object.keys(filter),\n statements: [...warehouseFilter.statements, ...quantityFilters.statements],\n onChangeStatements: onStatementsChange\n ? onStatementsChange(handleStatementsChange)\n : handleStatementsChange,\n options: { ...warehouseFilter.options, ...quantityFilters.options },\n }\n\n useFilterUsageEvents()\n\n return { props, filter, urlError: warehouseFilter.urlError }\n}\n\n```" } ]
code_custom-stock-export_32861de7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/index.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport React, { useState } from 'react'\nimport { pathOr } from 'ramda'\nimport {\n Input,\n /* Checkbox, */ FilterBar,\n ButtonWithIcon,\n} from 'vtex.styleguide'\nimport Download from '@vtex/styleguide/lib/icon/Download'\nimport type { ApolloError } from 'apollo-client'\nimport { useIntl } from 'react-intl'\n\nimport { useQuantityFilters } from '../../hooks/useQuantityFilters'\nimport { useWarehouseFilter } from '../../hooks/useWarehouseFilter'\nimport { filtersMessages, appMessages } from '../../utils/intl'\nimport CategorySelect from './CategorySelect'\n\nexport default function Filters() {\n const [statements, setStatements] = useState([])\n const intl = useIntl()\n\n const clear = intl.formatMessage(filtersMessages.clear)\n const all = intl.formatMessage(filtersMessages.all)\n const any = intl.formatMessage(filtersMessages.any)\n const is = intl.formatMessage(filtersMessages.is)\n const isNot = intl.formatMessage(filtersMessages.isNot)\n const contains = intl.formatMessage(filtersMessages.contains)\n const apply = intl.formatMessage(filtersMessages.apply)\n const exportIcon = <Download />\n\n const quantityFilters = useQuantityFilters()\n const warehouseFilter = useWarehouseFilter()\n\n function simpleInputVerbs() {\n return [\n {\n label: is,\n value: '=',\n object: (props: any) => <SimpleInputObject {...props} />,\n },\n {\n label: isNot,\n value: '!=',\n object: (props: any) => <SimpleInputObject {...props} />,\n },\n {\n label: contains,\n value: 'contains',\n object: (props: any) => <SimpleInputObject {...props} />,\n },\n ]\n }\n\n const onclickExport = () => {\n console.info('onclickExport')\n console.info('statements', statements)\n }\n\n const filter = { ...warehouseFilter.filter, ...quantityFilters.filter }\n\n return (\n <div>\n <FilterBar\n alwaysVisibleFilters={[\n 'categoryId',\n 'productId',\n 'productName',\n ...Object.keys(filter),\n ]}\n statements={statements}\n onChangeStatements={(s: any) => setStatements(s)}\n clearAllFiltersButtonLabel={clear}\n submitFilterLabel={apply}\n options={{\n categoryId: {\n label: 'Category',\n renderFilterLabel: pathOr(all, ['object', 'label']),\n verbs: [\n {\n label: '',\n value: is,\n object: function VerbObject({\n onChange,\n value,\n ...props\n }: StatementObjectProps<Statement | null>) {\n return (\n <CategorySelect\n {...props}\n onClear={() => {\n value = null\n onChange(null)\n }}\n value={value}\n onSelect={onChange}\n focused\n />\n )\n },\n },\n ],\n },\n productId: {\n label: 'Product ID',\n renderFilterLabel: (st: any) => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return any\n }\n\n return `${\n st.verb === '=' ? is : st.verb === '!=' ? isNot : contains\n } ${st.object}`\n },\n verbs: simpleInputVerbs(),\n },\n productName: {\n label: 'Product Name',\n renderFilterLabel: (st: any) => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return any\n }\n\n return `${\n st.verb === '=' ? is : st.verb === '!=' ? isNot : contains\n } ${st.object}`\n },\n verbs: simpleInputVerbs(),\n },\n ...warehouseFilter.options,\n ...quantityFilters.options,\n }}\n />\n <ButtonWithIcon icon={exportIcon} onClick={onclickExport}>\n {`${intl.formatMessage(appMessages.exportButton)}`}\n </ButtonWithIcon>\n </div>\n )\n}\n\nfunction SimpleInputObject({ value, onChange }: any) {\n return (\n <Input\n value={value || ''}\n onChange={(e: any) => onChange(e.target.value)}\n />\n )\n}\n\n// function StatusSelectorObject({ value, onChange }: any) {\n// const initialValue = {\n// 'Window to cancelation': true,\n// Canceling: true,\n// Canceled: true,\n// 'Payment pending': true,\n// 'Payment approved': true,\n// 'Ready for handling': true,\n// 'Handling shipping': true,\n// 'Ready for invoice': true,\n// Invoiced: true,\n// Complete: true,\n// ...(value || {}),\n// }\n\n// const toggleValueByKey = (key: any) => {\n// return {\n// ...(value || initialValue),\n// [key]: value ? !value[key] : false,\n// }\n// }\n\n// return (\n// <div>\n// {Object.keys(initialValue).map((opt, index) => {\n// return (\n// <div className=\"mb3\" key={`class-statment-object-${opt}-${index}`}>\n// <Checkbox\n// checked={value ? value[opt] : initialValue[opt]}\n// id={`status-${opt}`}\n// label={opt}\n// name=\"status-checkbox-group\"\n// onChange={() => {\n// const newValue = toggleValueByKey(`${opt}`)\n\n// onChange(newValue)\n// }}\n// value={opt}\n// />\n// </div>\n// )\n// })}\n// </div>\n// )\n// }\n\ninterface StatementObjectProps<T, U = SelectOption | null> {\n value: T\n onChange: (value: U) => void\n error?: ApolloError\n keepValueInput?: boolean\n}\n\n```" } ]
code_custom-stock-export_0265e867
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/FilterSelect/index.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classNames from 'classnames'\nimport React, { useState, useRef, useEffect } from 'react'\nimport { useIntl, defineMessages } from 'react-intl'\n\nimport useClickOutside from '../../../hooks/useClickOutside'\nimport useArrowNavigation from '../../../hooks/useArrowNavigation'\nimport type { Props as OptionProps } from './Option'\nimport Option from './Option'\nimport SelectInput from './SelectInput'\nimport styles from './styles.css'\nimport { filtersMessages } from '../../../utils/intl'\n\nconst messages = defineMessages({\n noOptionsFound: filtersMessages.noOptionsFound,\n})\n\ninterface InputProps\n extends Omit<React.HTMLProps<HTMLInputElement>, 'onChange' | 'value'> {\n onClear: () => void\n onChange: (term: string) => void\n value: string\n loading: boolean\n}\n\ninterface OptionsProps {\n renderOption?: (props: OptionProps, index: number) => React.ReactNode\n value: SelectOption[]\n icon?: React.ReactElement\n onSelect: (option: SelectOption) => void\n onPopoverOpened?: (popover: HTMLDivElement | null) => void\n onPopoverClosed?: () => void\n keepValueInput?: boolean\n}\n\nexport interface Props {\n input: InputProps\n options: OptionsProps\n testId?: string\n}\n\ntype OptionRef = HTMLElement | null\n\nconst NO_SELECTED_OPTION_INDEX = 0\n\nconst FilterSelect: React.FC<Props> = ({\n input: { value, onClear, onChange, loading, ref, ...inputProps },\n options: {\n onSelect,\n value: options,\n renderOption,\n icon,\n onPopoverOpened,\n onPopoverClosed,\n keepValueInput,\n },\n testId,\n}) => {\n const [term, setTerm] = useState(value || '')\n const [showPopover, setShowPopover] = useState(false)\n const containerRef = useRef<HTMLDivElement>(null)\n const inputRef = useRef<HTMLInputElement | null>(null)\n const popoverRef = useRef<HTMLDivElement>(null)\n const optionsRefs = useRef<OptionRef[]>([])\n const { formatMessage } = useIntl()\n\n const handleClear = () => {\n setShowPopover(false)\n setTerm('')\n onClear()\n }\n\n useEffect(() => {\n if (!keepValueInput && term) {\n handleClear()\n setShowPopover(true)\n }\n }, [])\n\n const [selectedOptionIndex, setSelectedOptionIndex] = useArrowNavigation(\n containerRef,\n options.length,\n NO_SELECTED_OPTION_INDEX\n )\n\n useClickOutside(containerRef, () => setShowPopover(false))\n\n const popoverOpened = showPopover\n\n useEffect(() => {\n if (popoverOpened && onPopoverOpened) {\n onPopoverOpened(popoverRef.current)\n } else if (!popoverOpened && onPopoverClosed) {\n onPopoverClosed()\n }\n }, [popoverOpened])\n\n useEffect(() => {\n const optionRef = optionsRefs.current[selectedOptionIndex]\n\n if (optionRef) {\n optionRef.focus()\n if (inputRef.current) {\n inputRef.current.focus()\n }\n }\n }, [selectedOptionIndex])\n\n const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (e.key !== 'Enter') {\n return\n }\n\n const selectedOption = options[selectedOptionIndex]\n\n setTerm(selectedOption.label)\n onSelect(selectedOption)\n setSelectedOptionIndex(NO_SELECTED_OPTION_INDEX)\n setShowPopover(false)\n }\n\n const handleTermChange = (newTerm = '') => {\n if (!showPopover) {\n setShowPopover(true)\n }\n\n setTerm(newTerm)\n if (onChange) {\n onChange(newTerm)\n }\n }\n\n const handleOptionClick = (option: SelectOption) => {\n setTerm(option.label)\n onSelect(option)\n setShowPopover(false)\n }\n\n const getOptionProps = (option: SelectOption, index: number) => ({\n key: `${option.label}-${option.value}-${index}`,\n selected: index === selectedOptionIndex,\n value: option,\n searchTerm: term,\n roundedBottom: index === options.length - 1,\n icon: typeof option !== 'string' && icon ? icon : null,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n ref: (ref: HTMLElement | null) => {\n optionsRefs.current[index] = ref\n },\n onFocus: () => {\n setSelectedOptionIndex(index)\n },\n onMouseEnter: () => {\n setSelectedOptionIndex(index)\n },\n onClick: () => {\n handleOptionClick(option)\n },\n })\n\n const renderOptions = (): React.ReactElement | React.ReactElement[] => (\n <div className=\"flex flex-column\">\n {options.length > 0\n ? options.map(\n renderOption\n ? (option, index) =>\n renderOption(getOptionProps(option, index), index)\n : (option, index) => <Option {...getOptionProps(option, index)} />\n )\n : !inputProps.disabled && (\n <Option\n key=\"disabled-option\"\n searchTerm={term}\n roundedBottom\n selected={false}\n testId=\"filter-no-results-option\"\n disabled\n value={{\n value: '',\n label: formatMessage(messages.noOptionsFound),\n }}\n />\n )}\n </div>\n )\n\n const popoverClasses = classNames(\n styles.popover,\n 'absolute w-100 overflow-y-auto z-1',\n {\n 'br br2 ba b--muted-3 bg-base shadow-5': popoverOpened,\n }\n )\n\n return (\n <div ref={containerRef} className=\"flex flex-column w-100\">\n <SelectInput\n testId={testId}\n {...inputProps}\n ref={(node) => {\n inputRef.current = node\n if (typeof ref === 'function') {\n ref(node)\n } else if (ref) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n ref.current = node\n }\n }}\n value={term}\n onKeyDown={handleKeyDown}\n onFocus={() => setShowPopover(true)}\n onClear={handleClear}\n onChange={handleTermChange}\n loading={loading}\n />\n <div className=\"relative\">\n <div ref={popoverRef} className={popoverClasses}>\n {popoverOpened ? renderOptions() : null}\n </div>\n </div>\n </div>\n )\n}\n\nexport default FilterSelect\n\n```" } ]
code_custom-stock-export_0eba2348
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/FilterSelect/styles.css from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.popover {\n max-height: 14rem;\n}\n\n.border-medium {\n border-width: medium;\n}\n\n.select-input:hover {\n border-color: hsl(0, 0%, 70%);\n}\n\n```" } ]
code_custom-stock-export_3d87d94a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/FilterSelect/Option.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classnames from 'classnames'\nimport { omit } from 'ramda'\nimport type { ForwardRefExoticComponent, PropsWithoutRef } from 'react'\nimport React, { forwardRef } from 'react'\n\nexport type Props = {\n roundedBottom?: boolean\n icon?: React.ReactNode\n searchTerm: string\n value: SelectOption\n selected: boolean\n key: string\n disabled?: boolean\n testId?: string\n} & Omit<Partial<React.HTMLProps<HTMLButtonElement | HTMLDivElement>>, 'value'>\n\nconst Option: ForwardRefExoticComponent<PropsWithoutRef<Props>> = forwardRef<\n HTMLButtonElement,\n Props\n>((props, ref) => {\n const {\n icon,\n selected,\n roundedBottom,\n searchTerm,\n disabled,\n testId,\n ...buttonProps\n } = props\n\n const value = props.value.label\n\n const renderOptionValue = (): string | React.ReactElement => {\n const index = value.toLowerCase().indexOf(searchTerm.toLowerCase())\n\n if (index === -1 || !searchTerm.length) {\n return value\n }\n\n const prefix = value.substring(0, index)\n const match = value.substr(index, searchTerm.length)\n const suffix = value.substring(index + match.length)\n\n return (\n <span className=\"truncate\">\n <span className=\"fw7\">{prefix}</span>\n {match}\n <span className=\"fw7\">{suffix}</span>\n </span>\n )\n }\n\n const buttonClasses = classnames('bn w-100 tl pa4 f6', {\n 'br2 br--bottom': roundedBottom,\n 'bg-muted-5': selected,\n 'c-disabled': disabled,\n 'bg-base': !selected,\n pointer: !disabled,\n })\n\n return (\n <button\n {...omit(['value', 'key', 'type'], buttonProps)}\n ref={ref}\n type=\"button\"\n disabled={disabled}\n className={buttonClasses}\n data-testid={testId}\n >\n <span className=\"h1 flex items-center\">\n <span className=\"mr3 c-muted-2 flex pt1\">{icon}</span>\n {disabled ? (\n <span className=\"truncate\">{value}</span>\n ) : (\n renderOptionValue()\n )}\n </span>\n </button>\n )\n})\n\nexport default Option\n\n```" } ]
code_custom-stock-export_9ef38180
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/CategorySelect/index.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { ApolloError } from 'apollo-client'\n\nimport withQuery from '../InfiniteSelect/withQuery'\nimport Select from './Select'\nimport categoriesQuery from '../../../graphql/categories.gql'\n\ntype Props = Omit<\n StatementObjectProps<Statement | null>,\n 'onChange' | 'error'\n> & {\n focused?: boolean\n testId?: string\n onClear?: () => void\n onSelect: (option: SelectOption) => void\n keepValueInput?: boolean\n}\n\nexport default withQuery<Props>(Select)({\n query: categoriesQuery,\n resultName: 'categories',\n})\n\nexport interface StatementObjectProps<T, U = SelectOption | null> {\n value: T\n onChange: (value: U) => void\n error?: ApolloError\n keepValueInput?: boolean\n}\n\n```" } ]
code_custom-stock-export_64ec5caa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/CategorySelect/Select.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React from 'react'\n\nimport { filtersMessages } from '../../../utils/intl'\nimport type { Props as InfiniteSelectProps } from '../InfiniteSelect'\nimport InfiniteSelect from '../InfiniteSelect'\n\nconst messages = {\n loading: filtersMessages.loading,\n placeholder: filtersMessages.placeholder,\n error: filtersMessages.error,\n}\n\nconst Select: FC<Omit<InfiniteSelectProps, 'messages' | 'intl'>> = (props) => (\n <InfiniteSelect {...props} messages={messages} />\n)\n\nexport default Select\n\n```" } ]
code_custom-stock-export_54a872fb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/CustomInputSearch/index.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC, ChangeEvent } from 'react'\nimport React, { useState } from 'react'\nimport { IconClear, IconSearch } from 'vtex.styleguide'\nimport classNames from 'classnames'\n\nimport styles from './styles.css'\n\nconst ICON_SIZE = 14\n\ninterface Props {\n value: string\n placeholder: string\n onChange: (event: ChangeEvent<HTMLInputElement>) => void\n onClear: () => void\n onSubmit: () => void\n}\n\nconst CustomInputSearch: FC<Props> = (props) => {\n const [focused, setFocused] = useState(false)\n\n return (\n <div\n className={classNames('w-100 h-small flex items-center bb bw1', {\n 'b--muted-2': focused,\n 'b--muted-4 hover-b--muted-3': !focused,\n })}\n >\n <span className=\"flex flex-none c-muted-2 mr3\">\n <IconSearch size={ICON_SIZE} />\n </span>\n <input\n className={`bn outline-0 c-on-base bg-base w-100 ${styles.input} ${styles.hideDecorators} ${styles.noAppearance}`}\n value={props.value}\n placeholder={props.placeholder}\n onChange={props.onChange}\n onKeyUp={(e) => e.key === 'Enter' && props.onSubmit()}\n onFocus={() => setFocused(true)}\n onBlur={() => setFocused(false)}\n type=\"search\"\n />\n {props.value && (\n <button\n onClick={props.onClear}\n className=\"flex flex-none mr3 pointer c-muted-3 br4 pa0 bn outline-transparent bg-base\"\n >\n <IconClear size={ICON_SIZE} />\n </button>\n )}\n </div>\n )\n}\n\nexport default CustomInputSearch\n\n```" } ]
code_custom-stock-export_1975b0e3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/CustomInputSearch/styles.css from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n/* removes edge clear button on input */\n.hideDecorators::-ms-clear {\n display: none;\n}\n\n.noAppearance {\n appearance: none;\n}\n\n/* placeholders are using c-muted-1's value */\n.input::-webkit-input-placeholder {\n /* Chrome/Opera/Safari */\n color: #979899;\n}\n.input::-moz-placeholder {\n /* Firefox 19+ */\n color: #979899;\n}\n.input:-ms-input-placeholder {\n /* IE 10+ */\n color: #979899;\n}\n.input:-moz-placeholder {\n /* Firefox 18- */\n color: #979899;\n}\n\n```" } ]
code_custom-stock-export_f2a37fce
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/WarehouseFilterPopup/index.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useState, useRef, useEffect, useCallback } from 'react'\nimport { useQuery } from 'react-apollo'\nimport { useIntl, FormattedMessage } from 'react-intl'\nimport { Checkbox, Spinner, IconWarning } from 'vtex.styleguide'\nimport { useDebouncedSearch } from 'vtex.logistics-carrier-commons'\nimport type { QueryWarehousesArgs } from 'vtex.logistics-carrier-graphql'\nimport classNames from 'classnames'\nimport type { ApolloError } from 'apollo-client'\n\nimport type { StatementProps } from '../../../hooks/useProductFilters'\nimport type { QueriedWarehouse, QueriedWarehousesPage } from '../../../types'\nimport type { WarehousesMap } from '../../../hooks/useWarehouseFilter'\nimport { useExponentialBackoff } from '../../../hooks/useExponentialBackoff'\nimport { filtersMessages as messages } from '../../../utils/intl'\nimport styles from './styles.css'\nimport CustomInputSearch from '../CustomInputSearch'\nimport WAREHOUSES from '../../../graphql/warehouses.graphql'\n\ntype Props = StatementProps<WarehousesMap>\n\nconst INITIAL_PAGE = 1\nconst PER_PAGE = 7\nconst SPINNER_SIZE = 24\n\nconst WarehouseFilterPopup: FC<Props> = ({ value: checked, onChange }) => {\n const intl = useIntl()\n const containerRef = useRef<HTMLDivElement>(null)\n const [showTopBorder, setShowTopBorder] = useState(false)\n\n const [keyword, setKeyword] = useState('')\n const { term, handleSearchChange, handleSearchClear, handleSearchSubmit } =\n useDebouncedSearch({\n term: keyword,\n onChange: ({ keyword: k }) => setKeyword(k),\n })\n\n const {\n loading: firstQueryLoading,\n error: firstQueryError,\n data,\n refetch,\n fetchMore: queryFetchMore,\n } = useQuery<{ warehouses: QueriedWarehousesPage }, QueryWarehousesArgs>(\n WAREHOUSES,\n {\n notifyOnNetworkStatusChange: true,\n variables: {\n page: INITIAL_PAGE,\n perPage: PER_PAGE,\n keyword,\n },\n }\n )\n\n const [fetchingMore, setFetchingMore] = useState<{\n loading: boolean\n error: ApolloError | null\n }>({ loading: false, error: null })\n\n const fetchMore = useCallback(() => {\n setFetchingMore({ loading: true, error: null })\n queryFetchMore({\n variables: {\n page: data?.warehouses?.paging\n ? data.warehouses.paging.page + 1\n : INITIAL_PAGE,\n },\n updateQuery: (prev, { fetchMoreResult }) => {\n if (!fetchMoreResult) {\n return prev\n }\n\n return {\n warehouses: {\n ...fetchMoreResult.warehouses,\n items: [\n ...prev.warehouses.items,\n ...fetchMoreResult.warehouses.items,\n ],\n },\n }\n },\n })\n .catch((error) => setFetchingMore({ loading: false, error }))\n .finally(() =>\n setFetchingMore((prevFetchingMore) => ({\n loading: false,\n error: prevFetchingMore.error,\n }))\n )\n }, [setFetchingMore, queryFetchMore, data])\n\n const {\n loading: queryLoading,\n error,\n stopBackoff,\n } = useExponentialBackoff({\n queryLoading: firstQueryLoading || fetchingMore.loading,\n queryError: firstQueryError ?? fetchingMore.error,\n refetch: () => {\n if (firstQueryError) {\n refetch()\n } else if (fetchingMore.error) {\n fetchMore()\n }\n },\n })\n\n // Need this to keep previously checked warehouses at the top,\n // and recently checked ones where they are\n const [checkedOnTop, setCheckedOnTop] = useState(checked)\n\n useEffect(() => {\n setCheckedOnTop(checked)\n stopBackoff()\n setFetchingMore({ loading: false, error: null })\n }, [term])\n\n const searchLoading =\n term !== keyword ||\n ((firstQueryLoading || firstQueryError) &&\n !fetchingMore.loading &&\n !fetchingMore.error)\n\n const loading = searchLoading ?? queryLoading\n\n const hasMorePages =\n searchLoading ||\n (data?.warehouses?.paging &&\n data.warehouses.paging.page < data.warehouses.paging.pages)\n\n const checkboxRenderer = (warehouse: QueriedWarehouse) => (\n <div className=\"h2 mw5 nl6 ph6 nr2 flex items-center\" key={warehouse.id}>\n <Checkbox\n checked={checked?.has(warehouse.id)}\n id={warehouse.id}\n onChange={() => {\n const newValue = new Map(checked ?? [])\n\n if (checked?.has(warehouse.id)) {\n newValue.delete(warehouse.id)\n } else {\n newValue.set(warehouse.id, warehouse.name)\n }\n\n onChange(newValue)\n }}\n />\n <label htmlFor={warehouse.id} className=\"w-100\">\n <div className=\"pl3 truncate pointer\">{warehouse.name}</div>\n </label>\n </div>\n )\n\n const handleScroll = () => {\n const reachedLoadingPoint =\n containerRef?.current &&\n containerRef.current.scrollTop + containerRef.current.clientHeight >\n containerRef.current.scrollHeight - SPINNER_SIZE\n\n if (containerRef?.current?.scrollTop && !showTopBorder) {\n setShowTopBorder(true)\n } else if (!containerRef?.current?.scrollTop && showTopBorder) {\n setShowTopBorder(false)\n }\n\n if (!loading && hasMorePages && reachedLoadingPoint) {\n fetchMore()\n }\n }\n\n return (\n <>\n <CustomInputSearch\n value={term}\n onChange={handleSearchChange}\n onClear={() => {\n containerRef.current?.scrollTo({ top: 0 })\n handleSearchClear()\n }}\n placeholder={intl.formatMessage(messages.search)}\n onSubmit={handleSearchSubmit}\n />\n <div\n className={classNames(\n 'overflow-y-auto overflow-x-hidden mt6 pb3 nh6 ph6 nb4 bb bw1 b--light-gray',\n styles.scrollShadow,\n { bt: showTopBorder }\n )}\n style={{ maxHeight: '14.25rem' }} // Height of 7 items + borders\n ref={containerRef}\n onScroll={handleScroll}\n >\n {checkedOnTop &&\n Array.from(checkedOnTop, ([id, name]) =>\n checkboxRenderer({ id, name })\n )}\n {!searchLoading &&\n data?.warehouses?.items\n ?.filter((warehouse) => !checkedOnTop?.has(warehouse.id))\n ?.map(checkboxRenderer)}\n {hasMorePages && (\n <div className=\"h2 flex items-center justify-center\">\n <Spinner size={SPINNER_SIZE} />\n </div>\n )}\n {/* Check for hasMorePages to avoid frame where data has loaded but\n error hasn't been updated so it would appear */}\n {hasMorePages && error && (\n <div className=\"flex mt3 pt5 pb3 nh6 ph6 bt b--light-gray bw1\">\n <span className=\"c-warning mr3\">\n <IconWarning />\n </span>\n <span className=\"lh-solid\">\n <FormattedMessage {...messages.warehousesQueryError} />\n </span>\n </div>\n )}\n </div>\n </>\n )\n}\n\nexport default WarehouseFilterPopup\n\n```" } ]
code_custom-stock-export_b0e1c9c2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/WarehouseFilterPopup/styles.css from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.scrollShadow {\n background: linear-gradient(\n rgba(255, 255, 255, 1),\n rgba(255, 255, 255, 0) 5%,\n rgba(255, 255, 255, 0) 95%,\n rgba(255, 255, 255, 1)\n ),\n linear-gradient(\n rgba(0, 0, 0, 0.05),\n rgba(0, 0, 0, 0) 2%,\n rgba(0, 0, 0, 0) 98%,\n rgba(0, 0, 0, 0.05)\n );\n background-attachment: local, scroll;\n}\n\n```" } ]
code_custom-stock-export_53227753
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/QuantityFilterPopup/index.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useState, useEffect } from 'react'\nimport { FormattedMessage, useIntl } from 'react-intl'\nimport { Input } from 'vtex.styleguide'\nimport type { QuantityFilterInput } from 'vtex.inventory-graphql'\n\nimport type { StatementProps, Verb } from '../../../hooks/useProductFilters'\nimport { filtersMessages as messages } from '../../../utils/intl'\nimport { isInteger, convertInteger } from '../../../utils/inputs'\n\ntype Props = StatementProps<QuantityFilterInput> & { verb: Verb }\n\nconst QuantityFilterPopup: FC<Props> = ({ verb, value, onChange }) => {\n const intl = useIntl()\n const showMinInput = verb === 'greaterOrEqual' || verb === 'between'\n const showMaxInput = verb === 'lessOrEqual' || verb === 'between'\n const [quantity, setQuantity] = useState(value)\n // In order to allow negative numbers\n const [minInputValue, setMinInputValue] = useState<string | null>(null)\n const [maxInputValue, setMaxInputValue] = useState<string | null>(null)\n const validQuantity =\n verb !== 'between'\n ? quantity?.min != null || quantity?.max != null\n : quantity?.min != null &&\n quantity?.max != null &&\n quantity.min <= quantity.max\n\n useEffect(() => {\n function updateStatement() {\n if (validQuantity) {\n onChange(quantity)\n } else {\n // Disable \"OK\" button\n onChange(null)\n }\n }\n\n updateStatement()\n // Should not update when `onChange` updates\n }, [quantity, validQuantity])\n\n useEffect(() => {\n function updateStatementByVerb() {\n if (verb === 'greaterOrEqual') {\n setMaxInputValue(null)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setQuantity((prevQuantity: any) =>\n prevQuantity?.min == null\n ? null\n : {\n min: prevQuantity?.min,\n max: null,\n }\n )\n } else if (verb === 'lessOrEqual') {\n setMinInputValue(null)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setQuantity((prevQuantity: any) =>\n prevQuantity?.max == null\n ? null\n : {\n min: null,\n max: prevQuantity?.max,\n }\n )\n }\n }\n\n updateStatementByVerb()\n }, [verb])\n\n function handleMinChange(event: React.ChangeEvent<HTMLInputElement>) {\n if (!isInteger(event.target.value)) {\n return\n }\n\n setMinInputValue(event.target.value)\n setQuantity({\n ...quantity,\n min: convertInteger(event.target.value),\n })\n }\n\n function handleMaxChange(event: React.ChangeEvent<HTMLInputElement>) {\n if (!isInteger(event.target.value)) {\n return\n }\n\n setMaxInputValue(event.target.value)\n setQuantity({\n ...quantity,\n max: convertInteger(event.target.value),\n })\n }\n\n return (\n <>\n {showMinInput && (\n <Input\n placeholder={intl.formatMessage(messages.minimumPlaceholder)}\n value={minInputValue ?? quantity?.min ?? ''}\n onChange={handleMinChange}\n />\n )}\n {showMinInput && showMaxInput && (\n <div className=\"mv3 ml5 pl1\">\n <FormattedMessage {...messages.and} />\n </div>\n )}\n {showMaxInput && (\n <Input\n placeholder={intl.formatMessage(messages.maximumPlaceholder)}\n value={maxInputValue ?? quantity?.max ?? ''}\n onChange={handleMaxChange}\n errorMessage={\n !validQuantity &&\n quantity?.min != null &&\n quantity?.max != null &&\n intl.formatMessage(messages.betweenInvalid)\n }\n />\n )}\n </>\n )\n}\n\nexport default QuantityFilterPopup\n\n```" } ]
code_custom-stock-export_9388ee23
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/InfiniteSelect/index.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable no-shadow */\n/* eslint-disable vtex/prefer-early-return */\nimport type { ApolloError } from 'apollo-client'\nimport debounce from 'lodash.debounce'\nimport { pathOr } from 'ramda'\nimport React, { useRef, useEffect, useState, useMemo, useCallback } from 'react'\nimport { useIntl } from 'react-intl'\n\nimport FilterSelect from '../FilterSelect'\nimport Option from '../FilterSelect/Option'\nimport type { QueryProps, SelectItem } from './withQuery'\nimport { usePolling, POLLING } from './hooks'\nimport type { Props as ErrorOptionProps } from './ErrorOption'\nimport ErrorOption from './ErrorOption'\nimport type { Pagination, PaginatedData } from '../../../utils/pagination'\n\nexport type Props<T = SelectItem> = QueryProps<T> & {\n focused?: boolean\n value: Statement | null\n onClear?: () => void\n keepValueInput?: boolean\n onSelect: (option: SelectOption) => void\n messages: { [key: string]: { id: string } }\n testId?: string\n}\n\ninterface Data<T> {\n [queryName: string]: undefined | PaginatedData<T>\n}\n\nconst DEBOUNCE = 500\n\nconst Select = <T extends SelectItem = SelectItem>({\n messages,\n loading: queryLoading,\n data,\n resultName,\n error: queryError,\n fetchMore,\n refetch,\n networkStatus,\n variables,\n pagination,\n setPagination,\n onClear,\n onSelect,\n focused,\n keepValueInput,\n testId,\n}: Props<T>) => {\n const { formatMessage } = useIntl()\n const [readyToFilter, setReadyToFilter] = useState(false)\n const [preventLoading, setPreventLoading] = useState(false)\n const [fetchMoreError, setFetchMoreError] = useState<ApolloError | undefined>(\n undefined\n )\n\n const observer = useRef<IntersectionObserver | null>(null)\n const loadingRef = useRef<HTMLSpanElement | null>(null)\n const popoverRef = useRef<HTMLDivElement | null>(null)\n const inputRef = useRef<HTMLInputElement | null>(null)\n const fetchingMore = useRef(false)\n\n const {\n reset,\n failed,\n status: pollingStatus,\n } = usePolling<Data<T>, Pagination>({\n loading: queryLoading,\n error: queryError ?? fetchMoreError,\n tryAgain: data?.[resultName] ? fetchMore : refetch,\n variables,\n networkStatus,\n pollingMs: POLLING.MS,\n pollingLimit: POLLING.LIMIT,\n })\n\n // Clear the fetchMoreError when it's done\n useEffect(() => {\n if (\n data?.[resultName] &&\n fetchMoreError &&\n !pollingStatus.error &&\n !pollingStatus.loading\n ) {\n setFetchMoreError(undefined)\n }\n }, [data, fetchMoreError, pollingStatus, resultName])\n\n const error = queryError ?? pollingStatus.error\n const loading = queryLoading || pollingStatus.loading || (error && !failed)\n\n const canFetchMore =\n pathOr(0, [resultName, 'paging', 'page'], data) <\n pathOr(0, [resultName, 'paging', 'pages'], data)\n\n const showLoading = loading ?? canFetchMore\n\n const options = pathOr<T[]>([], [resultName, 'items'], data)\n .map((item) => ({\n value: item.id,\n label: item.name,\n }))\n .concat(\n showLoading || error\n ? [\n {\n value: '',\n label: formatMessage(failed ? messages.error : messages.loading),\n },\n ]\n : []\n )\n\n const handleIntersection = useCallback(\n // eslint-disable-next-line @typescript-eslint/no-shadow\n ([entry]: IntersectionObserverEntry[], observer: IntersectionObserver) => {\n if (\n entry.isIntersecting &&\n options.length > 1 &&\n !loading &&\n !fetchingMore.current &&\n !fetchMoreError\n ) {\n observer.disconnect()\n fetchingMore.current = true\n fetchMore()\n .catch(setFetchMoreError)\n .finally(() => {\n fetchingMore.current = false\n })\n }\n },\n [fetchMore, fetchMoreError, loading, options.length]\n )\n\n const handleChange = useMemo(\n () =>\n debounce((searchKey: string) => {\n setPagination({ searchKey, page: 1 })\n }, DEBOUNCE),\n [setPagination]\n )\n\n const connectObserver = useCallback(\n (popover: HTMLDivElement | null) => {\n popoverRef.current = popover\n if (popover && loadingRef.current) {\n observer.current = new IntersectionObserver(handleIntersection, {\n root: popover,\n threshold: 0.3,\n })\n observer.current.observe(loadingRef.current)\n }\n },\n [handleIntersection]\n )\n\n const disconnectObserver = () => {\n if (observer.current) {\n observer.current.disconnect()\n }\n }\n\n useEffect(() => {\n if (!loading) {\n // Reset states\n setPreventLoading(false)\n setReadyToFilter(false)\n // Need this to correctly detect infinite scroll after filtering\n disconnectObserver()\n if (popoverRef.current) {\n connectObserver(popoverRef.current)\n }\n }\n }, [loading, popoverRef, loadingRef, connectObserver])\n\n useEffect(() => {\n if (inputRef.current && focused) {\n inputRef.current.focus()\n }\n }, [focused])\n\n return (\n <FilterSelect\n testId={testId}\n input={{\n ref: inputRef,\n value: pagination.searchKey,\n onClear: () => {\n setPagination({ searchKey: '' })\n if (onClear) {\n onClear()\n }\n },\n onChange: (term: string) => {\n setReadyToFilter(term !== pagination.searchKey)\n handleChange(term)\n },\n loading: !preventLoading && (loading || readyToFilter),\n placeholder: formatMessage(messages.placeholder),\n }}\n options={{\n value: options,\n onSelect: (option: SelectOption) => {\n setPreventLoading(true)\n setPagination({ searchKey: option.label })\n onSelect(option)\n },\n onPopoverOpened: connectObserver,\n onPopoverClosed: () => {\n disconnectObserver()\n popoverRef.current = null\n },\n keepValueInput,\n renderOption: function Renderer(props, index) {\n if (index !== options.length - 1 || (!showLoading && !error)) {\n return <Option {...props} />\n }\n\n if (showLoading && !failed) {\n return (\n <div key={props.key} className=\"pa4\">\n <span ref={loadingRef} className=\"i c-muted-3 f6 ml3\">\n {props.value.label}\n </span>\n </div>\n )\n }\n\n return (\n <ErrorOption\n {...(props as ErrorOptionProps)}\n onClick={() => {\n reset()\n if (inputRef.current) {\n inputRef.current.focus()\n }\n }}\n filterInput={inputRef.current}\n />\n )\n },\n }}\n />\n )\n}\n\nexport default Select\n\n```" } ]
code_custom-stock-export_3d57998e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/InfiniteSelect/withQuery.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { ApolloQueryResult, ApolloError } from 'apollo-client'\nimport type { DocumentNode } from 'graphql'\nimport { pathOr } from 'ramda'\nimport type { ComponentType } from 'react'\nimport React, { useRef, useEffect } from 'react'\nimport type { QueryResult } from 'react-apollo'\nimport { Query } from 'react-apollo'\n\nimport type {\n Pagination,\n PaginatedData,\n SetPagination,\n} from '../../../utils/pagination'\nimport { usePagination } from '../../../utils/pagination'\n\nexport interface StatementObjectProps<T, U = SelectOption | null> {\n value: T\n onChange: (value: U) => void\n error?: ApolloError\n keepValueInput?: boolean\n}\n\nexport interface SelectItem {\n id: string\n name: string\n}\n\ninterface Data<T> {\n [key: string]: PaginatedData<T>\n}\n\ntype Variables = Pagination\n\nexport type QueryProps<T> = Omit<\n QueryResult<Data<T>, Variables>,\n 'fetchMore'\n> & {\n resultName: string\n pagination: Pagination\n setPagination: SetPagination\n fetchMore: () => Promise<ApolloQueryResult<Data<T>>>\n}\n\ntype ComponentProps<T> = T & Partial<StatementObjectProps<Statement | null>>\n\ninterface Props {\n query: DocumentNode\n resultName: string\n}\n\nconst withQuery =\n <T, QData = SelectItem>(\n WrappedComponent: ComponentType<T & QueryProps<QData>>\n ) =>\n ({ query, resultName }: Props) =>\n (props: ComponentProps<T>) => {\n const [pagination, setPagination] = usePagination({\n page: 1,\n pageSize: 15,\n searchKey: pathOr('', ['value', 'label'], props),\n })\n\n return (\n <Query<Data<QData>, Variables>\n query={query}\n variables={pagination}\n notifyOnNetworkStatusChange\n >\n {({ fetchMore, variables, ...data }) => {\n // Apparently this workaround is needed :/\n const variablesRef = useRef(variables)\n\n useEffect(() => {\n variablesRef.current = pagination\n }, [])\n\n const handleFetchMore = () =>\n fetchMore({\n variables: {\n ...variablesRef.current,\n page: variablesRef.current.page + 1,\n },\n updateQuery: (\n prev,\n { fetchMoreResult, variables: newVariables }\n ) => {\n const getItems = pathOr<QData[]>([], [resultName, 'items'])\n\n variablesRef.current = newVariables ?? variablesRef.current\n\n return (\n prev && {\n ...prev,\n [resultName]: {\n ...prev[resultName],\n items: getItems(prev).concat(getItems(fetchMoreResult)),\n ...(fetchMoreResult?.resultName?.paging && {\n paging: fetchMoreResult.resultName.paging,\n }),\n },\n }\n )\n },\n })\n\n return (\n <WrappedComponent\n {...props}\n {...data}\n resultName={resultName}\n variables={variables}\n fetchMore={handleFetchMore}\n pagination={pagination}\n setPagination={setPagination}\n />\n )\n }}\n </Query>\n )\n }\n\nexport default withQuery\n\n```" } ]
code_custom-stock-export_d21c88aa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/InfiniteSelect/ErrorOption.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable vtex/prefer-early-return */\nimport classnames from 'classnames'\nimport type { ForwardRefExoticComponent } from 'react'\nimport React, { useEffect, useRef, forwardRef } from 'react'\nimport { defineMessages, FormattedMessage } from 'react-intl'\nimport { IconWarning, Button } from 'vtex.styleguide'\n\nimport { filtersMessages } from '../../../utils/intl'\n\nexport type Props = {\n filterInput: HTMLInputElement | null\n roundedBottom?: boolean\n icon?: React.ReactNode\n searchTerm: string\n value: SelectOption\n selected: boolean\n key: string\n} & Pick<React.HTMLProps<HTMLButtonElement>, 'onClick'>\n\nexport interface SelectOption {\n value: string\n label: string\n}\n\nconst messages = defineMessages({\n tryAgain: filtersMessages.tryAgain,\n})\n\nconst ErrorOption: ForwardRefExoticComponent<Props> = forwardRef<\n HTMLDivElement,\n Props\n>((props, ref) => {\n const { roundedBottom, value: optionValue, onClick, filterInput } = props\n const value = optionValue.label\n\n const buttonRef = useRef<HTMLButtonElement | null>(null)\n\n const containerClasses = classnames('w-100 tl pa4 f6 bt b--muted-4 bg-base', {\n 'br2 br--bottom': roundedBottom,\n })\n\n useEffect(() => {\n if (buttonRef.current) {\n buttonRef.current.focus()\n if (filterInput) {\n filterInput.focus()\n }\n }\n }, [filterInput])\n\n return (\n <div ref={ref} className={containerClasses}>\n <div className=\"ph2 pt2\">\n <span className=\"flex t-mini c-muted-1 pb3\">\n <span className=\"mr3 flex c-warning\">\n <IconWarning />\n </span>\n <span className=\"w-100\">{value}</span>\n </span>\n <Button\n ref={buttonRef}\n onClick={onClick}\n size=\"small\"\n variation=\"tertiary\"\n block\n >\n <FormattedMessage {...messages.tryAgain} />\n </Button>\n </div>\n </div>\n )\n})\n\nexport default ErrorOption\n\n```" } ]
code_custom-stock-export_e1da7d6a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/InfiniteSelect/hooks.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable no-shadow */\nimport type { ApolloQueryResult } from 'apollo-client'\nimport { useEffect, useState, useRef } from 'react'\nimport type { QueryResult } from 'react-apollo'\n\ntype UsePolling<TData, TVariables> = Pick<\n QueryResult<TData, TVariables>,\n 'loading' | 'error' | 'variables' | 'networkStatus'\n> & {\n pollingLimit: number\n pollingMs: number\n tryAgain: (variables?: TVariables) => Promise<ApolloQueryResult<TData>>\n}\n\nexport const APOLLO_STATUS = {\n LOADING: 1,\n REFETCHING: 4,\n POLLING: 5,\n}\n\nexport const POLLING = {\n LIMIT: 5,\n MS: 200,\n}\n\nexport const usePolling = <TData, TVariables>({\n loading: queryLoading,\n error: queryError,\n networkStatus,\n variables,\n tryAgain,\n pollingLimit,\n}: UsePolling<TData, TVariables>) => {\n const [error, setError] = useState(queryError)\n const [loading, setLoading] = useState(queryLoading)\n const [attempts, setAttempts] = useState(1)\n const refetchPromise = useRef<Promise<ApolloQueryResult<TData>> | null>(null)\n\n const status = {\n loading,\n error,\n }\n\n const refetch = () => {\n if (!refetchPromise.current) {\n setLoading(true)\n refetchPromise.current = tryAgain(variables)\n .then((result) => {\n setError(undefined)\n setAttempts(1)\n\n return result\n })\n // eslint-disable-next-line @typescript-eslint/no-shadow\n .catch((error) => {\n setError(error)\n setAttempts(attempts + 1)\n\n return error\n })\n .finally(() => {\n refetchPromise.current = null\n setLoading(false)\n })\n }\n\n return refetchPromise.current\n }\n\n useEffect(() => {\n if (!loading) {\n if (error) {\n if (attempts < pollingLimit) {\n refetch()\n }\n } else if (attempts > 1) {\n setAttempts(1)\n }\n }\n }, [loading, error, attempts])\n\n useEffect(() => {\n setLoading(networkStatus < 7)\n }, [networkStatus])\n\n useEffect(() => {\n setError(queryError)\n }, [queryError])\n\n return {\n reset: () => {\n setAttempts(1)\n },\n failed: attempts >= pollingLimit,\n status,\n }\n}\n\n```" } ]
code_custom-stock-export_c1bc52b8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export/react/components/Filters/FilterSelect/SelectInput/index.tsx from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classNames from 'classnames'\nimport React, { forwardRef, useRef, useState } from 'react'\nimport { IconClear, IconCaretDown, Spinner } from 'vtex.styleguide'\n\nimport styles from '../styles.css'\n\ntype Props = {\n value: string\n loading: boolean\n onClear: () => void\n onChange: (term: string) => void\n testId?: string\n} & Omit<React.HTMLProps<HTMLInputElement>, 'onChange' | 'value'>\n\nconst SearchInput = forwardRef<HTMLInputElement, Props>((props, ref) => {\n const {\n onClear,\n value,\n onChange,\n onFocus,\n onBlur,\n disabled,\n loading,\n testId,\n ...inputProps\n } = props\n\n const [focused, setFocused] = useState(false)\n const inputRef = useRef<HTMLInputElement | null>(null)\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n onChange?.(e.target.value)\n }\n\n const handleClear = () => {\n onClear?.()\n }\n\n const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {\n setFocused(true)\n onFocus?.(e)\n }\n\n const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {\n setFocused(false)\n onBlur?.(e)\n }\n\n const handleCaretClick = () => {\n if (inputRef.current) {\n inputRef.current.focus()\n }\n }\n\n const inputClasses = classNames(\n `w-100 ma0 border-box bw1 br2 ba outline-0 t-body h-regular ph5 pr8 t-small`,\n {\n 'bg-disabled b--disabled c-disabled': disabled,\n 'bg-base c-on-base': !disabled,\n [`b--blue ${styles['border-medium']}`]: focused,\n 'b--muted-3': !disabled && !focused,\n [styles['select-input']]: !disabled && !focused,\n }\n )\n\n const iconClasses = classNames('flex items-center', {\n 'bg-transparent b--disabled c-disabled': disabled,\n 'c-link': !disabled,\n })\n\n return (\n <div className=\"flex flex-row\">\n <div data-testid={testId} className=\"relative w-100\">\n <input\n ref={(node) => {\n inputRef.current = node\n if (typeof ref === 'function') {\n ref(node)\n } else if (ref) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n ref.current = node\n }\n }}\n className={inputClasses}\n value={value}\n onFocus={handleFocus}\n onBlur={handleBlur}\n onChange={handleChange}\n disabled={disabled}\n {...inputProps}\n />\n <span\n className=\"absolute fw5 flex items-center ph4 t-body top-0 right-0 h-100 pointer\"\n onClick={handleCaretClick}\n role=\"presentation\"\n >\n {onClear && value && (\n <span\n className=\"c-muted-3 mr3 flex items-center\"\n onClick={handleClear}\n role=\"button\"\n tabIndex={0}\n >\n <IconClear />\n </span>\n )}\n <span className={iconClasses}>\n {loading ? <Spinner size={14} /> : <IconCaretDown size={9} />}\n </span>\n </span>\n </div>\n </div>\n )\n})\n\nexport default SearchInput\n\n```" } ]
code_custom-stock-export_28cc5a86
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/docs/README.md from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# MASSIVE STOCK UPDATE\n\nThis application exposes an endpoint of massive stock update\n\n---\n\n```shell\nPUT https://{{workspace}}--{{accountName}}.myvtex.com/_v/massive/stock/update\n\n```\n\n## Curl\n\n```shell\ncurl --location --request PUT 'https://{{workspace}}--{{accountName}}.myvtex.com/_v/massive/stock/update' \\\n--header 'VtexIdClientAutCookie: \"\" \\\n--header 'Content-Type: application/json' \\\n--data-raw '[\n {\n \"sku\": 1,\n \"warehouseId\": 1,\n \"quantity\": 1,\n \"unlimitedQuantity\": false,\n \"dateUtcOnBalanceSystem\": null\n }\n]'\n```\n\n## Specification\n\n### Headers\n\n- Required\n - Accept : application/json\n - Content-Type : application/json; charset=utf-8\n - VtexIdclientAutCookie : `eyJhbGciOi...`\n\n### Path params\n\n- Required\n - sku [int32]\n - warehouseId [int32] || [string]\n - quantity [int32]\n - unlimitedQuantity [boolean]\n - dateUtcOnBalanceSystem [string]\n\n> Read the API information for more information [link](https://developers.vtex.com/vtex-rest-api/reference/inventory#updateinventorybyskuandwarehouse)\n\n### Request body example\n\n```json\n[\n {\n \"sku\": 1,\n \"warehouseId\": 123,\n \"quantity\": 50,\n \"unlimitedQuantity\": false,\n \"dateUtcOnBalanceSystem\": null\n }\n]\n```\n\n### Success Response body example\n\n```json\n{\n \"successfulResponses\": {\n \"elements\": [\n {\n \"sku\": 1,\n \"success\": true,\n \"warehouseId\": 123,\n \"quantity\": 50,\n \"unlimitedQuantity\": false,\n \"dateUtcOnBalanceSystem\": null\n }\n ],\n \"quantity\": 1\n },\n \"failedResponses\": {\n \"elements\": [],\n \"quantity\": 0\n },\n \"total\": 1\n}\n```\n\n### Error Response body example\n\n```json\n{\n \"failedResponses\": {\n \"elements\": [\n [\n {\n \"sku\": 159076,\n \"quantity\": 12,\n \"dateUtcOnBalanceSystem\": null,\n \"success\": \"false\",\n \"error\": 400,\n \"errorMessage\": \"The request is invalid: The 'warehouseId' field is required.\"\n }\n ]\n ],\n \"quantity\": 1\n }\n}\n```\n\n---\n\n## Credentials\n\n### Create appKey y appToken\n\nTo generate app keys in your account, you should follow the instructions seen in the [Application Keys](https://help.vtex.com/en/tutorial/application-keys--2iffYzlvvz4BDMr6WGUtet) article in our Help Center.\n\n### Create role\n\n[Create a role](https://help.vtex.com/en/tutorial/perfiles-de-acceso--7HKK5Uau2H6wxE1rH5oRbc) with the following resources and add your user to that role\n\n- Logistics / Logistics access / Logistics full access\n\n### Convert to JWT\n\nMake a call with the credentials created. The result, if the credentials are valid, will return a token that will be used as the value in the header 'VtexIdclientAutCookie' requested by the massive-stock-update component.\n\n```shell\n>>>>>>> 91953ff0fc5154ad45335f9f2a8dbc6141fadf81\ncurl --location --request POST 'http://vtexid.vtexcommercestable.com.br/api/vtexid/apptoken/login' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n \"appkey\": \"...\",\n \"apptoken\": \"...\"\n}'\n```\n\n## Flow\n\n![Massive stock update flow](https://user-images.githubusercontent.com/33711188/132750831-38272a4d-5abb-446b-ac1b-574969cb8561.png)\n\n## Contributors\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n <tr>\n <td align=\"center\"><a href=\"https://github.com/GuidoSdo\"><img src=\"https://avatars.githubusercontent.com/u/33711188?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Guido Salcedo</b></sub></a><br /><a href=\"https://github.com/vtex-apps/massive-stock-update\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n\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 welcome!\n\n```" } ]
code_custom-stock-export_4c41073e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/node/service.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 600,\n \"minReplicas\": 10,\n \"maxReplicas\": 20,\n \"workers\": 1,\n \"routes\": {\n \"status\": {\n \"path\": \"/_v/massive/stock/update\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_custom-stock-export_13d74481
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/node/utils.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\nimport type { AxiosError } from 'axios'\n\nexport const BUCKET_NAME = 'product-translation'\nexport const ALL_TRANSLATIONS_FILES = 'all-translations'\n\nexport const statusToError = (e: AxiosError) => {\n if (!e.response) {\n throw e\n }\n\n const {\n response: { status },\n } = e\n\n switch (status) {\n case 401: {\n throw new AuthenticationError(e)\n }\n\n case 403: {\n throw new ForbiddenError(e)\n }\n\n case 400: {\n throw new UserInputError(e)\n }\n\n default:\n throw new TypeError(e.message)\n }\n}\n\n```" } ]
code_custom-stock-export_340ae8c8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/node/package.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"license\": \"MIT\",\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"ramda\": \"^0.25.0\",\n \"graphql\": \"^14.5.8\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.6\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"typescript\": \"3.9.7\",\n \"vtex.catalog-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.catalog-graphql@1.96.0/public/@types/vtex.catalog-graphql\",\n \"@types/graphql\": \"^14.5.0\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\"\n },\n \"version\": \"3.0.0\"\n}\n\n```" } ]
code_custom-stock-export_15a3b435
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/node/index.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ClientsConfig, ServiceContext, RecorderState } from '@vtex/api'\nimport { LRUCache, method, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { inventoryMiddleware } from './middlewares/inventoryMiddleware'\nimport { validateMiddleware } from './middlewares/validateMiddleware'\n\nconst TIMEOUT_MS = 600000\n\n// Create a LRU memory cache for the Status client.\n// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.\nconst memoryCache = new LRUCache<string, any>({ max: 5000 })\n\nmetrics.trackCache('status', memoryCache)\n\n// This is the configuration for clients available in `ctx.clients`.\nconst clients: ClientsConfig<Clients> = {\n // We pass our custom implementation of the clients bag, containing the Status client.\n implementation: Clients,\n options: {\n // All IO Clients will be initialized with these options, unless otherwise specified.\n default: {\n // retries: 2,\n timeout: TIMEOUT_MS,\n },\n // This key will be merged with the default options and add this cache to our Status client.\n status: {\n memoryCache,\n },\n },\n}\n\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\n type Context = ServiceContext<Clients, State>\n\n // The shape of our State object found in `ctx.state`. This is used as state bag to communicate between middlewares.\n interface State extends RecorderState {\n validatedBody: UpdateRequest[]\n }\n\n interface UpdateRequest {\n sku: number\n warehouseId?: number | string\n quantity?: number\n unlimitedQuantity?: boolean\n dateUtcOnBalanceSystem?: string\n }\n\n interface UpdateResponse {\n sku: number\n warehouseId?: number | string\n success: string\n error?: number | string\n errorMessage?: string\n quantity?: number\n unlimitedQuantity?: boolean\n dateUtcOnBalanceSystem?: string\n }\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service({\n clients,\n routes: {\n // `status` is the route ID from service.json. It maps to an array of middlewares (or a single handler).\n status: method({\n PUT: [validateMiddleware, inventoryMiddleware],\n }),\n },\n})\n\n```" } ]
code_custom-stock-export_053aeb40
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/public/metadata/messages/es-AR.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Massive Stock Update\",\n \"headline\": \"Actualice el stock mediante lotes.\",\n \"overview\": \"Actualice el stock por lotes para reducir los tiempos de integración y los gastos generales de las solicitudes.\",\n \"features\": [\n \"Servicio de actualización masiva de inventario a través de SKU y warehouseId.\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_custom-stock-export_9f87b2f5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/public/metadata/messages/pt-BR.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Massive Stock Update\",\n \"headline\": \"Atualize o estoque por massas.\",\n \"overview\": \"Atualize o estoque em massa para diminuir os tempos de integração e a sobrecarga de solicitações.\",\n \"features\": [\n \"Serviço de atualização de estoque em massa via SKU e warehouseId.\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_custom-stock-export_b8a02983
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/public/metadata/messages/en-US.json from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Massive Stock Update\",\n \"headline\": \"Update the stock by batches.\",\n \"overview\": \"Update stock in batches to decrease integration times and requests overhead.\",\n \"features\": [\n \"Massive inventory stock update service through SKU and warehouseId.\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_custom-stock-export_881e21ed
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/node/clients/inventoryRestClient.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { JanusClient } from '@vtex/api'\nimport type { InstanceOptions, IOContext, IOResponse } from '@vtex/api'\n\nimport type { UpdateinventoryBySkuAndWarehouseRequest } from '../middlewares/inventoryMiddleware'\n\nexport default class InventoryRestClient extends JanusClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n VtexIdclientAutCookie: context.authToken,\n 'Content-Type': 'application/json; charset=utf-8',\n Accept: 'application/json',\n 'X-Vtex-Use-Https': 'true',\n },\n })\n }\n\n // eslint-disable-next-line max-params\n public async updateInventory(\n authToken: string,\n body: UpdateinventoryBySkuAndWarehouseRequest,\n skuId?: number | string,\n warehouseId?: number | string\n ): Promise<IOResponse<string>> {\n return this.http.putRaw(\n `http://${this.context.account}.vtexcommercestable.com.br/api/logistics/pvt/inventory/skus/${skuId}/warehouses/${warehouseId}`,\n body,\n {\n headers: {\n VtexIdclientAutCookie: authToken,\n },\n }\n )\n }\n}\n\n```" } ]
code_custom-stock-export_5d9d23f8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/node/clients/index.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport InventoryRestClient from './inventoryRestClient'\n\nexport class Clients extends IOClients {\n public get inventoryRestClient() {\n return this.getOrSet('inventoryRestClient', InventoryRestClient)\n }\n}\n\n```" } ]
code_custom-stock-export_3c6f659c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/node/middlewares/inventoryMiddleware.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport async function inventoryMiddleware(\n ctx: Context,\n next: () => Promise<any>\n) {\n const {\n clients: { inventoryRestClient },\n state: { validatedBody },\n } = ctx\n\n const responseList: UpdateResponse[] = []\n\n try {\n const expected = await operationRetry(\n await Promise.all(\n validatedBody.map(async (item) => {\n return updateInventory(item)\n })\n )\n )\n\n if (expected) {\n const successfulResponses: UpdateResponse[] = responseList.filter((e) => {\n return e.success !== 'false'\n })\n\n const failedResponses: UpdateResponse[] = responseList.filter((e) => {\n return e.success === 'false'\n })\n\n ctx.status = 200\n ctx.body = {\n successfulResponses: {\n elements: successfulResponses,\n quantity: successfulResponses.length,\n },\n failedResponses: {\n elements: failedResponses,\n quantity: failedResponses.length,\n },\n total: responseList.length,\n }\n\n await next()\n }\n } catch (error) {\n ctx.status = 500\n ctx.body = error\n await next()\n }\n\n async function updateInventory(\n updateRequest: UpdateRequest\n ): Promise<UpdateResponse> {\n const {\n sku,\n warehouseId,\n quantity,\n unlimitedQuantity,\n dateUtcOnBalanceSystem,\n } = updateRequest\n\n const body: UpdateinventoryBySkuAndWarehouseRequest = {\n quantity,\n dateUtcOnBalanceSystem,\n unlimitedQuantity,\n }\n\n try {\n const vtexIdToken = ctx.get('VtexIdclientAutCookie') ?? ''\n\n const updateInventoryRestClientResponse = await inventoryRestClient.updateInventory(\n vtexIdToken,\n body,\n sku,\n warehouseId\n )\n\n const inventoryMiddlewareResponse: UpdateResponse = {\n sku: updateRequest.sku,\n success: updateInventoryRestClientResponse.data,\n warehouseId: updateRequest.warehouseId,\n quantity: updateRequest.quantity,\n unlimitedQuantity: updateRequest.unlimitedQuantity,\n dateUtcOnBalanceSystem: updateRequest.dateUtcOnBalanceSystem,\n }\n\n return inventoryMiddlewareResponse\n } catch (error) {\n const data = error.response ? error.response.data : ''\n const updateInventoryRestClientErrorResponse = {\n sku: updateRequest.sku,\n success: 'false',\n warehouseId: updateRequest.warehouseId,\n quantity: updateRequest.quantity,\n unlimitedQuantity: updateRequest.unlimitedQuantity,\n dateUtcOnBalanceSystem: updateRequest.dateUtcOnBalanceSystem,\n error: error.response ? error.response.status : 500,\n errorMessage: data.error ? data.error.message : data,\n }\n\n if (error.response && error.response.status === 429) {\n updateInventoryRestClientErrorResponse.errorMessage = error.response\n ? error.response.headers['ratelimit-reset']\n : '0'\n }\n\n return updateInventoryRestClientErrorResponse\n }\n }\n\n async function operationRetry(\n updateResponseList: UpdateResponse[]\n ): Promise<any> {\n addResponsesSuccessfulUpdates(updateResponseList)\n\n const response = await findStoppedRequests(updateResponseList)\n\n return response\n }\n\n async function findStoppedRequests(\n // eslint-disable-next-line @typescript-eslint/no-shadow\n responseList: UpdateResponse[]\n ): Promise<any> {\n const retryList: UpdateRequest[] = []\n let value = '0'\n\n if (responseList.length >= 1) {\n for (const index in responseList) {\n const response = responseList[index]\n\n if (response.error && response.error === 429) {\n if (response.errorMessage && response.errorMessage > value) {\n value = response.errorMessage\n }\n\n if (value === '0') {\n value = '20'\n }\n\n retryList.push({\n sku: response.sku,\n warehouseId: response.warehouseId,\n quantity: response.quantity,\n unlimitedQuantity: response.unlimitedQuantity,\n dateUtcOnBalanceSystem: response.dateUtcOnBalanceSystem,\n })\n }\n }\n }\n\n if (retryList.length >= 1) {\n let retryOperation: UpdateResponse[] = []\n\n const awaitTimeout = (delay: string) =>\n new Promise((resolve) => setTimeout(resolve, parseFloat(delay) * 1000))\n\n await awaitTimeout(value)\n\n retryOperation = await Promise.all(\n retryList.map(async (item) => {\n return updateInventory(item)\n })\n )\n\n return operationRetry(retryOperation)\n }\n\n return true\n }\n\n function addResponsesSuccessfulUpdates(\n updateResponseList: UpdateResponse[]\n ): void {\n for (const index in updateResponseList) {\n const updateResponse = updateResponseList[index]\n\n if (updateResponse.error !== 429) {\n responseList.push(updateResponse)\n }\n }\n }\n}\n\nexport type UpdateinventoryBySkuAndWarehouseRequest = {\n unlimitedQuantity?: boolean\n dateUtcOnBalanceSystem?: string\n quantity?: number\n}\n\n```" } ]
code_custom-stock-export_2a0115db
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of custom-stock-export/custom-stock-export-back/node/middlewares/validateMiddleware.ts from the custom-stock-export VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\nimport { json } from 'co-body'\n\nexport async function validateMiddleware(\n ctx: Context,\n next: () => Promise<any>\n) {\n const vtexIdToken =\n ctx.cookies.get('VtexIdclientAutCookie') ?? ctx.get('VtexIdclientAutCookie')\n\n if (!vtexIdToken) {\n ctx.status = 401\n ctx.body = 'VtexIdclientAutCookie not found.'\n\n return\n }\n\n const requestList = await json(ctx.req)\n const errorList: any[] = []\n\n function requestValidator(request: UpdateRequest): void {\n const requestErrorList: UpdateResponse[] = []\n\n const {\n sku,\n warehouseId,\n quantity,\n unlimitedQuantity,\n dateUtcOnBalanceSystem,\n } = request\n\n if (!sku) {\n requestErrorList.push(errorResponseGenerator('sku'))\n }\n\n if (!warehouseId) {\n requestErrorList.push(errorResponseGenerator('warehouseId'))\n }\n\n if (!quantity) {\n requestErrorList.push(errorResponseGenerator('quantity'))\n }\n\n if (typeof unlimitedQuantity === 'undefined') {\n requestErrorList.push(errorResponseGenerator('unlimitedQuantity'))\n }\n\n if (typeof dateUtcOnBalanceSystem === 'undefined') {\n requestErrorList.push(errorResponseGenerator('dateUtcOnBalanceSystem'))\n }\n\n if (requestErrorList.length >= 1) {\n errorList.push(requestErrorList)\n }\n\n function errorResponseGenerator(field: string): UpdateResponse {\n return {\n sku,\n warehouseId,\n quantity,\n unlimitedQuantity,\n dateUtcOnBalanceSystem,\n success: 'false',\n error: 400,\n errorMessage: `The request is invalid: The '${field}' field is required.`,\n }\n }\n }\n\n try {\n for (const request of requestList) {\n requestValidator(request)\n }\n } catch (error) {\n throw new UserInputError(error)\n }\n\n if (errorList.length >= 1) {\n ctx.status = 400\n ctx.body = {\n failedResponses: {\n elements: errorList,\n quantity: errorList.length,\n },\n }\n\n return\n }\n\n ctx.state.validatedBody = requestList\n await next()\n}\n\n```" } ]
code_adserver-resolver_71e3f21b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/service.json from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 512,\n \"minReplicas\": 5,\n \"workers\": 10\n}\n\n```" } ]
code_adserver-resolver_0cbd4c6e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/package.json from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"adserver-resolver\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"jest\": {\n \"transform\": {\n \"^.+\\\\.tsx?$\": \"ts-jest\"\n },\n \"testMatch\": [\n \"**/__tests__/**/*.(spec|test).(js|ts)?(x)\",\n \"**/?(*.)+(spec|test).(js|ts)?(x)\"\n ],\n \"moduleFileExtensions\": [\n \"ts\",\n \"tsx\",\n \"js\"\n ]\n },\n \"dependencies\": {\n \"@vtex/clients\": \"^2.21.0\",\n \"graphql\": \"^14.5.8\",\n \"vtex.adserver-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.adserver-graphql@0.3.1/public\"\n },\n \"devDependencies\": {\n \"@types/jest\": \"^27.0.3\",\n \"@types/node\": \"^12.12.21\",\n \"@vtex/api\": \"6.48.0\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"jest\": \"^25.1.0\",\n \"ts-jest\": \"^25.2.1\",\n \"typescript\": \"3.9.7\"\n },\n \"resolutions\": {\n \"@types/express-serve-static-core\": \"4.17.28\"\n },\n \"version\": \"2.10.4\"\n}\n\n```" } ]
code_adserver-resolver_df02a87e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/index.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ParamsContext, RecorderState } from '@vtex/api'\nimport { Service } from '@vtex/api'\nimport schema from 'vtex.adserver-graphql/graphql'\n\nimport { Clients } from './clients'\nimport { resolvers } from './resolvers'\n\nconst THREE_SECONDS_MS = 3 * 1000\n\nexport default new Service<Clients, RecorderState, ParamsContext>({\n clients: {\n implementation: Clients,\n options: {\n default: {\n retries: 0,\n timeout: THREE_SECONDS_MS,\n },\n },\n },\n graphql: {\n resolvers,\n schema,\n },\n})\n\n```" } ]
code_adserver-resolver_60252f80
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/clients/AdServer.ts from the adserver-resolver 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\nimport type {\n AdServerRequest,\n AdServerResponse,\n AdServerSponsoredBannersRequest,\n AdServerSponsoredBannersResponse,\n} from '../typings/AdServer'\n\nclass AdServer extends ExternalClient {\n public static BASE_URL = 'https://ad-server.vtex.systems'\n\n public static ERROR_MESSAGES = {\n AD_NOT_FOUND: 'Ad not found',\n }\n\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(AdServer.BASE_URL, ctx, { ...options })\n }\n\n public getSponsoredProducts(\n body: AdServerRequest\n ): Promise<AdServerResponse> {\n if (process.env.VTEX_APP_LINK) {\n // eslint-disable-next-line no-console\n console.log(\n 'endpoint: /api/v1/sponsored-products',\n 'body: ',\n JSON.stringify({ ...body, accountName: this.context.account }, null, 2)\n )\n }\n\n body.searchParams.query = body.searchParams.query ?? ''\n\n return this.http.post('/api/v1/sponsored-products', {\n accountName: this.context.account,\n ...body,\n })\n }\n\n public getSponsoredBanners(\n body: AdServerSponsoredBannersRequest\n ): Promise<AdServerSponsoredBannersResponse> {\n if (process.env.VTEX_APP_LINK) {\n // eslint-disable-next-line no-console\n console.log(\n 'endpoint: /api/ads/v1/ads/banner/query',\n 'body: ',\n JSON.stringify({ ...body, accountName: this.context.account }, null, 2)\n )\n }\n\n return this.http.post('/api/ads/v1/ads/banner/query', {\n accountName: this.context.account,\n ...body,\n })\n }\n}\n\nexport default AdServer\n\n```" } ]
code_adserver-resolver_2a9ded31
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/clients/Checkout.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { JanusClient } from '@vtex/api'\n\nexport type RegionSeller = {\n id: string\n name: string\n}\n\nexport type Region = {\n id: string\n sellers: RegionSeller[]\n}\n\nclass Checkout extends JanusClient {\n public regions = (\n regionId: string,\n channel?: number | string\n ): Promise<Region[]> => {\n const url = `/api/checkout/pub/regions/${regionId}`\n\n return this.http.get(url, {\n params: {\n sc: channel,\n },\n })\n }\n}\n\nexport default Checkout\n\n```" } ]
code_adserver-resolver_a0176d54
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/clients/Newtail.ts from the adserver-resolver 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\nimport type { NewtailRequest, NewtailResponse } from '../typings/Newtail'\n\nclass Newtail extends ExternalClient {\n public static BASE_URL = 'https://newtail-media.newtail.com.br'\n\n public static ERROR_MESSAGES = {\n AD_NOT_FOUND: 'Ad not found',\n }\n\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(Newtail.BASE_URL, ctx, { ...options })\n }\n\n public async getSponsoredProducts(\n body: NewtailRequest,\n newtailPublisherId: string\n ): Promise<NewtailResponse> {\n const endpoint = `/v1/rma/${newtailPublisherId}`\n\n return this.http\n .post<NewtailResponse>(endpoint, {\n ...body,\n })\n .then((response) => {\n if (response.validations && response.validations.length > 0) {\n throw new Error('Newtail validation error')\n }\n\n return response\n })\n }\n}\n\nexport default Newtail\n\n```" } ]
code_adserver-resolver_a2508f7d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/clients/index.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport AdServer from './AdServer'\nimport Checkout from './Checkout'\nimport Newtail from './Newtail'\n\nexport class Clients extends IOClients {\n public get adServer() {\n return this.getOrSet('adServer', AdServer)\n }\n\n public get newtail() {\n return this.getOrSet('newtail', Newtail)\n }\n\n public get checkout() {\n return this.getOrSet('checkout', Checkout)\n }\n}\n\n```" } ]
code_adserver-resolver_e6340e03
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/typings/AdServer.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport type AdServerRequest = {\n accountName?: string\n count: number\n searchParams: AdServerSearchParams\n userId?: string\n placement?: string\n}\n\nexport type AdServerResponse = {\n adRequestId: string\n adResponseId: string\n sponsoredProducts: AdServerSponsoredProduct[]\n}\n\nexport type AdServerSearchParams = Pick<SearchParams, AdServerSearchParamsKeys>\n\ntype AdServerSearchParamsKeys = 'query' | 'selectedFacets'\n\ntype AdServerSponsoredProduct = {\n campaignId: string\n adId: string\n productId: string\n actionCost: number\n options?: Options\n}\n\ntype Options = {\n hideSponsoredBadge?: boolean\n}\n\nexport type AdServerSponsoredBannersRequest = {\n accountName?: string\n count: number\n adUnit: string\n channel?: string\n placement: string\n userId?: string\n}\n\nexport type AdServerSponsoredBannersResponse = {\n adResponseId: string\n banners: AdServerSponsoredBanner[]\n}\n\ntype AdServerSponsoredBanner = {\n imageUrl: string\n targetUrl: string\n bannerImageId: string\n width: number\n height: number\n}\n\n```" } ]
code_adserver-resolver_05605add
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/typings/Newtail.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport type NewtailRequest = {\n term?: string\n context?: 'search' | 'home' | 'category' | 'brand_page' | 'product_page',\n category_name?: string,\n placements?: { [key: string]: NewtailPlacement }\n user_id?: string\n session_id?: string\n tags?: string[]\n product_sku?: string\n brand_name?: string\n}\n\nexport type NewtailPlacement = {\n quantity: number\n types: string[]\n}\n\nexport interface NewtailResponse {\n query_at: string\n query_id: string\n request_id: string\n validations: any[] | undefined\n [key: string]: PlacementResponse[] | string | undefined\n}\n\nexport type NewtailSearchParams = Pick<SearchParams, NewtailSearchParamsKeys>\n\ntype NewtailSearchParamsKeys = 'query' | 'selectedFacets'\n\nexport type PlacementResponse = {\n ad_id: string\n\n click_url: string\n impression_url: string\n view_url: string\n position: number\n\n product_sku: string\n seller_id?: string\n type: string\n\n product_metadata: ProductMetadata\n}\n\nexport type ProductMetadata = {\n productId: string\n}\n\n```" } ]
code_adserver-resolver_2ef877b5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/typings/global.d.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ServiceContext } from '@vtex/api'\nimport type { Clients } from '../clients'\n\ndeclare global {\n type Context = ServiceContext<Clients>\n\n type SelectedFacet = {\n key: string\n value: string\n }\n\n type Options = {\n allowRedirect: boolean\n }\n\n type Operator = 'AND' | 'OR'\n\n type BoostAction = 'add' | 'remove' | 'promote' | 'demote'\n\n type BoostType =\n | 'term'\n | 'id'\n | 'skuId'\n | 'skuEan'\n | 'skuReference'\n | 'productLink'\n | 'product'\n | 'sku'\n | 'productId'\n | 'attribute'\n\n type DynamicRule = {\n action: BoostAction\n type: BoostType\n value: string\n }\n\n type SponsoredProductsParams = SearchParams & {\n placement?: string\n sponsoredCount?: number\n macId?: string\n userId?: string\n skuId?: string\n }\n\n type SearchParams = {\n query?: string\n page?: string\n count?: string\n sort?: string\n operator?: string\n map?: string\n fuzzy?: string\n locale?: string\n allowRedirect?: boolean\n regionId?: string\n simulationBehavior?: 'skip' | 'only1P' | 'default' | null\n hideUnavailableItems?: boolean | null\n productOriginVtex?: string\n selectedFacets?: SelectedFacet[]\n dynamicRules?: DynamicRule[]\n searchState?: string\n customPluginInfo?: string\n anonymousId?: string\n }\n\n type SponsoredProduct = {\n productId: string\n identifier: ProductUniqueIdentifier\n rule: Rule\n advertisement?: Advertisement\n }\n\n type ProductUniqueIdentifier = {\n field: ProductUniqueIdentifierField\n value: string\n sellerId?: string\n }\n\n type ProductUniqueIdentifierField = 'anuId' | 'skuId' | 'product'\n\n type Rule = {\n id: string\n }\n\n type Advertisement = {\n campaignId: string\n adId: string\n actionCost: number\n adRequestId: string\n adResponseId: string\n options?: AdvertisementOptions\n }\n\n type AdvertisementOptions = {\n hideSponsoredBadge?: boolean\n }\n\n type Placement =\n | 'top_search'\n | 'middle_search'\n | 'home_shelfpdp_shelf'\n | 'search_shelf'\n | 'cart_shelf'\n | 'plp_shelf'\n | 'autocomplete'\n | 'homepage'\n\n type AdUnit =\n | 'billboard'\n | 'smartphonebanner'\n | 'leaderboard'\n | 'superleaderboard'\n | 'portrait'\n | 'skyscraper'\n | 'mediumrectangle'\n | 'button120x60'\n | 'mobilephoneinterstitial'\n | 'featurephonesmallbanner'\n | 'featurephonemediumbanner'\n | 'featurephonelargebanner'\n\n type Channel = 'website' | 'android' | 'ios' | 'msite' | 'whatsapp'\n\n type SponsoredBannersParams = {\n sponsoredCount: number\n placement: Placement\n adUnit: AdUnit\n channel?: Channel\n anonymousId?: string\n }\n\n type SponsoredBanner = {\n adResponseId: string\n advertisement: AdvertisementBanner\n }\n\n type AdvertisementBanner = {\n bannerImageId: string\n imageUrl: string\n targetUrl: string\n width: number\n height: number\n }\n}\n\n```" } ]
code_adserver-resolver_bd2297a6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/utils/shouldFetchSponsoredProducts.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {PRODUCT_CLUSTER_MAP, RELEVANCE_DESC_SORT_STR} from \"./constants\"\n\nconst isSortedByRelevance = (args: SearchParams) => {\n return !args.sort || args.sort?.toLowerCase() === RELEVANCE_DESC_SORT_STR\n}\n\nconst queryHasProductClusters = (args: SearchParams) => {\n const mapHasProductClusters = PRODUCT_CLUSTER_MAP.includes(args.map?.toLowerCase() ?? '')\n const facetsHaveProductClusters = args.selectedFacets?.some(\n (facet) => PRODUCT_CLUSTER_MAP.includes(facet.key?.toLowerCase())\n )\n\n return mapHasProductClusters || facetsHaveProductClusters\n}\n\nconst shouldFetchOnProductClusers = async (ctx: Context) => {\n const settings = await ctx.clients.apps.getAppSettings(\n 'vtex.adserver-resolver'\n )\n\n return settings?.enableAdsOnCollections ?? true\n}\n\nconst isFirstPage = (args: SearchParams) => {\n return args.page === undefined || args.page.toString() === '1'\n}\n\n/**\n * Determine whether or not to fetch sponsored products based on a few parameters:\n * 1. If the search is not sorted by relevance, don't fetch.\n * 2. If the search is not for a product cluster (collections), fetch.\n * 3. If the search is for a product cluster, fetch if the feature is enabled.\n */\nexport const shouldFetchSponsoredProducts = async (\n args: SearchParams,\n ctx: Context\n) => {\n if (!isSortedByRelevance(args)) return false\n if (!isFirstPage(args)) return false\n\n if (!queryHasProductClusters(args)) {\n return true\n }\n\n return shouldFetchOnProductClusers(ctx)\n}\n\n```" } ]
code_adserver-resolver_46c965de
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/utils/shouldUseNewtail.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const shouldUseNewtail = async (ctx: Context) => {\n const settings = await ctx.clients.apps.getAppSettings(\n 'vtex.adserver-resolver'\n )\n\n return settings?.enableNewtail ?? false\n}\n\n```" } ]
code_adserver-resolver_72634516
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/utils/compact.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst compact = <T>(object: Record<string, T>) => {\n const result: Record<string, T> = {}\n\n for (const key in object) {\n if (object[key] !== undefined || object[key] !== null) {\n result[key] = object[key]\n }\n }\n\n return result\n}\n\nexport default compact\n\n```" } ]
code_adserver-resolver_f1a40c63
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/utils/constants.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const RELEVANCE_DESC_SORT_STR = 'orderbyscoredesc'\nexport const PRODUCT_CLUSTER_MAP = ['productclusterids', 'productclusternames']\nexport const BRAND_FACET_KEYS = ['b', 'brand']\n\n```" } ]
code_adserver-resolver_0b25f82b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/utils/getNewtailPublisherID.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const getNewtailPublisherId = async (ctx: Context) => {\n const settings = await ctx.clients.apps.getAppSettings(\n 'vtex.adserver-resolver'\n )\n\n const publisherId = settings?.newtailPublisherId\n\n if (!publisherId) {\n throw new Error('Newtail publisher ID not found')\n }\n\n return publisherId\n}\n\n```" } ]
code_adserver-resolver_6193f5db
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/utils/region.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nasync function toSelectedFacets(\n regionId: string | undefined,\n ctx: Context\n): Promise<SelectedFacet[]> {\n const {\n clients: { checkout },\n vtex: { logger },\n } = ctx\n\n if (!regionId) {\n return []\n }\n\n try {\n const regions = (await checkout.regions(regionId)) ?? []\n const region = regions.find((r) => r.id === regionId)\n const sellers = region?.sellers ?? []\n\n return sellers.map((seller) => ({\n key: 'private-seller',\n value: seller.id,\n }))\n } catch (e) {\n logger.error(e)\n\n return []\n }\n}\n\nasync function fromSegment(ctx: Context): Promise<string | undefined> {\n const {\n clients: { segment },\n vtex: { segmentToken, logger },\n } = ctx\n\n try {\n const segmentData = segmentToken\n ? JSON.parse(Buffer.from(segmentToken, 'base64').toString())\n : await segment.getSegment()\n\n return segmentData?.regionId\n } catch (e) {\n logger.error(e)\n\n return undefined\n }\n}\n\nexport default { toSelectedFacets, fromSegment }\n\n```" } ]
code_adserver-resolver_cfdb4508
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/resolvers/index.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { sponsoredBanners } from './sponsoredBanners'\nimport { sponsoredProducts } from './sponsoredProducts'\n\nexport const resolvers = {\n Query: {\n sponsoredProducts,\n sponsoredBanners,\n },\n}\n\n```" } ]
code_adserver-resolver_b48cc5da
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/resolvers/sponsoredBanners.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport AdServer from '../clients/AdServer'\nimport type { AdServerSponsoredBannersResponse } from '../typings/AdServer'\n\nconst mapAdServerResponseToSponsoredBanner = (\n adResponse: AdServerSponsoredBannersResponse\n): SponsoredBanner[] => {\n if (!adResponse?.banners) {\n return []\n }\n\n return adResponse.banners?.map(\n ({ bannerImageId, imageUrl, targetUrl, width, height }) => {\n const advertisement = {\n bannerImageId,\n imageUrl,\n targetUrl,\n width,\n height,\n }\n\n return {\n adResponseId: adResponse?.adResponseId,\n advertisement,\n }\n }\n )\n}\n\nexport async function sponsoredBanners(\n _: unknown,\n args: SponsoredBannersParams,\n ctx: Context\n): Promise<SponsoredBanner[]> {\n try {\n const adResponse = await ctx.clients.adServer.getSponsoredBanners({\n count: args.sponsoredCount,\n userId: args.anonymousId,\n placement: args.placement,\n adUnit: args.adUnit,\n channel: args.channel,\n })\n\n return mapAdServerResponseToSponsoredBanner(adResponse)\n } catch (error) {\n if (error.response?.data === AdServer.ERROR_MESSAGES.AD_NOT_FOUND) {\n return []\n }\n\n throw error\n }\n}\n\n```" } ]
code_adserver-resolver_d9be9c8b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/resolvers/sponsoredProducts/newtail.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport Newtail from '../../clients/Newtail'\nimport type {\n NewtailResponse,\n NewtailPlacement,\n PlacementResponse,\n NewtailRequest,\n} from '../../typings/Newtail'\nimport {BRAND_FACET_KEYS, PRODUCT_CLUSTER_MAP} from '../../utils/constants'\nimport {getNewtailPublisherId} from '../../utils/getNewtailPublisherID'\nimport { shouldFetchSponsoredProducts } from '../../utils/shouldFetchSponsoredProducts'\n\nconst RULE_ID = 'sponsoredProduct'\nconst PRODUCT_SKU_IDENTIFIER_FIELD = 'skuId'\nconst DEFAULT_SPONSORED_COUNT = 3\nconst DEFAULT_PLACEMENT_NAME = 'ads_newtail'\nconst DEFAULT_CAMPAIGN_ID = ''\nconst DEFAULT_SESSION_ID = 'VTEX_SESSION_ID'\n\nconst getPlacementList = (\n newtailResponse: NewtailResponse,\n placement: string\n): PlacementResponse[] => {\n return (newtailResponse[placement] as PlacementResponse[]) ?? []\n}\n\nconst encodeBase64 = (str: string): string => {\n return Buffer.from(str).toString('base64')\n}\n\nconst removeTrackingParamsFromUrl = (eventUrl: string): string => {\n const url = new URL(eventUrl)\n const paramsToRemove = ['user_id', 'session_id', 'event_id']\n\n paramsToRemove.forEach(param => {\n url.searchParams.delete(param)\n })\n\n return url.toString()\n}\n\nconst mapSponsoredProduct = (\n newtailResponse: NewtailResponse,\n requestHadSessionId: boolean,\n placement = DEFAULT_PLACEMENT_NAME,\n): SponsoredProduct[] => {\n const placementList: PlacementResponse[] = getPlacementList(\n newtailResponse,\n placement\n )\n\n if (placementList.length === 0) return []\n\n return placementList?.map(\n ({ product_sku, impression_url, seller_id, product_metadata }) => {\n const advertisement = {\n campaignId: DEFAULT_CAMPAIGN_ID,\n adId: encodeBase64(requestHadSessionId ? impression_url : removeTrackingParamsFromUrl(impression_url)),\n actionCost: 0.0,\n\n adRequestId: newtailResponse?.request_id,\n adResponseId: newtailResponse?.query_id,\n }\n\n return {\n productId: product_metadata.productId,\n identifier: {\n field: PRODUCT_SKU_IDENTIFIER_FIELD,\n value: product_sku,\n },\n rule: { id: RULE_ID },\n advertisement,\n sellerId: seller_id,\n }\n }\n )\n}\n\nconst definePlacements = (\n quantity: number,\n placement = DEFAULT_PLACEMENT_NAME\n): { [key: string]: NewtailPlacement } => {\n const placements: { [key: string]: NewtailPlacement } = {\n [placement]: {\n quantity,\n types: ['product'],\n },\n }\n\n return placements\n}\n\nconst validateParams = (args: SponsoredProductsParams, ctx: Context): boolean => {\n const {\n vtex: { logger },\n } = ctx\n\n if (args.macId) return true\n else {\n logger.warn(\"macId was not provided.\")\n return false\n }\n}\nexport async function newtailSponsoredProducts(\n _: unknown,\n args: SponsoredProductsParams,\n ctx: Context\n): Promise<SponsoredProduct[]> {\n\n const hasMacId = validateParams(args, ctx)\n\n const shouldFetch = await shouldFetchSponsoredProducts(args, ctx)\n if (!shouldFetch) return []\n\n try {\n const adsAmount = args.sponsoredCount ?? DEFAULT_SPONSORED_COUNT\n\n const categoryName =\n args?.selectedFacets?.length && args.selectedFacets.some((facet) => (facet.key.startsWith(\"category\") || facet.key === \"c\" || facet.key === \"categoria\"))\n ? args.selectedFacets\n .filter((facet) => (facet.key.startsWith(\"category\") || facet.key === \"c\" || facet.key === \"categoria\"))\n .map((facet) => facet.value)\n .join(\" > \")\n : undefined;\n\n const brandName = args\n ?.selectedFacets\n ?.filter((facet) => BRAND_FACET_KEYS.includes(facet.key?.toLowerCase()))\n .map((facet) => facet.value)[0]\n\n let context: NewtailRequest['context'] = 'home'\n if (args?.query?.length) {\n context = 'search'\n } else if (categoryName) {\n context = 'category'\n } else if (brandName) {\n context = 'brand_page'\n } else if (args.skuId) {\n context = 'product_page'\n }\n\n const tags = args.selectedFacets\n ?.filter((facet) => PRODUCT_CLUSTER_MAP.includes(facet.key?.toLowerCase()))\n .map((facet) => `product_cluster/${facet.value}`)\n ;\n\n const body: NewtailRequest = {\n term: args.query,\n context,\n category_name: categoryName,\n placements: definePlacements(adsAmount, args.placement),\n user_id: args.userId,\n session_id: hasMacId ? args.macId : DEFAULT_SESSION_ID,\n tags: (tags && tags?.length > 0) ? tags : undefined,\n product_sku: args.skuId,\n brand_name: brandName,\n }\n\n const publisherId = await getNewtailPublisherId(ctx)\n const newtailResponse = await ctx.clients.newtail.getSponsoredProducts(body, publisherId)\n\n return mapSponsoredProduct(newtailResponse, hasMacId, args.placement)\n } catch (error) {\n if (error.response?.data === Newtail.ERROR_MESSAGES.AD_NOT_FOUND) return []\n\n throw error\n }\n}\n\n```" } ]
code_adserver-resolver_33fa1577
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/resolvers/sponsoredProducts/vtex.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport AdServer from '../../clients/AdServer'\nimport type {\n AdServerResponse,\n AdServerSearchParams,\n} from '../../typings/AdServer'\nimport compact from '../../utils/compact'\nimport region from '../../utils/region'\nimport { shouldFetchSponsoredProducts } from '../../utils/shouldFetchSponsoredProducts'\n\nconst RULE_ID = 'sponsoredProduct'\nconst PRODUCT_UNIQUE_IDENTIFIER_FIELD = 'product'\nconst DEFAULT_SPONSORED_COUNT = 3\n\nconst getSearchParams = (\n args: SearchParams,\n privateSellers: SelectedFacet[]\n): AdServerSearchParams => {\n const adServerSearchParams = {\n query: args.query,\n selectedFacets: [...privateSellers, ...(args.selectedFacets ?? [])],\n }\n\n return compact(adServerSearchParams)\n}\n\nconst mapSponsoredProduct = (\n adResponse: AdServerResponse\n): SponsoredProduct[] => {\n if (!adResponse?.sponsoredProducts) return []\n\n return adResponse.sponsoredProducts?.map(\n ({ productId, campaignId, adId, actionCost, options }) => {\n const advertisement = {\n campaignId,\n adId,\n actionCost,\n adRequestId: adResponse?.adRequestId,\n adResponseId: adResponse?.adResponseId,\n options,\n }\n\n return {\n productId,\n identifier: {\n field: PRODUCT_UNIQUE_IDENTIFIER_FIELD,\n value: productId,\n },\n rule: { id: RULE_ID },\n advertisement,\n sellerId: undefined,\n }\n }\n )\n}\n\nexport async function vtexSponsoredProducts(\n _: unknown,\n args: SponsoredProductsParams,\n ctx: Context\n): Promise<SponsoredProduct[]> {\n const shouldFetch = await shouldFetchSponsoredProducts(args, ctx)\n\n if (!shouldFetch) return []\n\n const regionId = args.regionId ?? (await region.fromSegment(ctx))\n const privateSellers = await region.toSelectedFacets(regionId, ctx)\n\n try {\n const adResponse = await ctx.clients.adServer.getSponsoredProducts({\n searchParams: getSearchParams(args, privateSellers),\n count: args.sponsoredCount ?? DEFAULT_SPONSORED_COUNT,\n placement: args.placement,\n userId: args.anonymousId,\n })\n\n return mapSponsoredProduct(adResponse)\n } catch (error) {\n if (error.response?.data === AdServer.ERROR_MESSAGES.AD_NOT_FOUND) return []\n\n throw error\n }\n}\n\n```" } ]
code_adserver-resolver_ab2aca21
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/resolvers/sponsoredProducts/index.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {shouldUseNewtail} from \"../../utils/shouldUseNewtail\";\nimport {newtailSponsoredProducts} from \"./newtail\";\nimport {vtexSponsoredProducts} from \"./vtex\";\n\n\nexport async function sponsoredProducts(\n arg: unknown,\n params: SponsoredProductsParams,\n ctx: Context\n): Promise<SponsoredProduct[]> {\n const should = await shouldUseNewtail(ctx)\n\n if (should) {\n return newtailSponsoredProducts(arg, params, ctx)\n }\n\n return vtexSponsoredProducts(arg, params, ctx)\n}\n\n```" } ]
code_adserver-resolver_ff7eb639
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/__tests__/utils/compact.test.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport compact from '../../utils/compact'\n\ndescribe('#compact', () => {\n const object = {\n a: 1,\n b: null,\n c: undefined,\n }\n\n it('should remove the null and undefined values from an object', () => {\n const result = compact(object)\n\n expect(result).toMatchObject({ a: 1 })\n })\n})\n\n```" } ]
code_adserver-resolver_c7164da6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/__tests__/utils/region.test.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport region from '../../utils/region'\n\ndescribe('region#toSelectedFacets', () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const ctx = {\n clients: {\n checkout: {\n regions: jest.fn(),\n },\n },\n vtex: {\n segmentToken: 'eyJyZWdpb24tSWQiOiIxIn0=',\n logger: {\n error: jest.fn(),\n },\n },\n }\n\n it('should return an array of selected facets', async () => {\n ctx.clients.checkout.regions.mockResolvedValue([\n {\n id: '1',\n sellers: [\n { id: '1', name: 'seller1' },\n { id: '2', name: 'seller2' },\n { id: '3', name: 'seller3' },\n ],\n },\n { id: '2', sellers: [] },\n { id: '3', sellers: [] },\n ])\n\n const result = await region.toSelectedFacets('1', ctx as unknown as Context)\n\n expect(result).toMatchObject([\n { key: 'private-seller', value: '1' },\n { key: 'private-seller', value: '2' },\n { key: 'private-seller', value: '3' },\n ])\n })\n\n it('should return an empty array if regionId is undefined', async () => {\n const result = await region.toSelectedFacets(\n undefined,\n ctx as unknown as Context\n )\n\n expect(result).toMatchObject([])\n })\n\n it('should return an empty array if checkout.regions returns undefined', async () => {\n ctx.clients.checkout.regions.mockResolvedValue(undefined)\n\n const result = await region.toSelectedFacets('1', ctx as unknown as Context)\n\n expect(result).toMatchObject([])\n })\n\n it('should return an empty array if checkout.regions throws an error', async () => {\n ctx.clients.checkout.regions.mockRejectedValue('Error')\n\n const result = await region.toSelectedFacets('1', ctx as unknown as Context)\n\n expect(result).toMatchObject([])\n })\n})\n\ndescribe('region#fromSegment', () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let ctx: any\n\n beforeEach(() => {\n ctx = {\n clients: {\n segment: {\n getSegment: jest.fn(),\n },\n },\n vtex: {\n segmentToken: undefined,\n logger: {\n error: jest.fn(),\n },\n },\n }\n })\n\n it('should return the segment from client if segmentToken is undefined', async () => {\n ctx.clients.segment.getSegment.mockResolvedValue({ regionId: '1' })\n\n const result = await region.fromSegment(ctx as unknown as Context)\n\n expect(result).toBe('1')\n })\n\n it('should return the segment from segmentToken if segmentToken is defined', async () => {\n ctx.vtex.segmentToken = Buffer.from(\n JSON.stringify({ regionId: '2' })\n ).toString('base64')\n\n const result = await region.fromSegment(ctx as unknown as Context)\n\n expect(result).toBe('2')\n })\n\n it('should return undefined if segment.getSegment returns undefined', async () => {\n ctx.clients.segment.getSegment.mockResolvedValue(undefined)\n\n const result = await region.fromSegment(ctx as unknown as Context)\n\n expect(result).toBeUndefined()\n })\n\n it('should return undefined if segment.getSegment throws an error', async () => {\n ctx.clients.segment.getSegment.mockRejectedValue('Error')\n\n const result = await region.fromSegment(ctx as unknown as Context)\n\n expect(result).toBeUndefined()\n })\n})\n\n```" } ]
code_adserver-resolver_edf0fca7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/__tests__/resolvers/sponsoredProducts.test.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport AdServer from '../../clients/AdServer'\nimport { resolvers } from '../../resolvers'\nimport { getSponsoredProductsResponse } from '../__utils__/mocks/adServer'\n\nconst getSponsoredProductsSpy = jest.fn()\n\nconst defaultContext = {\n vtex: { logger: { error: jest.fn() } },\n clients: {\n adServer: { getSponsoredProducts: getSponsoredProductsSpy },\n apps: {\n getAppSettings: jest\n .fn()\n .mockResolvedValue({ enableAdsOnCollections: true }),\n },\n },\n}\n\nconst sponsoredCount = 4\n\nconst defaultVariables = {\n query: 'shoes',\n sort: '',\n anonymousId: 'anonymousId',\n sponsoredCount,\n}\n\ndescribe('query sponsoredProducts', () => {\n const query = resolvers.Query.sponsoredProducts\n\n beforeEach(() => {\n getSponsoredProductsSpy.mockResolvedValue(getSponsoredProductsResponse)\n })\n\n describe('when the shopper is sorting products by relevance', () => {\n describe('and the ad server returns sponsored products', () => {\n const expectedResponse =\n getSponsoredProductsResponse.sponsoredProducts.map(\n ({ productId, campaignId, adId, actionCost, options }) => ({\n productId,\n identifier: {\n field: 'product',\n value: productId,\n },\n rule: { id: 'sponsoredProduct' },\n advertisement: {\n campaignId,\n adId,\n actionCost,\n adRequestId: getSponsoredProductsResponse.adRequestId,\n adResponseId: getSponsoredProductsResponse.adResponseId,\n options,\n },\n })\n )\n\n it('queries the Ad Server and returns the ad response', async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await query({}, defaultVariables, defaultContext as any)\n\n expect(getSponsoredProductsSpy).toHaveBeenCalledWith({\n count: sponsoredCount,\n searchParams: {\n query: 'shoes',\n selectedFacets: [],\n },\n userId: 'anonymousId',\n })\n expect(result).toMatchObject(expectedResponse)\n })\n })\n\n describe('and the ad server returns a \"Ad Not Found\" error', () => {\n beforeEach(() => {\n getSponsoredProductsSpy.mockRejectedValue({\n response: { data: AdServer.ERROR_MESSAGES.AD_NOT_FOUND },\n })\n })\n\n it('queries returns an empty list', async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await query({}, defaultVariables, defaultContext as any)\n\n expect(result).toMatchObject([])\n })\n })\n\n describe('and the shopper is requesting a product collection', () => {\n const selectedFacets = [\n { key: 'productClusterIds', value: 'collectionId' },\n ]\n\n const variables = {\n ...defaultVariables,\n selectedFacets,\n map: 'productClusterIds',\n }\n\n beforeEach(() => {\n getSponsoredProductsSpy.mockResolvedValue(getSponsoredProductsResponse)\n })\n\n it('returns the ad response', async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await query({}, variables, defaultContext as any)\n\n expect(result[0].advertisement?.adId).toBe(\n getSponsoredProductsResponse.sponsoredProducts[0].adId\n )\n })\n\n describe('and the store has disabled sponsored products on collections', () => {\n const context = {\n ...defaultContext,\n clients: {\n ...defaultContext.clients,\n apps: {\n getAppSettings: jest\n .fn()\n .mockResolvedValue({ enableAdsOnCollections: false }),\n },\n },\n }\n\n it('returns an empty list as sponsored products', async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await query({}, variables, context as any)\n\n expect(result).toMatchObject([])\n })\n })\n })\n })\n\n describe('when the shopper is sorting products by something other than relevance', () => {\n const expectedResponse: SponsoredProduct[] = []\n\n const variables = {\n ...defaultVariables,\n sort: 'OrderByTopSaleDESC',\n }\n\n it('returns an empty list as sponsored products', async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await query({}, variables, defaultContext as any)\n\n expect(result).toMatchObject(expectedResponse)\n })\n })\n})\n\n```" } ]
code_adserver-resolver_c32f86c5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/__tests__/resolvers/sponsoredBanners.test.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport AdServer from '../../clients/AdServer'\nimport { resolvers } from '../../resolvers'\nimport { getSponsoredBannersResponse } from '../__utils__/mocks/adServer'\n\nconst getSponsoredBannersSpy = jest.fn()\n\nconst defaultContext = {\n vtex: { logger: { error: jest.fn() } },\n clients: {\n adServer: { getSponsoredBanners: getSponsoredBannersSpy },\n apps: {\n getAppSettings: jest\n .fn()\n .mockResolvedValue({ enableAdsOnCollections: true }),\n },\n },\n}\n\nconst defaultVariables: SponsoredBannersParams = {\n sponsoredCount: 1,\n placement: 'homepage',\n adUnit: 'billboard',\n channel: 'website',\n anonymousId: 'anonymousId',\n}\n\ndescribe('query sponsoredBanners', () => {\n const query = resolvers.Query.sponsoredBanners\n\n beforeEach(() => {\n getSponsoredBannersSpy.mockResolvedValue(getSponsoredBannersResponse)\n })\n\n describe('when the ad server returns sponsored banners', () => {\n it('queries the Ad Server and returns the ad response', async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await query({}, defaultVariables, defaultContext as any)\n\n expect(getSponsoredBannersSpy).toHaveBeenCalledWith({\n count: 1,\n userId: 'anonymousId',\n placement: 'homepage',\n adUnit: 'billboard',\n channel: 'website',\n })\n\n expect(result).toMatchObject([\n {\n adResponseId: 'adResponseBannerId',\n advertisement: {\n bannerImageId: 'bannerImageId',\n height: 250,\n imageUrl: 'https://example.com/banner.jpg',\n targetUrl: 'https://example.com',\n width: 970,\n },\n },\n ])\n })\n\n describe('when the ad server returns a \"Ad Not Found\" error', () => {\n beforeEach(() => {\n getSponsoredBannersSpy.mockRejectedValue({\n response: { data: AdServer.ERROR_MESSAGES.AD_NOT_FOUND },\n })\n })\n\n it('queries returns an empty list', async () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await query({}, defaultVariables, defaultContext as any)\n\n expect(result).toMatchObject([])\n })\n })\n })\n})\n\n```" } ]
code_adserver-resolver_7b8c9f59
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adserver-resolver/node/__tests__/__utils__/mocks/adServer.ts from the adserver-resolver VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n AdServerResponse,\n AdServerSponsoredBannersResponse,\n} from '../../../typings/AdServer'\n\nexport const getSponsoredProductsResponse: AdServerResponse = {\n adRequestId: 'adRequestId',\n adResponseId: 'adResponseId',\n sponsoredProducts: [\n {\n productId: 'productId',\n campaignId: 'campaignId',\n adId: 'adId',\n actionCost: 0.32,\n options: {\n hideSponsoredBadge: true,\n },\n },\n ],\n}\n\nexport const getSponsoredBannersResponse: AdServerSponsoredBannersResponse = {\n adResponseId: 'adResponseBannerId',\n banners: [\n {\n bannerImageId: 'bannerImageId',\n imageUrl: 'https://example.com/banner.jpg',\n targetUrl: 'https://example.com',\n width: 970,\n height: 250,\n },\n ],\n}\n\n```" } ]
code_flow-finance-payment_e104f826
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of flow-finance-payment/docs/README.md from the flow-finance-payment VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/flow-finance-payment) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Flow Finance Payment\n\nThis is a payment authorization app for the Flow Finance payment method (financing with monthly payments). It is used in conjunction with [Flow Finance API](https://github.com/vtex-apps/flow-finance-api) and [Flow Finance Components](https://github.com/vtex-apps/flow-finance-components).\n\n## Configuration\n\n1. Enable Flow Finance as a payment method in your account admin. In the Gateway Affiliation, enter your Flow Finance Client ID as the `Application Key` and your Flow Finance Client Secret as the `Application Token`. For initial testing, make sure the slider is set to `Test` and not `Production/Live`.\n2. [Install](https://vtex.io/docs/recipes/store/installing-an-app) `vtex.flow-finance-api` and `vtex.flow-finance-payment` in your account.\n3. Configure the app settings by clicking \"Apps\" in your admin sidebar and then selecting \"Flow Finance\". The available settings are:\n\n- `Client ID` / `Client Secret`: These are needed for the non-checkout Flow Finance API calls, such as pre-qualification checks and account creation.\n- `Live`: Determines if non-checkout API calls are made in sandbox mode or not. Set to `false` if you are testing the implementation.\n\n4. Update the [orderForm configuration](https://developers.vtex.com/reference/configuration#updateorderformconfiguration) for your account using the following options:\n\n```json\n\"apps\": [\n {\n \"id\": \"flowFinance\",\n \"fields\": [\n \"chosenLoanToken\"\n ]\n }\n]\n```\n\n5. Create three email templates for your account named `\"flow-finance-submitted\"`, `\"flow-finance-approved\"`, and `\"flow-finance-denied\"`. The first will be sent to a shopper when they complete the Flow Finance account sign up form, and one of the other two will be sent to them after Flow Finance reviews their application and either approves or rejects it.\n\n6. Send a `POST` to `https://app.io.vtex.com/vtex.flow-finance-api/v0/{{account}}/master/_v/api/connectors/flow-finance/init-webhooks` using standard VTEX authentication; this will initialize the Flow Finance webhooks that trigger the above emails to be sent. Note that if you do this while in sandbox mode (and while using sandbox keys), you will need to do it again once the app is in production mode (and the production keys have been added).\n\n7. Add the following JavaScript, adjusted as needed, to your account's `checkout6-custom.js` file (this will allow the shopper to choose a loan option inside the checkout payment method window):\n\n```javascript\nlet loanChosen = false\n\nasync function postData(url = '', data = {}) {\n const response = await fetch(url, {\n method: 'POST',\n mode: 'cors',\n cache: 'no-cache',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/json',\n },\n redirect: 'follow',\n referrerPolicy: 'no-referrer',\n body: JSON.stringify(data),\n })\n if (!response.ok) {\n console.error(response)\n return response\n }\n return response.json()\n}\n\nfunction calculateInstallments(\n price,\n interestRate = 0.0149,\n installments = 12\n) {\n if (!price || !interestRate || !installments) return 0\n const pricePerInstallment =\n (price * Math.pow(1 + interestRate, installments) * interestRate) /\n (Math.pow(1 + interestRate, installments) - 1)\n return pricePerInstallment.toFixed(2).replace('.', ',')\n}\n\nfunction hideFlowFinanceOption() {\n $('.payment-group-item:first').click()\n $('#payment-group-custom203PaymentGroupPaymentGroup').hide()\n}\n\nfunction showBuyNowButton() {\n $('#payment-flowfinance-submit').remove()\n $('.payment-submit-wrap').show()\n}\n\nfunction hideBuyNowButton() {\n $('.payment-submit-wrap').hide()\n $('#payment-flowfinance-submit').remove()\n $('.payment-submit-wrap')\n .after(`<button id=\"payment-flowfinance-submit\" class=\"submit btn btn-success btn-large btn-block disabled\">\n <span class=\"flowfinance-custom-button__text-wrapper\">\n <span class=\"flowfinance-custom-button__icon\"></span>\n <span class=\"flowfinance-custom-button__text\">Finalizar Compra</span>\n </span>\n </button>`)\n}\n\nfunction renderPromoMessageWithLinkToSignUpPage(total) {\n let html = ''\n html += `<div class='pa3'><div>`\n html += `Financie sua compra e pague em até 12x de R$ ${calculateInstallments(\n total\n )}*`\n html += `</div><div>`\n html += `<a href='/flow-finance'>Peça seu crédito agora</a>`\n html += `</div><div class='t-mini'>`\n html += `*Parcela calculada com a taxa mínima de 2% ao mês, sem incluir o imposto sobre operações financeiras (IOF).`\n html += `</div><hr class='flowfinance-hr' /><div class='flex flex-row'><div class='flex flex-column justify-center flowfinance-powered-by'>Powered by</div>`\n html += `<img src='https://{{account}}.vteximg.com.br/arquivos/flow-finance-logo.png' alt='Flow Finance' />`\n html += `</div></div>`\n $('.FlowFinancePaymentGroup').html(html)\n}\n\nfunction renderMessageToCheckBackLater() {\n let html = ''\n html += `<div class='pa3'><div>`\n html += `Sua análise de crédito ainda está em andamento. Em breve você vai receber uma mensagem com o resultado.`\n html += `</div><hr class='flowfinance-hr' /><div class='flex flex-row'><div class='flex flex-column justify-center flowfinance-powered-by'>Powered by</div>`\n html += `<img src='https://{{account}}.vteximg.com.br/arquivos/flow-finance-logo.png' alt='Flow Finance' />`\n html += `</div></div>`\n $('.FlowFinancePaymentGroup').html(html)\n}\n\nfunction renderMessageThatUserDoesNotHaveEnoughCredit(availableCredit) {\n let html = ''\n html += `<div class='pa3'><div>`\n html += `Seu saldo de crédito é insuficiente para realizar esse pagamento.<br />Ao pagar as parcelas de suas compras anteriores, seu saldo de crédito será incrementado.`\n html += `</div><hr class='flowfinance-hr' /><div>`\n html += `Seu saldo de crédito é: <b>R$${availableCredit\n .toString()\n .replace('.', ',')}</b>`\n html += `</div><hr class='flowfinance-hr' /><div class='flex flex-row'><div class='flex flex-column justify-center flowfinance-powered-by'>Powered by</div>`\n html += `<img src='https://{{account}}.vteximg.com.br/arquivos/flow-finance-logo.png' alt='Flow Finance' />`\n html += `</div></div>`\n $('.FlowFinancePaymentGroup').html(html)\n}\n\nfunction renderLoanOptions(loanOptions, availableCredit) {\n let html = `<div class='pa3'><div>`\n loanOptions.forEach((option, index) => {\n html += `<div class='flex flex-row flowfinance-loan-options'>`\n html += `<input type='radio' id='loan-${index}' name='loans' onClick='updateOrderForm(\"${option.offer_token}\")' />`\n html += `<label for='loan-${index}'>`\n html += `<b>${option.term}X R$${option.installment_amount} (${option.interest_rate}% APR)</b>`\n html += `</label></div>`\n })\n html += `</div><hr class='flowfinance-hr' /><div>`\n html += `Seu saldo de crédito é: <b>R$${availableCredit\n .toString()\n .replace('.', ',')}</b>`\n html += `</div><hr class='flowfinance-hr' /><div class='flex flex-row'>`\n html += `<div class='flex flex-column justify-center flowfinance-powered-by'>Powered by</div>`\n html += `<img src='https://{{account}}.vteximg.com.br/arquivos/flow-finance-logo.png' alt='Flow Finance' />`\n html += `</div></div>`\n $('.FlowFinancePaymentGroup').html(html)\n}\n\nfunction updateOrderForm(offerToken) {\n loanChosen = true\n let orderFormID = vtexjs.checkout.orderFormId\n $.ajax({\n url:\n window.location.origin +\n '/api/checkout/pub/orderForm/' +\n orderFormID +\n '/customData/flowfinance/chosenLoanToken',\n type: 'PUT',\n data: { value: offerToken },\n success: function() {\n vtexjs.checkout.getOrderForm().done(function(orderForm) {\n if (orderForm.customData) {\n showBuyNowButton()\n } else {\n initializeFlowFinance()\n }\n })\n },\n })\n}\n\nasync function initializeFlowFinance() {\n $('.FlowFinancePaymentGroup').html(\n `<div class=\"pa3 center\"><i class=\"icon-spinner icon-spin\" /></div>`\n )\n $('.FlowFinancePaymentGroup').show()\n hideBuyNowButton()\n let email = ''\n let total = 0\n let credit = 0\n let status = 'none'\n let loanOptions = []\n\n await vtexjs.checkout.getOrderForm().done(function(orderForm) {\n if (orderForm.clientProfileData) {\n email = orderForm.clientProfileData.email\n total = orderForm.value\n\n if (email && total > 0) {\n total = total / 100\n postData(`/_v/api/connectors/flow-finance/get-loan-options`, {\n email: email,\n total: total,\n }).then(response => {\n if (\n response.accountStatus &&\n response.availableCredit &&\n response.loanOptions\n ) {\n status = response.accountStatus\n credit = response.availableCredit\n loanOptions = response.loanOptions\n }\n\n if (status === 'rejected' || !email || !total) {\n hideFlowFinanceOption()\n }\n if (status === 'none' || status === 'pending') {\n renderPromoMessageWithLinkToSignUpPage(total)\n }\n if (status === 'under-review') {\n renderMessageToCheckBackLater()\n }\n if (status === 'approved') {\n if (credit < total) {\n renderMessageThatUserDoesNotHaveEnoughCredit(credit)\n } else if (loanOptions.length) {\n renderLoanOptions(loanOptions, credit)\n }\n }\n })\n }\n if (!email || !total) {\n hideFlowFinanceOption()\n }\n }\n })\n}\n\n$(window).on('checkoutRequestBegin.vtex', function(evt, ajaxOptions) {\n console.log('checkout request begin')\n if (\n !loanChosen &&\n $('.payment-group-item.active').attr('id') ===\n 'payment-group-FlowFinancePaymentGroup'\n ) {\n initializeFlowFinance()\n } else {\n const json = JSON.parse(ajaxOptions.data)\n if (\n json.payments &&\n json.payments[0].paymentSystemName &&\n json.payments[0].paymentSystemName === 'Flow Finance'\n ) {\n if (!loanChosen) initializeFlowFinance()\n } else {\n showBuyNowButton()\n }\n }\n})\n\n$(window).on('hashchange', function() {\n if (\n '#/payment' === window.location.hash &&\n $('.payment-group-item.active').attr('id') ===\n 'payment-group-FlowFinancePaymentGroup'\n ) {\n initializeFlowFinance()\n }\n})\n```\n\n8. Add the following CSS, adjusted as needed, to your account's `checkout6-custom.css` file:\n\n```css\n.flex {\n display: flex;\n}\n.flex-column {\n flex-direction: column;\n}\n.flex-row {\n flex-direction: row;\n}\n.justify-center {\n justify-content: center;\n}\n.pa3 {\n padding: 0.5rem;\n}\n.t-mini {\n font-weight: normal;\n font-size: 0.75rem;\n text-transform: initial;\n letter-spacing: 0;\n}\n.flowfinance-loan-options > input {\n margin-right: 5px;\n}\n.flowfinance-hr {\n border-top: 1px solid #c4c4c4;\n border-bottom: none;\n}\n.FlowFinancePaymentGroup {\n display: none;\n}\n```\n\n```" } ]
code_flow-finance-payment_97beb610
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of flow-finance-payment/pages/pages.json from the flow-finance-payment VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"pages\": {\n \"ff-test\": {\n \"path\": \"/ff-test\"\n }\n },\n \"extensions\": {\n \"checkout/transactions/flow-finance-payment\": {\n \"component\": \"FlowFinanceModal\"\n },\n \"ff-test\": {\n \"component\": \"FlowFinanceTest\"\n }\n }\n}\n\n```" } ]
code_flow-finance-payment_9808d0f9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of flow-finance-payment/react/package.json from the flow-finance-payment VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"flow-finance-payment\",\n \"version\": \"0.0.1\",\n \"description\": \"\",\n \"scripts\": {\n \"test\": \"vtex-scripts test\"\n },\n \"author\": \"VTEX\",\n \"license\": \"UNLICENSED\",\n \"dependencies\": {\n \"graphql\": \"^15.0.0\",\n \"react\": \"^16.8.6\",\n \"react-dom\": \"^16.8.5\",\n \"react-intl\": \"^4.3.1\",\n \"vtex-tachyons\": \"^3.2.0\"\n },\n \"devDependencies\": {\n \"@types/bootstrap\": \"^4.3.0\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jquery\": \"^3.3.34\",\n \"@types/node\": \"^10.14.4\",\n \"@types/ramda\": \"^0.27.0\",\n \"@types/react\": \"^16.8.8\",\n \"@types/react-dom\": \"^16.8.3\",\n \"eslint\": \"5.15.1\",\n \"eslint-config-vtex\": \"10.1.0\",\n \"eslint-config-vtex-react\": \"4.1.0\",\n \"prettier\": \"^2.0.2\",\n \"tslint\": \"^5.12.1\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typescript\": \"3.8.3\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@7.41.1/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@8.73.11/public/@types/vtex.styleguide\"\n }\n}\n\n```" } ]
code_flow-finance-payment_1a01f5fc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of flow-finance-payment/react/FlowFinanceModal.tsx from the flow-finance-payment VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport AffirmModal from './components/FlowFinanceModal'\n\nexport default AffirmModal\n\n```" } ]
code_flow-finance-payment_06f33df2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of flow-finance-payment/store/interfaces.json from the flow-finance-payment VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store.custom#ff-test\": {\n \"required\": [\"ff-test\"]\n },\n \"ff-test\": {\n \"component\": \"FlowFinanceTest\"\n }\n}\n\n```" } ]
code_flow-finance-payment_541949fa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of flow-finance-payment/store/routes.json from the flow-finance-payment VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store.custom#ff-test\": {\n \"path\": \"/ff-test\"\n }\n}\n\n```" } ]
code_flow-finance-payment_402585bf
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of flow-finance-payment/react/typings/vtex.render-runtime.d.ts from the flow-finance-payment VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import { Component, ComponentType, ReactElement } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n export const ExtensionPoint: ReactElement\n export const Helmet: ComponentType<any>\n export const Link: ReactElement\n export const NoSSR: ComponentType<any>\n export const RenderContextConsumer: ReactElement\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n interface RenderComponent<P = {}, S = {}> extends Component<P, S> {\n getCustomMessages?: (locale: string) => any\n schema: ComponentSchema\n getSchema?: (a: any, b: ?any) => ComponentSchema\n uiSchema: UISchema\n }\n\n export interface ComponentsRegistry {\n [component: string]: RenderComponent<any, any>\n }\n\n export interface Window extends Window {\n __RENDER_7_COMPONENTS__: ComponentsRegistry\n }\n\n let global: Window\n}\n\n```" } ]
code_flow-finance-payment_a9ead2bf
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of flow-finance-payment/react/typings/vtex.styleguide.d.ts from the flow-finance-payment VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n import { ComponentType } from 'react'\n\n export const PageBlock: ComponentType<Props>\n export const ModalDialog: ComponentType<Props>\n export const Button: ComponentType<Props>\n export const ButtonPlain: ComponentType<Props>\n export const ButtonWithIcon: ComponentType<Props>\n export const Input: ComponentType<Props>\n export const Spinner: ComponentType<Props>\n export const Dropdown: ComponentType<Props>\n export const Checkbox: ComponentType<Props>\n export const Toggle: ComponentType<Props>\n export const Divider: ComponentType<Props>\n export const IconCheck: ComponentType<Props>\n export const IconClose: ComponentType<Props>\n export const IconDelete: ComponentType<Props>\n\n interface Props {\n [key: string]: any\n }\n}\n\n```" } ]