id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_store-locator_a902033f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/messages/en.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/more-details\": \"More details\",\n \"store/none-stores\": \"None stores nearby\",\n \"store/load-all\": \"Load all stores\",\n \"store/back-link\": \"Back to all stores\",\n \"store/address-label\": \"Store address\",\n \"store/information-label\": \"Information\",\n \"store/store-closed\": \"Closed\",\n \"store/hours-label\": \"Store hours\",\n \"store/day-of-week-sunday\": \"Sunday\",\n \"store/day-of-week-monday\": \"Monday\",\n \"store/day-of-week-tuesday\": \"Tuesday\",\n \"store/day-of-week-wednesday\": \"Wednesday\",\n \"store/day-of-week-thursday\": \"Thursday\",\n \"store/day-of-week-friday\": \"Friday\",\n \"store/day-of-week-saturday\": \"Saturday\"\n}\n\n```"
}
] |
code_store-locator_e54b0451
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/messages/context.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/more-details\": \"store/more-details\",\n \"store/none-stores\": \"store/none-stores\",\n \"store/load-all\": \"store/load-all\",\n \"store/back-link\": \"store/back-link\",\n \"store/address-label\": \"store/address-label\",\n \"store/information-label\": \"store/information-label\",\n \"store/store-closed\": \"store/store-closed\",\n \"store/hours-label\": \"store/hours-label\",\n \"store/day-of-week-sunday\": \"store/day-of-week-sunday\",\n \"store/day-of-week-monday\": \"store/day-of-week-monday\",\n \"store/day-of-week-tuesday\": \"store/day-of-week-tuesday\",\n \"store/day-of-week-wednesday\": \"store/day-of-week-wednesday\",\n \"store/day-of-week-thursday\": \"store/day-of-week-thursday\",\n \"store/day-of-week-friday\": \"store/day-of-week-friday\",\n \"store/day-of-week-saturday\": \"store/day-of-week-saturday\"\n}\n```"
}
] |
code_store-locator_26b8a7a0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/messages/es.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/more-details\": \"Más detalles\",\n \"store/none-stores\": \"Ninguna tienda cercana\",\n \"store/load-all\": \"Cargar todas las tiendas\",\n \"store/back-link\": \"Volver a todas las tiendas\",\n \"store/address-label\": \"Dirección de la tienda\",\n \"store/information-label\": \"Información\",\n \"store/store-closed\": \"Cerrado\",\n \"store/hours-label\": \"Horario de la tienda\",\n \"store/day-of-week-sunday\": \"Domingo\",\n \"store/day-of-week-monday\": \"Lunes\",\n \"store/day-of-week-tuesday\": \"Martes\",\n \"store/day-of-week-wednesday\": \"Miércoles\",\n \"store/day-of-week-thursday\": \"Jueves\",\n \"store/day-of-week-friday\": \"Viernes\",\n \"store/day-of-week-saturday\": \"Sábado\"\n}\n```"
}
] |
code_store-locator_a00968f3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/docs/README.md from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/store-locator) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Store Locator\n\n## ⚠️ Maintenance ⚠️\n*Starting June 1st 2023, this application will no longer be maintained by VTEX.*\n\n---\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nThe Store Locator app fetches the Pickup point data in order to display address location for retail stores.\n\n\n\n\n## Configuration\n\n1. [Install](https://vtex.io/docs/recipes/development/installing-an-app/) the Store Locator app in your VTEX account by running `vtex install vtex.store-locator` in your terminal.\n2. In your account's admin page, select **Inventory & Shipping** section and then access **Settings**.\n3. Type in the Google Geolocation API key and save your changes.\n4. Open your Store Theme app directory in your code editor.\n5. Add the Store Locator app as a `peerDependency` in the `manifest.json` file:\n\n```diff\n \"peerDependencies\": {\n+ \"vtex.store-locator\": \"0.x\"\n }\n```\n\nOnce installed, the app will generate a new route called `/stores` for your store, listing the retail stores registered in the **Pickup Points** section (under the **Inventory & Shipping** module).\n\nThe new page already contains a default template with all blocks exported by the Store Locator app, meaning the `/stores` page is ready to be rendered and no further actions are required. However, you can **customize the new page overwriting the template by creating a brand new one**. To do so, check the [**Advanced configuration**](./README.md#advanced-configuration) section below.\n\n> ℹ️ _This app will also **add a new entry to your store's `/sitemap.xml` file so that all your pickup points are available to search engines** - make sure you already have the `vtex.store-sitemap@2.x` app installed in your VTEX account!_\n\n### Advanced configuration\n\nIn order to define the Store Locator custom page UI, you must use the blocks exported by the `vtex.store-locator` app. Namely, they are:\n\n| Block name | Description |\n| :------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------: |\n| `store-list` | Renders a list of retail stores and a map with all their locations marked. |\n| `store-group` | Provides the Pickup Point data to other blocks exported by the app, such as the ones listed below. |\n| `store-name` | Renders the store name. |\n| `store-back-link` | Renders a link to return to the previous page. |\n| `store-map` | Renders a map with the retail store's location. |\n| `store-address` | Renders the store's address. |\n| `store-hours` | Renders the store's opening hours. This information comes by default from the Pickup Points configuration, but you can also define manually through the Store's theme |\n| `store-instructions` | Renders the desired instructions to access the retail store. |\n\n1. Open your Store Theme app directory in your code editor.\n2. In the `/store/blocks` folder of your Store Theme app, create a new file called `storelocator.json`.\n3. Create a new store template in it called `store.storelocator`. In its blocks array, paste the default implementation stated below:\n\n```json\n{\n \"store.storelocator\": {\n \"blocks\": [\"flex-layout.row#title\", \"flex-layout.row#container\"]\n },\n \"flex-layout.row#title\": {\n \"children\": [\"flex-layout.col#title\"]\n },\n \"flex-layout.row#container\": {\n \"children\": [\"store-list\"]\n },\n \"flex-layout.col#title\": {\n \"children\": [\"rich-text#title\"],\n \"props\": {\n \"blockClass\": \"title\",\n \"preventVerticalStretch\": true\n }\n },\n \"rich-text#title\": {\n \"props\": {\n \"text\": \"## Store Locator\"\n }\n },\n \"store.storedetail\": {\n \"blocks\": [\"flex-layout.row#titleStore\", \"store-group\"]\n },\n \"store-group\": {\n \"children\": [\"flex-layout.row#containerStore\"],\n \"props\": {\n \"title\": \"{storeName} Store\"\n }\n },\n \"flex-layout.row#titleStore\": {\n \"children\": [\"flex-layout.col#titleStore\"]\n },\n \"flex-layout.row#containerStore\": {\n \"children\": [\"flex-layout.col#detail\", \"flex-layout.col#store\"]\n },\n \"flex-layout.col#titleStore\": {\n \"children\": [\"rich-text#titleStore\"],\n \"props\": {\n \"blockClass\": \"title\",\n \"preventVerticalStretch\": true\n }\n },\n \"rich-text#titleStore\": {\n \"props\": {\n \"text\": \"## Store Detail\"\n }\n },\n \"flex-layout.col#detail\": {\n \"children\": [\n \"store-back-link\",\n \"store-map\",\n \"store-address\",\n \"store-hours\",\n \"store-instructions\"\n ],\n \"props\": {\n \"width\": \"30%\",\n \"preventVerticalStretch\": true\n }\n },\n \"flex-layout.col#store\": {\n \"children\": [\"store-name\"],\n \"props\": {\n \"width\": \"70%\"\n }\n },\n \"store-hours\": {\n \"props\": {\n \"label\": \"Business hours:\",\n \"format\": \"12h\",\n \"businessHours\": [\n {\n \"dayOfWeek\": \"Sunday\",\n \"openingTime\": \"11:00am\",\n \"closingTime\": \"5:00pm\"\n },\n {\n \"dayOfWeek\": \"Monday\",\n \"openingTime\": \"11:00am\",\n \"closingTime\": \"6:00pm\"\n },\n {\n \"dayOfWeek\": \"Tuesday\",\n \"openingTime\": \"11:00am\",\n \"closingTime\": \"6:00pm\"\n },\n {\n \"dayOfWeek\": \"Wednesday\",\n \"openingTime\": \"11:00am\",\n \"closingTime\": \"6:00pm\"\n },\n {\n \"dayOfWeek\": \"Thursday\",\n \"openingTime\": \"11:00am\",\n \"closingTime\": \"6:00pm\"\n },\n {\n \"dayOfWeek\": \"Friday\",\n \"openingTime\": \"11:00am\",\n \"closingTime\": \"6:00pm\"\n },\n {\n \"dayOfWeek\": \"Saturday\",\n \"openingTime\": \"11:00am\",\n \"closingTime\": \"5:00pm\"\n }\n ]\n }\n },\n \"store-back-link\": {\n \"props\": {\n \"label\": \"Back to all stores\"\n }\n },\n \"store-instructions\": {\n \"props\": {\n \"label\": \"\"\n }\n }\n}\n```\n\n4. Configure each one of the blocks previously declared as you wish using their props (check out the following tables).\n\n#### `store-list`\n\n| Prop name | Type | Description | Default value |\n| :-----------: | :------: | :--------------------------------------------------------------------------: | :------------------: |\n| `filterByTag` | `string` | Filter fetched Pickup Points by this tag. | undefined |\n| `icon` | `string` | Icon used to display store location in map. Input icon URL (`svg` or `png`). | Google's default |\n| `iconWidth` | `number` | Icon width in pixels (`px`). | Image default width |\n| `iconHeight` | `number` | Icon height in pixels (`px`). | Image default height |\n| `zoom` | `number` | Map zoom as a number. | `10` |\n| `lat` | `number` | Latitude coordinate. | undefined |\n| `long` | `number` | Longitude coordinate. | undefined |\n| `sortBy` | `string` | Property (`name` or `distance`) used to sort the stores list. | `distance` |\n\n> ℹ️ _Use the `lat` and `long` props to display Pickup Points configured in seller accounts. If these props are not configured and you do not have any pick up points set up in your main account, the app will display no stores._\n\n> ℹ️ _The `filterByTag` prop cannot be used along with `lat` and `long`. If you set a value for `filterByTag`, the `lat` and `long` props will be ignored._\n\n#### `store-group` props\n\n| Prop name | Type | Description | Default value |\n| :-------------------: | :-------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----------: |\n| `title` | `string` | Title used in the page's HTML `title` tag and Structured Data for SEO purposes. The `{storeName}`, `{storeCity}`, and / or `{storeState}` variables can be used in the title text. | `{storeName}` |\n| `description` | `string` | Description text used in the page's HTML `description` meta tag and Structured Data for SEO purposes. The `{storeName}`, `{storeCity}`, and / or `{storeState}` variables can be used in the description text. | empty string |\n| `imageSelector` | `string` | CSS Selector to select the images included in the page's Structured Data. | empty string |\n| `instructionsAsPhone` | `boolean` | To provide a unique phone number for each store, a phone number can be entered in the `Instructions` field in the Pickup Points section. The `store-instructions` will display a phone number and it will be included in the page's Structured Data. | `false` |\n\n⚠️ _Both `imageSelector` and `instructionsAsPhone` must be declared with valid values in order to provide Structured Data for SEO purposes._\n\n#### `store-name` props\n\n| Prop name | Type | Description | Default value |\n| :-------: | :------: | :--------------------------------------------------------------------------------------------------------------------------------------: | :-----------: |\n| `text` | `string` | Text to be displayed as store name. `{storeName}`, `{storeCity}`, and / or `{storeState}` values can be used to generate the store name. | undefined |\n| `tag` | `string` | HTML element to wrap the `store-name` block when rendered on the UI. | `div` |\n\n#### `store-back-link` props\n\n| Prop name | Type | Description | Default value |\n| :-------: | :------: | :----------------------------------------------------------------: | :------------------: |\n| `label` | `string` | Text displayed by `store-back-link` block when rendered on the UI. | `Back to all stores` |\n\n#### `store-map` props\n\n| Prop name | Type | Description | Default value |\n| :-------: | :-------: | :--------------------------------------------------------------------------: | :-----------: |\n| `width` | `string` | Map width. | `100%` |\n| `height` | `string` | Map height. | `200px` |\n| `zoom` | `integer` | Map zoom as a `number` | `14` |\n| `icon` | `string` | Icon used to display store location in map. Input icon URL (`svg` or `png`). | undefined |\n\n#### `store-address` props\n\n| Prop name | Type | Description | Default value |\n| :-------: | :------: | :----------------------------------------------------------: | :-------------: |\n| `label` | `string` | Label for the `store-address` block when rendered on the UI. | `Store address` |\n\n#### `store-hours` props\n\n| Prop name | Type | Description | Default value. |\n| :-------------: | :---------------: | :-------------------------------------------------------------------------------: | :------------: |\n| `label` | `string` | Label for the `store-hours` block when rendered on the UI. | `Store hours` |\n| `format` | `enum` | Hour format. Possible values are `12h` and `24h`. | `24h` |\n| `businessHours` | `array of object` | format `{\"dayOfWeek\": \"Sunday\",\"openingTime\": \"11:00am\",\"closingTime\": \"5:00pm\"}` | undefined |\n\n#### `store-description` props\n\n| Prop name | Type | Description | Default value |\n| :-------: | :------: | :--------------------------------------------------------------------------------------------------------------------------------------------------: | :-----------: |\n| `text` | `string` | Text to be displayed on the store page. Use `{storeName}`, `{storeCity}`, or `{storeState}` within your text to display that store's specific value. | undefined |\n\n#### `store-instructions` props\n\n| Prop name | Type | Description | Default value |\n| :-------: | :------: | :---------------------------------------------------------------: | :-----------: |\n| `label` | `string` | Label for the `store-instructions` block when rendered on the UI. | `Information` |\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| `addressContainer` |\n| `addressLabel` |\n| `addressListFirstItem` |\n| `addressListItem` |\n| `addressListLink` |\n| `addressList` |\n| `addressStoreAddress` |\n| `addressStoreName` |\n| `addressStoreAddressGroupA` |\n| `addressStoreAddressNumber` |\n| `addressStoreAddressStreet` |\n| `backlinkContainer` |\n| `backlink` |\n| `businessHours` |\n| `container` |\n| `descriptionContainer` |\n| `descriptionText` |\n| `dayOfWeek` |\n| `divider` |\n| `hourRow` |\n| `hoursContainer` |\n| `hoursLabel` |\n| `instructionsContainer` |\n| `instructionsLabel` |\n| `instructionsText` |\n| `listingMapContainer` |\n| `loadAll` |\n| `markerInfoAddress` |\n| `markerInfoLink` |\n| `markerInfoStoreName` |\n| `markerInfo` |\n| `noResults` |\n| `storeName` |\n| `storesListCol` |\n| `storesList` |\n| `storesMapCol` |\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```"
}
] |
code_store-locator_21c39bae
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/graphql/schema.graphql from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\ntype Query {\n getStores(latitude: Float, longitude: Float, keyword: String): StoreResponse\n @cacheControl(scope: PRIVATE)\n}\n\ntype StoreResponse {\n items: [StoreItemType]\n}\ntype StoreItemType {\n id: String\n name: String\n instructions: String\n distance: Float\n isActive: Boolean\n address: Address\n businessHours: [Hours]\n pickupHolidays: [PickupHolidays]\n}\ntype PickupHolidays {\n date: String\n hourBegin: String\n hourEnd: String\n}\n\ntype Address {\n postalCode: String\n country: String\n city: String\n state: String\n neighborhood: String\n street: String\n number: String\n complement: String\n reference: String\n location: LocationType\n}\n\ntype LocationType {\n latitude: Float\n longitude: Float\n}\n\ntype Hours {\n dayOfWeek: Int\n openingTime: String\n closingTime: String\n}\n\n```"
}
] |
code_store-locator_6b6f3eca
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/node/service.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 512,\n \"ttl\": 60,\n \"timeout\": 60,\n \"routes\": {\n \"getSitemap\": {\n \"path\": \"/sitemap/store-locator.xml\",\n \"public\": true\n }\n }\n}\n\n```"
}
] |
code_store-locator_4d89e8f7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/node/typings.d.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Logger {\n // eslint-disable-next-line @typescript-eslint/ban-types\n log(content: string, level: LogLevel, details?: {}): PromiseLike<void>\n}\n\ninterface OperationState {\n orderFormId: string\n ctx: Context\n data?: OperationData\n logger: Logger\n}\n\ninterface OperationData {\n orderForm?: any\n userProfileId: string\n cookie: string\n}\n\ntype ProcessPaymentStep = (\n state: OperationState,\n next: () => Promise<void>\n) => Promise<void>\n\ntype LogLevel = 'info' | 'error' | 'warning'\n\ntype Timings = { [middleware: string]: [number, number] }\n\ndeclare module '*.json' {\n const value: any\n export default value\n}\n\n```"
}
] |
code_store-locator_3ff8eb35
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/node/package.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.store-locator\",\n \"version\": \"1.0.1\",\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"ramda\": \"^0.25.0\",\n \"slugify\": \"^1.2.6\"\n },\n \"devDependencies\": {\n \"@types/bluebird\": \"^3.5.25\",\n \"@types/co-body\": \"0.0.3\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.12\",\n \"@vtex/prettier-config\": \"^0.3.1\",\n \"tslint\": \"^5.12.0\",\n \"tslint-config-prettier\": \"^1.18.0\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.flex-layout\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.flex-layout@0.17.0/public/@types/vtex.flex-layout\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.130.0/public/@types/vtex.render-runtime\",\n \"vtex.rich-text\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.rich-text@0.14.0/public/@types/vtex.rich-text\",\n \"vtex.store\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store@2.120.0/public/@types/vtex.store\",\n \"vtex.store-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.142.6/public/@types/vtex.store-graphql\",\n \"vtex.store-sitemap\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-sitemap@2.13.9/public/@types/vtex.store-sitemap\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.0/public/@types/vtex.styleguide\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit && tslint -c tslint.json './**/*.ts'\"\n }\n}\n\n```"
}
] |
code_store-locator_096a6f60
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/node/index.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n ClientsConfig,\n ServiceContext,\n ParamsContext,\n RecorderState,\n} from '@vtex/api'\nimport { Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { resolvers } from './graphql'\n\nconst TIMEOUT_MS = 60000\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 },\n}\n\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\n type Context = ServiceContext<Clients>\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service<Clients, RecorderState, ParamsContext>({\n clients,\n graphql: {\n resolvers: {\n Query: resolvers.Query,\n },\n },\n routes: resolvers.Routes,\n})\n\n```"
}
] |
code_store-locator_82bcc11d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/StoreBackLink.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable jsx-a11y/no-static-element-interactions */\n/* eslint-disable jsx-a11y/click-events-have-key-events */\nimport React, { FC } from 'react'\nimport { defineMessages, WrappedComponentProps, injectIntl } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { useCssHandles } from 'vtex.css-handles'\n\nconst CSS_HANDLES = ['backlinkContainer', 'backlink'] as const\nconst messages = defineMessages({\n backlink: {\n defaultMessage: 'Back to all stores',\n id: 'store/back-link',\n },\n})\n\ninterface StoreBackLinkProps {\n label: string\n}\n\nconst StoreBackLink: FC<StoreBackLinkProps & WrappedComponentProps> = ({\n label,\n intl,\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n const { navigate } = useRuntime()\n\n const goBack = () => {\n navigate({\n page: 'store.storelocator',\n })\n }\n\n return (\n <div className={handles.backlinkContainer}>\n <span\n className={`link c-link underline-hover pointer ${handles.backlink}`}\n onClick={() => {\n goBack()\n }}\n >\n {label ?? intl.formatMessage(messages.backlink)}\n </span>\n </div>\n )\n}\n\nexport default injectIntl(StoreBackLink)\n\n```"
}
] |
code_store-locator_e06128f3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/StoreName.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport PropTypes from 'prop-types'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { useStoreGroup } from './StoreGroup'\n\nconst CSS_HANDLES = ['storeName'] as const\n\nconst StoreName: FC<StoreNameProps> = ({ text, tag }) => {\n const handles = useCssHandles(CSS_HANDLES)\n const group = useStoreGroup()\n\n if (!group) {\n return null\n }\n\n const Wrapper = tag as keyof JSX.IntrinsicElements\n\n const parseText = (string: string) => {\n const { city, state } = group.address\n\n return string\n .replace(/{storeName}/gi, group.friendlyName)\n .replace(/{storeCity}/gi, city ?? '')\n .replace(/{storeState}/gi, state ?? '')\n }\n\n return (\n <Wrapper className={handles.storeName}>\n {text ? parseText(text) : group.friendlyName}\n </Wrapper>\n )\n}\n\ninterface StoreNameProps {\n text?: string\n tag?: string\n}\n\nStoreName.defaultProps = {\n tag: 'div',\n}\n\nStoreName.propTypes = {\n text: PropTypes.string,\n tag: PropTypes.string,\n}\n\nexport default StoreName\n\n```"
}
] |
code_store-locator_192ebae4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/List.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { FunctionComponent } from 'react'\nimport React, { useState, useEffect } from 'react'\nimport type { WrappedComponentProps } from 'react-intl'\nimport { injectIntl, FormattedMessage } from 'react-intl'\nimport { useQuery, useLazyQuery } from 'react-apollo'\nimport { Spinner } from 'vtex.styleguide'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport ORDER_FORM from './queries/orderForm.gql'\nimport GET_STORES from './queries/getStores.gql'\nimport GOOGLE_KEYS from './queries/GetGoogleMapsKey.graphql'\nimport Listing from './components/Listing'\nimport Pinpoints from './components/Pinpoints'\n\nconst CSS_HANDLES = [\n 'container',\n 'storesListCol',\n 'storesList',\n 'storesMapCol',\n 'noResults',\n 'listingMapContainer',\n 'loadAll',\n] as const\n\ninterface Props {\n filterByTag?: string\n icon?: string\n iconWidth?: number\n iconHeight?: number\n zoom?: number\n lat?: number\n long?: number\n sortBy?: string\n}\n\nconst StoreList: FunctionComponent<WrappedComponentProps & Props> = ({\n filterByTag,\n icon,\n iconWidth,\n iconHeight,\n zoom,\n lat,\n long,\n sortBy = 'distance',\n}) => {\n const { data: ofData, loading: ofLoading } = useQuery(ORDER_FORM, {\n ssr: false,\n })\n\n const { data: googleMapsKeys } = useQuery(GOOGLE_KEYS, { ssr: false })\n\n const [getStores, { data, loading }] = useLazyQuery(GET_STORES, {\n fetchPolicy: 'cache-first',\n })\n\n const [state, setState] = useState({\n allLoaded: false,\n center: null,\n zoom: zoom ?? 10,\n })\n\n const handles = useCssHandles(CSS_HANDLES)\n\n const handleLoadAll = () => {\n setState({\n ...state,\n allLoaded: true,\n })\n getStores({\n variables: {\n latitude: lat,\n longitude: long,\n filterByTag: lat && long ? null : filterByTag,\n },\n })\n }\n\n const handleCenter = (center: any) => {\n setState({\n ...state,\n center,\n })\n }\n\n useEffect(() => {\n if (!ofData?.orderForm) return\n\n let longitude: number | undefined\n let latitude: number | undefined\n\n if (\n ofData?.orderForm?.shippingData?.address?.postalCode &&\n ofData?.orderForm?.shippingData?.address?.postalCode?.indexOf('*') === -1\n ) {\n const [ofLongitude, ofLatitude] =\n ofData?.orderForm?.shippingData.address.geoCoordinates\n\n longitude = ofLongitude\n latitude = ofLatitude\n }\n\n if (!longitude || !latitude) {\n setState((prev) => ({\n ...prev,\n allLoaded: true,\n }))\n }\n\n getStores({\n variables: {\n latitude,\n longitude,\n filterByTag,\n },\n })\n }, [filterByTag, getStores, ofData])\n\n useEffect(() => {\n if (state.center || !data?.getStores?.items?.length) return\n\n const [firstResult] = data.getStores.items\n\n const { latitude, longitude } = firstResult.address.location\n\n const center = ofData?.orderForm?.shippingData?.address?.geoCoordinates ?? [\n longitude || long,\n latitude || lat,\n ]\n\n setState({\n ...state,\n center,\n })\n }, [data, lat, long, ofData, state])\n\n const stores =\n data?.getStores?.items.sort((a, b) => {\n if (a[sortBy] < b[sortBy]) {\n return -1\n }\n\n if (a[sortBy] > b[sortBy]) {\n return 1\n }\n\n return 0\n }) ?? []\n\n return (\n <div\n className={`flex flex-row ${handles.container}`}\n style={{\n maxHeight: 750,\n }}\n >\n <div className={`flex-col w-30 ${handles.storesListCol}`}>\n {(loading || ofLoading) && <Spinner />}\n {!loading && !!data && stores.length > 0 && (\n <div className={`overflow-auto h-100 ${handles.storesList}`}>\n <Listing items={stores} onChangeCenter={handleCenter} />\n {!state.allLoaded && (\n <span\n className={`mt2 link c-link underline-hover pointer ${handles.loadAll}`}\n role=\"button\"\n tabIndex={0}\n onClick={() => {\n handleLoadAll()\n }}\n onKeyDown={(e) => {\n if (e.key !== 'Enter' && e.key !== ' ') return\n e.preventDefault()\n handleLoadAll()\n }}\n >\n <FormattedMessage id=\"store/load-all\" />\n </span>\n )}\n </div>\n )}\n {!loading && !!data && stores.length === 0 && (\n <div className={handles.noResults}>\n <h3>\n <FormattedMessage id=\"store/none-stores\" />\n </h3>\n </div>\n )}\n </div>\n <div className={`flex-col w-70 ${handles.storesMapCol}`}>\n {!loading &&\n !!data &&\n stores.length > 0 &&\n state.center &&\n googleMapsKeys?.logistics?.googleMapsKey && (\n <Pinpoints\n apiKey={googleMapsKeys.logistics.googleMapsKey}\n className={handles.listingMapContainer}\n items={data.getStores.items}\n zoom={state.zoom}\n center={state.center}\n icon={icon}\n iconWidth={iconWidth}\n iconHeight={iconHeight}\n />\n )}\n </div>\n </div>\n )\n}\n\nexport default injectIntl(StoreList)\n\n```"
}
] |
code_store-locator_00fcf0a5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/StoreDescription.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport PropTypes from 'prop-types'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { useStoreGroup } from './StoreGroup'\n\nconst CSS_HANDLES = ['descriptionContainer', 'descriptionText'] as const\n\nconst StoreDescription: FC<StoreNameProps> = ({ text }) => {\n const handles = useCssHandles(CSS_HANDLES)\n const group = useStoreGroup()\n\n if (!group || !text) {\n return null\n }\n\n const parseText = (string: string) => {\n const { city, state } = group.address\n\n return string\n .replace(/{storeName}/gi, group.friendlyName)\n .replace(/{storeCity}/gi, city ?? '')\n .replace(/{storeState}/gi, state ?? '')\n }\n\n return (\n <div className={handles.descriptionContainer}>\n <div className={handles.descriptionText}>{parseText(text)}</div>\n </div>\n )\n}\n\ninterface StoreNameProps {\n text?: string\n}\n\nStoreDescription.propTypes = {\n text: PropTypes.string,\n}\n\nexport default StoreDescription\n\n```"
}
] |
code_store-locator_881d340f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/StoreAddress.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { defineMessages, WrappedComponentProps, injectIntl } from 'react-intl'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { useStoreGroup } from './StoreGroup'\n\nconst CSS_HANDLES = [\n 'addressContainer',\n 'addressLink',\n 'addressLabel',\n 'addressStoreAddressGroupA',\n 'addressStoreAddressNumber',\n 'addressStoreAddressStreet',\n] as const\n\nconst messages = defineMessages({\n address: {\n defaultMessage: 'Store address',\n id: 'store/address-label',\n },\n})\n\ninterface StoreAddressProps {\n label: string\n}\n\nconst StoreAddress: FC<StoreAddressProps & WrappedComponentProps> = ({\n label,\n intl,\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n\n const group = useStoreGroup()\n\n if (!group) {\n return null\n }\n\n const [lng, lat] = group.address.geoCoordinates\n\n return (\n <div className={handles.addressContainer}>\n <span className={`b ${handles.addressLabel}`}>\n {label ?? intl.formatMessage(messages.address)}\n </span>\n <a\n className={`${handles.addressLink} underline-hover no-underline`}\n target=\"_blank\"\n rel=\"noreferrer\"\n href={`https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`}\n >\n <br />\n <span className={handles.addressStoreAddressGroupA}>\n <span className={handles.addressStoreAddressNumber}>\n {group.address.number ? `${group.address.number} ` : ''}\n </span>\n <span\n className={handles.addressStoreAddressStreet}\n >{`${group.address.street}`}</span>\n </span>\n <br />\n {group.address.city ? `${group.address.city}` : ''}\n {group.address.state ? `, ${group.address.state}` : ''}\n {group.address.postalCode ? `, ${group.address.postalCode}` : ''}\n </a>\n </div>\n )\n}\n\nexport default injectIntl(StoreAddress)\n\n```"
}
] |
code_store-locator_34ceea90
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/package.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"store-locator\",\n \"version\": \"1.0.1\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"@react-google-maps/api\": \"^2.2.0\",\n \"apollo-client\": \"^2.6.8\",\n \"prop-types\": \"^15.7.2\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\",\n \"slugify\": \"^1.2.6\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.flex-layout\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.flex-layout@0.17.0/public/@types/vtex.flex-layout\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.130.0/public/@types/vtex.render-runtime\",\n \"vtex.rich-text\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.rich-text@0.14.0/public/@types/vtex.rich-text\",\n \"vtex.store\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store@2.120.0/public/@types/vtex.store\",\n \"vtex.store-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.142.6/public/@types/vtex.store-graphql\",\n \"vtex.store-sitemap\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-sitemap@2.13.9/public/@types/vtex.store-sitemap\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.0/public/@types/vtex.styleguide\"\n }\n}\n\n```"
}
] |
code_store-locator_17bbd3b6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/StoreGroup.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { FC, ReactNode } from 'react'\nimport React, { useContext, useState, useEffect } from 'react'\nimport { useLazyQuery } from 'react-apollo'\nimport { useRuntime, Helmet } from 'vtex.render-runtime'\n\nimport { OptionsContext } from './contexts/OptionsContext'\nimport GET_STORE from './queries/getStore.gql'\n\nconst DAYS = [0, 1, 2, 3, 4, 5, 6]\n\nconst StoreGroupContext = React.createContext<SpecificationGroup | undefined>(\n undefined\n)\n\ninterface StoreGroupProviderProps {\n group: SpecificationGroup\n hasPhone: boolean\n}\nconst StoreGroupProvider: FC<StoreGroupProviderProps> = ({\n group,\n children,\n hasPhone,\n}) => {\n return (\n <OptionsContext.Provider value={hasPhone}>\n <StoreGroupContext.Provider value={group}>\n {children}\n </StoreGroupContext.Provider>\n </OptionsContext.Provider>\n )\n}\n\ninterface StoreGroupProps {\n children: ReactNode\n title: string\n description: string\n imageSelector: string\n phoneSelector: string\n instructionsAsPhone?: boolean\n}\n\nconst getImages = (imageSelector: string) => {\n const images: string[] = []\n const elements: NodeListOf<HTMLImageElement> =\n document.querySelectorAll(imageSelector)\n\n if (elements.length) {\n for (let i = 0; i < elements.length; i++) {\n const { src } = elements[i]\n\n if (src) {\n images.push(src)\n }\n }\n }\n\n return images\n}\n\nconst textParser = (text: string, group: SpecificationGroup) => {\n const {\n friendlyName,\n address: { city, state },\n } = group\n\n return text\n .replace(/{storeName}/gi, friendlyName)\n .replace(/{storeCity}/gi, city ?? '')\n .replace(/{storeState}/gi, state ?? '')\n}\n\nconst buildDataType = (\n data: any,\n title: string,\n description: string,\n imageSelector: string,\n hasPhone: boolean\n) => {\n const [longitude, latitude] = data.address.geoCoordinates\n const weekDays = [\n 'Sunday',\n 'Monday',\n 'Tuesday',\n 'Wednesday',\n 'Thursday',\n 'Friday',\n 'Saturday',\n ]\n\n return {\n '@context': 'https://schema.org',\n '@type': 'Store',\n '@id': data.id,\n name: title,\n description,\n image: getImages(imageSelector),\n telephone: hasPhone ? data.instructions : '',\n address: {\n '@type': 'PostalAddress',\n streetAddress: `${data.address.number} ${data.address.street}`,\n addressLocality: data.address.city,\n addressRegion: data.address.state,\n postalCode: data.address.postalCode,\n addressCountry: data.address.country,\n },\n geo: {\n '@type': 'GeoCoordinates',\n latitude,\n longitude,\n },\n url: window.location.href,\n openingHoursSpecification: data.businessHours.map((curr: any) => {\n const [opensHour, opensMinute] = curr.openingTime.split(':')\n const [closesHour, closesMinute] = curr.closingTime.split(':')\n\n return {\n '@type': 'OpeningHoursSpecification',\n dayOfWeek: [weekDays[curr.dayOfWeek]],\n opens: `${opensHour}:${opensMinute}`,\n closes: `${closesHour}:${closesMinute}`,\n }\n }),\n }\n}\n\nconst StoreGroup: FC<StoreGroupProps> = ({\n children,\n title,\n description,\n imageSelector,\n phoneSelector,\n instructionsAsPhone,\n}) => {\n const { history } = useRuntime()\n const [pickupPoint, setPickupPoint] = useState<any>(null)\n const [parsedTitle, setParsedTitle] = useState<string>('')\n const [parsedDescription, setParsedDescription] = useState<string>('')\n const [getStore, { data, called }] = useLazyQuery(GET_STORE)\n\n if (history && !called) {\n const id = history.location.state.navigationRoute.params.store_id\n\n getStore({\n variables: {\n id,\n },\n })\n }\n\n if (pickupPoint?.id !== data?.pickupPoint.id) {\n const businessHours = DAYS.map((day) => {\n const openHours = data.pickupPoint.businessHours.find(\n (hours) => hours.dayOfWeek === day\n )\n\n if (!openHours) {\n return {\n closingTime: null,\n dayOfWeek: day,\n openingTime: null,\n }\n }\n\n return openHours\n })\n\n setPickupPoint({ ...data.pickupPoint, businessHours })\n }\n\n useEffect(() => {\n if (!pickupPoint) {\n return\n }\n\n const pageTitle = title\n ? textParser(title, pickupPoint)\n : pickupPoint.friendlyName\n\n const pageDescription = description\n ? textParser(description, pickupPoint)\n : ''\n\n setParsedTitle(pageTitle)\n setParsedDescription(pageDescription)\n }, [pickupPoint, title, description])\n\n return (\n <>\n {pickupPoint && (\n <Helmet>\n <title>{parsedTitle}</title>\n <meta name=\"description\" content={parsedDescription} />\n {!!imageSelector && (\n <script type=\"application/ld+json\">\n {JSON.stringify(\n buildDataType(\n data.pickupPoint,\n parsedTitle,\n parsedDescription,\n imageSelector,\n instructionsAsPhone ?? phoneSelector?.length > 0\n )\n )}\n </script>\n )}\n </Helmet>\n )}\n <StoreGroupProvider\n group={pickupPoint}\n hasPhone={instructionsAsPhone ?? phoneSelector.length > 0}\n >\n {children}\n </StoreGroupProvider>\n </>\n )\n}\n\nexport const useStoreGroup = () => {\n const group = useContext(StoreGroupContext)\n\n return group\n}\n\nStoreGroup.defaultProps = {\n title: '{storeName}',\n description: '',\n imageSelector: '',\n phoneSelector: '',\n instructionsAsPhone: false,\n}\n\nexport default StoreGroup\n\n```"
}
] |
code_store-locator_0ed05c7a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/StoreHours.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport React, { FC } from 'react'\nimport { defineMessages, WrappedComponentProps, injectIntl } from 'react-intl'\nimport PropTypes from 'prop-types'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { useStoreGroup } from './StoreGroup'\n\nconst messages = defineMessages({\n hoursLabel: {\n defaultMessage: 'Store hours',\n id: 'store/hours-label',\n },\n holidayLabel: {\n defaultMessage: 'Holidays',\n id: 'store/holidays-label',\n },\n storeClosed: {\n defaultMessage: 'Closed',\n id: 'store/store-closed',\n },\n '0': {\n defaultMessage: 'Sunday',\n id: 'store/day-of-week-sunday',\n },\n '1': {\n defaultMessage: 'Monday',\n id: 'store/day-of-week-monday',\n },\n '2': {\n defaultMessage: 'Tuesday',\n id: 'store/day-of-week-tuesday',\n },\n '3': {\n defaultMessage: 'Wednesday',\n id: 'store/day-of-week-wednesday',\n },\n '4': {\n defaultMessage: 'Thursday',\n id: 'store/day-of-week-thursday',\n },\n '5': {\n defaultMessage: 'Friday',\n id: 'store/day-of-week-friday',\n },\n '6': {\n defaultMessage: 'Saturday',\n id: 'store/day-of-week-saturday',\n },\n})\n\nconst CSS_HANDLES = [\n 'hoursContainer',\n 'hoursLabel',\n 'hourRow',\n 'dayOfWeek',\n 'divider',\n 'businessHours',\n] as const\n\nconst timeFormat = (time: string, format?: string) => {\n if (!time) {\n return ''\n }\n\n const [hour, minute] = time.split(':')\n\n if (format?.toLocaleLowerCase() === '12h') {\n return `${\n parseInt(hour, 10) > 12 ? parseInt(hour, 10) - 12 : hour\n }:${minute}${parseInt(hour, 10) >= 12 ? 'pm' : 'am'}`\n }\n\n return `${hour}:${minute}`\n}\n\nconst StoreHours: FC<WrappedComponentProps & StoreHoursProps> = ({\n label,\n format,\n businessHours,\n pickupHolidays,\n intl,\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n const group = useStoreGroup()\n\n if (!group) {\n return null\n }\n\n const displayHours = (item) => {\n const open = timeFormat(item.openingTime, format)\n const close = timeFormat(item.closingTime, format)\n\n if (!open && !close) {\n return intl.formatMessage(messages.storeClosed)\n }\n\n return `${open} - ${close}`\n }\n\n const displayHolidayDay = (item) => {\n const holiday = new Date(item.date)\n const dayOfWeek = holiday.getDay()\n const { locale } = intl\n const month = new Intl.DateTimeFormat(locale, {\n day: 'numeric',\n month: 'long',\n }).format(holiday)\n\n const today = new Date()\n\n if (today >= holiday) {\n return ``\n }\n\n return (\n <div className={`${handles.dayOfWeek} w-30`}>\n {intl.formatMessage(messages[dayOfWeek])}, {month}\n </div>\n )\n }\n\n const displayHolidayHours = (item) => {\n const open = timeFormat(item.hourBegin, format)\n const close = timeFormat(item.hourEnd, format)\n const holiday = new Date(item.date)\n\n holiday.setDate(holiday.getDate() + 1)\n const today = new Date()\n\n if (open === '' && close === '') {\n return (\n <div className={`${handles.businessHours} tc w-50`}>\n {intl.formatMessage(messages.storeClosed)}\n </div>\n )\n }\n\n if (today > holiday) {\n return ``\n }\n\n return (\n <div className={`${handles.businessHours} tc w-50`}>\n {open} - {close}\n </div>\n )\n }\n\n return (\n <div className={handles.hoursContainer}>\n <span className={`b ${handles.hoursLabel}`}>\n {label ?? intl.formatMessage(messages.hoursLabel)}\n </span>\n <br />\n {businessHours?.map((item: any, i: number) => {\n return (\n <div\n key={`hour_${i}`}\n className={`${handles.hourRow} mv1 flex flex-wrap`}\n >\n <div className={`${handles.dayOfWeek} w-30`}>\n {item.dayOfWeek}\n <span className={handles.divider}>:</span>\n </div>\n <div className={`${handles.businessHours} tc w-50`}>\n {item.openingTime} - {item.closingTime}\n </div>\n </div>\n )\n })}\n {!businessHours &&\n group.businessHours.map((item: any, i: number) => {\n return (\n <div\n key={`hour_${i}`}\n className={`${handles.hourRow} mv1 flex flex-wrap`}\n >\n <div className={`${handles.dayOfWeek} w-30`}>\n {intl.formatMessage(messages[item.dayOfWeek])}\n <span className={handles.divider}>:</span>\n </div>\n <div className={`${handles.businessHours} tc w-50`}>\n {displayHours(item)}\n </div>\n </div>\n )\n })}\n <br />\n <b>{intl.formatMessage(messages.holidayLabel)}</b>\n {!pickupHolidays &&\n group.pickupHolidays.map((item: any, i: number) => (\n <div\n key={`hour_${i}`}\n className={`${handles.hourRow} mv1 flex flex-wrap`}\n >\n {displayHolidayDay(item)}\n {displayHolidayHours(item)}\n </div>\n ))}\n </div>\n )\n}\n\ninterface StoreHoursProps {\n label?: string\n format?: string\n businessHours?: any\n pickupHolidays?: any\n}\n\nStoreHours.propTypes = {\n label: PropTypes.string,\n format: PropTypes.oneOf(['24h', '12h']),\n businessHours: PropTypes.arrayOf(\n PropTypes.shape({\n dayOfWeek: PropTypes.string,\n openingTime: PropTypes.string,\n closingTime: PropTypes.string,\n })\n ),\n pickupHolidays: PropTypes.arrayOf(\n PropTypes.shape({\n date: PropTypes.string,\n hourBegin: PropTypes.string,\n hourEnd: PropTypes.string,\n })\n ),\n intl: PropTypes.any,\n}\n\nexport default injectIntl(StoreHours)\n\n```"
}
] |
code_store-locator_392f6a40
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/StoreInstructions.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useContext } from 'react'\nimport { defineMessages, WrappedComponentProps, injectIntl } from 'react-intl'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { OptionsContext } from './contexts/OptionsContext'\nimport { useStoreGroup } from './StoreGroup'\n\nconst CSS_HANDLES = [\n 'instructionsContainer',\n 'instructionsLabel',\n 'instructionsText',\n 'instructionsLink',\n] as const\n\nconst messages = defineMessages({\n information: {\n defaultMessage: 'Information',\n id: 'store/information-label',\n },\n})\n\ninterface StoreInstructionsProps {\n label: string\n}\n\nconst StoreInstructions: FC<StoreInstructionsProps & WrappedComponentProps> = ({\n label,\n intl,\n}) => {\n const group = useStoreGroup()\n const hasPhone = useContext(OptionsContext)\n\n const handles = useCssHandles(CSS_HANDLES)\n\n if (!group?.instructions) {\n return null\n }\n\n return (\n <div className={handles.instructionsContainer}>\n <span className={handles.instructionsLabel}>\n {label ?? intl.formatMessage(messages.information)}\n </span>\n {hasPhone ? (\n <a\n className={`${handles.instructionsLink} underline-hover no-underline`}\n href={`tel:${group.instructions}`}\n >\n {group.instructions}\n </a>\n ) : (\n <span className={handles.instructionsText}>{group.instructions}</span>\n )}\n </div>\n )\n}\n\nexport default injectIntl(StoreInstructions)\n\n```"
}
] |
code_store-locator_59ac1c28
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/StoreMap.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { FC } from 'react'\nimport React from 'react'\nimport type { WrappedComponentProps } from 'react-intl'\nimport { injectIntl } from 'react-intl'\nimport { useQuery } from 'react-apollo'\n\nimport { useStoreGroup } from './StoreGroup'\nimport Map from './components/Map'\nimport GOOGLE_KEYS from './queries/GetGoogleMapsKey.graphql'\n\nconst DEFAULT = {\n WIDTH: '100%',\n HEIGHT: '200px',\n ZOOM: 14,\n}\n\ninterface StoreMapProps {\n width: string\n height: string\n icon?: string\n iconWidth?: number\n iconHeight?: number\n googleMapsKeys: any\n zoom: number\n}\n\nconst StoreMap: FC<StoreMapProps & WrappedComponentProps> = ({\n width,\n height,\n icon,\n iconWidth,\n iconHeight,\n zoom,\n}) => {\n const { data: googleMapsKeys } = useQuery(GOOGLE_KEYS, { ssr: false })\n const group = useStoreGroup()\n\n if (!group || !googleMapsKeys?.logistics?.googleMapsKey) {\n return null\n }\n\n return (\n <div style={{ height, width }}>\n <Map\n apiKey={googleMapsKeys.logistics.googleMapsKey}\n loadingElement={<div style={{ height: `100%` }} />}\n mapElement={<div style={{ height: `100%` }} />}\n icon={icon}\n iconWidth={iconWidth}\n iconHeight={iconHeight}\n center={group.address.geoCoordinates}\n zoom={zoom}\n />\n </div>\n )\n}\n\nStoreMap.defaultProps = {\n width: DEFAULT.WIDTH,\n height: DEFAULT.HEIGHT,\n zoom: DEFAULT.ZOOM,\n}\n\nexport default injectIntl(StoreMap)\n\n```"
}
] |
code_store-locator_a3a25736
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/store/blocks.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.storelocator\": {\n \"blocks\": [\"flex-layout.row#title\", \"flex-layout.row#container\"]\n },\n \"flex-layout.row#title\": {\n \"children\": [\"flex-layout.col#title\"]\n },\n \"flex-layout.row#container\": {\n \"children\": [\"store-list\"]\n },\n \"flex-layout.col#title\": {\n \"children\": [\"rich-text#title\"],\n \"props\": {\n \"blockClass\": \"title\",\n \"preventVerticalStretch\": true\n }\n },\n \"rich-text#title\": {\n \"props\": {\n \"text\": \"## Store Locator\"\n }\n },\n \"store.storedetail\": {\n \"blocks\": [\"flex-layout.row#titleStore\", \"store-group\"]\n },\n \"store-group\": {\n \"children\": [\"flex-layout.row#containerStore\"],\n \"props\": {\n \"title\": \"{storeName} Store\"\n }\n },\n \"flex-layout.row#titleStore\": {\n \"children\": [\"flex-layout.col#titleStore\"]\n },\n \"flex-layout.row#containerStore\": {\n \"children\": [\"flex-layout.col#detail\", \"flex-layout.col#store\"]\n },\n \"flex-layout.col#titleStore\": {\n \"children\": [\"rich-text#titleStore\"],\n \"props\": {\n \"blockClass\": \"title\",\n \"preventVerticalStretch\": true\n }\n },\n \"rich-text#titleStore\": {\n \"props\": {\n \"text\": \"## Store Detail\"\n }\n },\n \"flex-layout.col#detail\": {\n \"children\": [\n \"store-back-link\",\n \"store-map\",\n \"store-address\",\n \"store-hours\",\n \"store-instructions\"\n ],\n \"props\": {\n \"width\": \"30%\",\n \"preventVerticalStretch\": true\n }\n },\n \"flex-layout.col#store\": {\n \"children\": [\"store-name\"],\n \"props\": {\n \"width\": \"70%\"\n }\n },\n \"store-hours\": {\n \"props\": {\n \"label\": \"Business hours:\",\n \"format\": \"12h\"\n }\n },\n \"store-back-link\": {\n \"props\": {\n \"label\": \"Back to all stores\"\n }\n },\n \"store-instructions\": {\n \"props\": {\n \"label\": \"\"\n }\n }\n}\n\n```"
}
] |
code_store-locator_9b7bfc0c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/store/interfaces.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store-list\": {\n \"component\": \"List\"\n },\n \"store-group\": {\n \"component\": \"StoreGroup\",\n \"composition\": \"children\"\n },\n \"store-name\": {\n \"component\": \"StoreName\",\n \"composition\": \"children\"\n },\n \"store-description\": {\n \"component\": \"StoreDescription\",\n \"composition\": \"children\"\n },\n \"store-instructions\": {\n \"component\": \"StoreInstructions\",\n \"composition\": \"children\"\n },\n \"store-address\": {\n \"component\": \"StoreAddress\",\n \"composition\": \"children\"\n },\n \"store-back-link\": {\n \"component\": \"StoreBackLink\",\n \"composition\": \"children\"\n },\n \"store-hours\": {\n \"component\": \"StoreHours\",\n \"composition\": \"children\"\n },\n \"store-map\": {\n \"component\": \"StoreMap\",\n \"composition\": \"children\"\n },\n \"store.storelocator\": {},\n \"store.storedetail\": {}\n}\n\n```"
}
] |
code_store-locator_85725ef4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/store/routes.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.storelocator\": {\n \"path\": \"/stores\",\n \"isSitemapEntry\": true\n },\n \"store.storedetail\": {\n \"path\": \"/store/:slug/:store_id\",\n \"isSitemapEntry\": false\n }\n}\n\n```"
}
] |
code_store-locator_cc897fee
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/plugins/index.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n// / <reference types=\"cypress\" />\n// ***********************************************************\n// This example plugins/index.js can be used to load plugins\n//\n// You can change the location of this file or turn off loading\n// the plugins file with the 'pluginsFile' configuration option.\n//\n// You can read more here:\n// https://on.cypress.io/plugins-guide\n// ***********************************************************\n\n// This function is called when a project is opened or re-opened (e.g. due to\n// the project's config changing)\n\n/**\n * @type {Cypress.PluginConfig}\n */\n\nmodule.exports = (_on, _config) => {\n // `on` is used to hook into various events Cypress emits\n // `config` is the resolved Cypress config\n}\n\n```"
}
] |
code_store-locator_d9d32fa4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/integration/2.2.2-add_multiple_pickup_points_via_csv.spec.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { testSetup, updateRetry } from '../support/common/support'\n\nconst prefix = 'Verify Upload XLS File'\n\ndescribe('Adding Multiple pickup point', () => {\n // Load test setup\n testSetup()\n\n // If we upload this file cypress/fixtures/pickups.xls then it will create two pickup points\n // pickup example 1 & pickup example 2\n it(`${prefix} - Visit admin endpoint and upload file`, updateRetry(2), () => {\n cy.uploadXLS()\n })\n})\n\n```"
}
] |
code_store-locator_244a6f37
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/integration/wipe.spec.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { updateShippingPolicy } from '../support/graphql_testcase.js'\nimport { deleteAllPickupPoints } from '../support/api_testcase.js'\nimport data from '../support/shipping-policy.json'\nimport { testSetup } from '../support/common/support.js'\nimport { graphql } from '../support/common/graphql_utils.js'\n\ndescribe('Wipe the pickup points', () => {\n testSetup(false)\n\n deleteAllPickupPoints()\n\n // If we leave the shipping policy active then it is forcing us to use pickup points in checkout\n // So, make shipping policy as inactive\n it('Update shipping policy status to inactive', () => {\n graphql(\n updateShippingPolicy(data, { status: false, pickup: false }),\n (response) => {\n expect(response.status).to.equal(200)\n }\n )\n })\n})\n\n```"
}
] |
code_store-locator_9971f3b5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/integration/2.2.1-add_pickup_point.spec.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { testSetup, updateRetry } from '../support/common/support'\nimport { addPickUpPoint } from '../support/common.js'\nimport { pickupTestCase } from '../support/outputvalidation.js'\n\ndescribe('Adding Multiple pickup point', () => {\n // Load test setup\n testSetup()\n\n it('Adding PickUp Point', updateRetry(1), () => {\n addPickUpPoint(pickupTestCase.pickupPointName)\n })\n})\n\n```"
}
] |
code_store-locator_87442e30
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/integration/2.4-order_product_via_pick_up_store.spec.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { testSetup, updateRetry } from '../support/common/support'\nimport { pickupTestCase } from '../support/outputvalidation.js'\n\ndescribe('Test pickup in checkout with one of the pickup points created in 2.2 testcase', () => {\n // Load test setup\n testSetup()\n\n const { productName, postalCode } = pickupTestCase\n const prefix = 'Pickup In Store'\n\n it(`${prefix} - Adding product to cart`, updateRetry(2), () => {\n // Search the product\n cy.searchProduct(productName)\n // Add product to cart\n cy.addProduct(productName)\n })\n\n it(`In ${prefix} - Updating Shipping Information`, updateRetry(2), () => {\n // Update Shipping Section\n cy.updateShippingInformation({ postalCode, pickup: true, timeout: 12000 })\n })\n\n it(`In ${prefix} - Order the product using promisory`, updateRetry(2), () => {\n cy.orderProduct()\n })\n})\n\n```"
}
] |
code_store-locator_5caa1e10
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/integration/2.1.2-rest_graphql_apis.spec.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { testSetup, updateRetry } from '../support/common/support'\nimport {\n createPickupPointAPI,\n deletePickupPointAPI,\n getPickupPointByIdAPI,\n listallPickupPointsAPI,\n searchPickupPointAPI,\n updatePickupPointAPI,\n} from '../support/api_testcase.js'\nimport { restAPITestCase } from '../support/outputvalidation.js'\nimport data from '../support/shipping-policy.json'\nimport { updateShippingPolicy } from '../support/graphql_testcase'\nimport { logisticsCarrier } from '../support/app_list'\nimport { graphql } from '../support/common/graphql_utils'\n\n/*\nHow to get shippingPolicy Id?\n1. Go to /admin endpoint\n2. Search for shipping strategy and from search results click to open\n3. Edit any of the available shipping strategies\n4. Now in url, you will get admin/shipping-strategy/shipping-policy/?id=sha1920ede3r\n*/\n\nconst shippingPolicyId = 'sha1920ede3r'\n\nconst { pickupPoint1Payload, pickupPoint2Payload, pickupPoint3Payload } =\n restAPITestCase\n\ndescribe('Rest & Graphql API testcases', () => {\n testSetup()\n\n listallPickupPointsAPI()\n createPickupPointAPI(pickupPoint1Payload)\n updatePickupPointAPI(pickupPoint1Payload, pickupPoint2Payload)\n getPickupPointByIdAPI(pickupPoint2Payload)\n deletePickupPointAPI(pickupPoint2Payload)\n searchPickupPointAPI()\n createPickupPointAPI(pickupPoint3Payload)\n // Shipping policy should be updated to active\n // Then only we can use pickup in 2.4 testcase\n it(\n 'Update shipping policy status to active and enable pickup points',\n updateRetry(5),\n () => {\n cy.addDelayBetweenRetries(1000)\n graphql(\n logisticsCarrier,\n updateShippingPolicy(data, {\n status: true,\n pickup: true,\n }),\n (response) => {\n expect(response.status).to.equal(200)\n expect(response.body.data.updateShippingPolicy.id).to.equal(\n shippingPolicyId\n )\n }\n )\n }\n )\n})\n\n```"
}
] |
code_store-locator_f19ea2f3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/integration/2.5-inactive_pickup_scenarios.spec.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { testSetup, updateRetry } from '../support/common/support'\nimport {\n listallPickupPointsAPI,\n INTIAL_PICKUP_POINTS_ENV,\n updatePickupPointdata,\n} from '../support/api_testcase'\nimport { restAPITestCase } from '../support/outputvalidation.js'\nimport storelocatorSelectors from '../support/selectors.js'\nimport { clickLoadAllStores } from '../support/common.js'\nimport { graphql } from '../support/common/graphql_utils'\nimport { getStores } from '../support/graphql_testcase'\nimport { storeLocator } from '../support/app_list'\n\nconst { pickupPoint3Payload } = restAPITestCase\n\ndescribe('Inactive Pickup Points should not be visible in storefront', () => {\n testSetup()\n\n listallPickupPointsAPI()\n\n updatePickupPointdata(pickupPoint3Payload)\n\n it(\n `Verify the inactive pickup point \"${pickupPoint3Payload.name}\" is not visible in stores page`,\n updateRetry(3),\n () => {\n cy.getPickupPointItem().then((pickupCount) => {\n cy.visitStore()\n cy.get(storelocatorSelectors.StorePickUpPointList, {\n timeout: 8000,\n }).should('be.visible')\n clickLoadAllStores()\n cy.get(storelocatorSelectors.MoreItems, { timeout: 8000 }).should(\n 'have.length',\n pickupCount[INTIAL_PICKUP_POINTS_ENV] + 3\n )\n cy.get(storelocatorSelectors.StorePickUpPointList, {\n timeout: 8000,\n }).should('not.contain', `${pickupPoint3Payload.name}`)\n })\n }\n )\n\n it('verify getStores with latitude and longitude', updateRetry(5), () => {\n graphql(storeLocator, getStores(-22.94, -43.18), (response) => {\n cy.addDelayBetweenRetries(10000)\n expect(response.status).to.equal(200)\n const pickupPoints = response.body.data.getStores.items.map((p) =>\n p.name.includes('pickup example')\n )\n\n expect(pickupPoints.length).to.equal(2)\n })\n })\n\n it('verify getStores without latitude and longitude', updateRetry(5), () => {\n graphql(storeLocator, getStores(), (response) => {\n cy.addDelayBetweenRetries(4000)\n expect(response.status).to.equal(200)\n expect(response.body.data.getStores.items.length).to.not.equal(0)\n })\n })\n})\n\n```"
}
] |
code_store-locator_0271a15e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/integration/2.3-verify_pickup_points.spec.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { testSetup, updateRetry } from '../support/common/support'\nimport { verifyAllPickUpPoint } from '../support/common.js'\nimport { listallPickupPointsAPI } from '../support/api_testcase.js'\n\ndescribe('Verify all pickup points is displayed', () => {\n // Load test setup\n testSetup()\n\n listallPickupPointsAPI()\n it('Verify all pickup points is shown in stores', updateRetry(5), () => {\n cy.addDelayBetweenRetries(10000)\n verifyAllPickUpPoint()\n })\n})\n\n```"
}
] |
code_store-locator_1e92a316
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/integration/2.1.1-delete_pickup_points.spec.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { deleteAllPickupPoints } from '../support/api_testcase.js'\nimport { testSetup } from '../support/common/support.js'\n\ndescribe('Wipe the pickup points', () => {\n testSetup(false)\n\n deleteAllPickupPoints()\n})\n\n```"
}
] |
code_store-locator_e0b952fb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/support/selectors.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport default {\n AddPickUpButton: '.vtex-button .vtex-button__label div',\n SaveChanges: '.vtex-button > .vtex-button__label',\n ChangesSaved: 'div[class*=vtex-toast] .pr5',\n ListOfStores: '.overflow-auto > .list',\n LoadStores: 'span[class*=loadAll]',\n MoreItems: 'span[class*=addressListLink]',\n AddressContainer: 'div[class*=addressContainer]',\n BackToPickUpPoint: 'span[class*=backlink]',\n VtexButton: '.vtex-button',\n UploadInput: 'input[type=file]',\n CloseIcon: '.vtex-modal__close-icon',\n VtexAlert: '.vtex-alert .ph5',\n VtexStoreName: 'span[class*=addressStoreName]',\n HoursContainer: 'div[class*=hoursContainer]',\n SaveButton: '.flex.justify-end > .pb7 > .vtex-button > .vtex-button__label',\n StorePickUpPointList: '.overflow-auto > .list',\n PickupInStoresAddressLink: '.srp-address-title',\n PickupInStoresShowList: '#pkpmodal-show-list-btn',\n ShippingPolicyPickUpPointToggle: '#active',\n ShippingPolicySaveChanges:\n '.styleguide__floating-action-bar > :nth-child(2) > .vtex-button',\n PickUpModelSearch: 'form[class*=modalSearch] input',\n FindPickupLink: '#find-pickup-link',\n ShippingPolicyStatusToggle: '#isActive',\n ShippingPolicyActiveStatus:\n 'label[for=\"isActive\"] > div > div[class*=primary]',\n ShippingPolicyPickupPointStatus:\n 'label[for=\"active\"] > div > div[class*=primary]',\n FillInvoiceAddress: 'p[class*=omnishipping] ~ button[class*=omnishipping]',\n}\n\nexport function getAddressLink(index) {\n return `span[class*=addressListItem]:nth-child(${\n index + 1\n }) span[class*=addressListLink]`\n}\n\nexport function getPickupPoint(pickupPoint) {\n return `.pickupPoint-1_${pickupPoint}`\n}\n\n```"
}
] |
code_store-locator_e9899ef3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/support/app_list.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport default {\n storeLocator: 'vtex.store-locator',\n logisticsCarrier: 'vtex.logistics-carrier-graphql',\n}\n\n```"
}
] |
code_store-locator_550dfdbd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/support/shipping-policy.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"shippingPolicy\": {\n \"numberOfItemsPerShipment\": 1,\n \"id\": \"sha1920ede3r\",\n \"name\": \"Test Shipping\",\n \"shippingMethod\": \"Test\",\n \"carrierSchedule\": [\n {\n \"dayOfWeek\": 0,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 1,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 2,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 3,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 4,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 5,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 6,\n \"timeLimit\": \"23:59:59\"\n }\n ],\n \"pickupPointsSettings\": {\n \"pickupPointIds\": [\"1\"],\n \"pickupPointTags\": [],\n \"sellers\": []\n },\n \"shippingHoursSettings\": {\n \"shippingHours\": [\n {\n \"dayOfWeek\": 0,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 1,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 2,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 3,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 4,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 5,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 6,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n }\n ],\n \"acceptOrdersOutsideShippingHours\": true\n }\n }\n}\n\n```"
}
] |
code_store-locator_685be7fa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/support/index.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n// Import commands.js using ES2015 syntax:\nimport './common/commands'\nimport './common/api_commands'\nimport './commands'\n\n// Configure it to preserve cookies\nCypress.Cookies.defaults({\n preserve: /VtexIdclientAutCookie/,\n})\n\n```"
}
] |
code_store-locator_ca2a5d90
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/support/api_testcase.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { VTEX_AUTH_HEADER, FAIL_ON_STATUS_CODE } from './common/constants'\nimport { updateRetry } from './common/support'\nimport {\n getPickupPoints,\n createPickupPoint,\n updatePickupPoint,\n getPickupPointById,\n deletePickupPoint,\n searchPickupPoint,\n} from './apis'\n\nexport const INTIAL_PICKUP_POINTS_ENV = 'INTIAL_PICKUP_POINTS_ENV'\n\nconst FILTER_PICKUP_POINT_KEY = 'pickup example'\n\nexport function filterPickupPoint(response, filterByPickupExample = true) {\n return response.body.filter((b) =>\n filterByPickupExample\n ? b.name.includes(FILTER_PICKUP_POINT_KEY)\n : !b.name.includes(FILTER_PICKUP_POINT_KEY)\n )\n}\n\nexport function setIntialPickupPoints(response) {\n const pickupointsCount = filterPickupPoint(response, false).length\n\n cy.setPickupPointItem(INTIAL_PICKUP_POINTS_ENV, pickupointsCount)\n}\n\nexport function listallPickupPointsAPI() {\n it('List all pickup points via API', updateRetry(2), () => {\n cy.addDelayBetweenRetries(2000)\n cy.getVtexItems().then((vtex) => {\n cy.getAPI(getPickupPoints(vtex.baseUrl)).then((response) => {\n expect(response.status).to.equal(200)\n setIntialPickupPoints(response)\n })\n })\n })\n}\n\nexport function createPickupPointAPI(pickupPointPayload) {\n it(\n `Create a pickup point \"${pickupPointPayload.name}\" via API`,\n updateRetry(2),\n () => {\n cy.addDelayBetweenRetries(2000)\n cy.getVtexItems().then((vtex) => {\n cy.request({\n method: 'POST',\n url: createPickupPoint(vtex.baseUrl),\n headers: {\n ...VTEX_AUTH_HEADER(vtex.apiKey, vtex.apiToken),\n },\n body: pickupPointPayload,\n ...FAIL_ON_STATUS_CODE,\n }).then((response) => {\n cy.log(response)\n expect(response.status).to.equal(200)\n expect(response.body).to.have.property('name')\n expect(response.body).to.have.property('id')\n // In storelocators.json -> {pickup_point_name : response.body.id }\n cy.setPickupPointItem(pickupPointPayload.name, response.body.id)\n })\n })\n }\n )\n}\n\nexport function updatePickupPointAPI(\n currentPickupPointPayload,\n updatedPickupPointPayload\n) {\n it(\n `Update a pickup point \"${currentPickupPointPayload.name}\" payload with \"${updatedPickupPointPayload.name}\" payload via API`,\n updateRetry(2),\n () => {\n cy.addDelayBetweenRetries(2000)\n cy.getVtexItems().then((vtex) => {\n cy.getPickupPointItem().then((data) => {\n cy.request({\n method: 'POST',\n url: updatePickupPoint(vtex.baseUrl),\n headers: {\n ...VTEX_AUTH_HEADER(vtex.apiKey, vtex.apiToken),\n },\n body: updatedPickupPointPayload,\n qs: { id: data[currentPickupPointPayload.name] },\n\n ...FAIL_ON_STATUS_CODE,\n }).then((response) => {\n // In storelocators.json -> {pickup_point_name : response.body.id }\n cy.setPickupPointItem(\n updatedPickupPointPayload.name,\n response.body.id\n )\n expect(response.status).to.equal(200)\n expect(response.body).to.have.property(\n 'name',\n updatedPickupPointPayload.name\n )\n })\n })\n })\n }\n )\n}\n\nexport function getPickupPointByIdAPI(pickupPointPayload) {\n it(\n `List the pickup point by \"${pickupPointPayload.name}'s\" id via API`,\n updateRetry(2),\n () => {\n cy.addDelayBetweenRetries(2000)\n cy.getVtexItems().then((vtex) => {\n cy.getPickupPointItem().then((data) => {\n cy.getAPI(\n getPickupPointById(vtex.baseUrl, data[pickupPointPayload.name])\n ).then((response) => {\n expect(response.status).to.equal(200)\n expect(response.body).to.have.property('name')\n expect(response.body).to.have.property('id')\n })\n })\n })\n }\n )\n}\n\nexport function deletePickupPointAPI(pickupPointPayload) {\n it(\n `Delete a pickup point ${pickupPointPayload.name} via API`,\n updateRetry(2),\n () => {\n cy.addDelayBetweenRetries(2000)\n cy.getVtexItems().then((vtex) => {\n cy.getPickupPointItem().then((data) => {\n cy.request({\n method: 'DELETE',\n url: deletePickupPoint(vtex.baseUrl, data[pickupPointPayload.name]),\n headers: {\n ...VTEX_AUTH_HEADER(vtex.apiKey, vtex.apiToken),\n },\n ...FAIL_ON_STATUS_CODE,\n }).then((response) => {\n expect(response.status).to.equal(204)\n })\n })\n })\n }\n )\n}\n\nexport function deleteAllPickupPoints() {\n it(\n `Filter and delete pickup point which starts with \"${FILTER_PICKUP_POINT_KEY}\"`,\n updateRetry(5),\n () => {\n cy.getVtexItems().then((vtex) => {\n cy.getAPI(getPickupPoints(vtex.baseUrl)).then((response) => {\n // Pickup points created in E2E tests should start with text \"pickup example\"\n // If we create other pickup points then it will not be deleted in wipe\n const filterPickUpPoints = filterPickupPoint(response, true)\n\n if (filterPickUpPoints.length > 0) {\n for (const element of filterPickUpPoints) {\n cy.request({\n method: 'DELETE',\n url: deletePickupPoint(vtex.baseUrl, element.id),\n headers: {\n ...VTEX_AUTH_HEADER(vtex.apiKey, vtex.apiToken),\n },\n ...FAIL_ON_STATUS_CODE,\n }).then((deleteResponse) => {\n expect(deleteResponse.status).to.equal(204)\n })\n }\n }\n })\n })\n }\n )\n}\n\nexport function searchPickupPointAPI() {\n it('Search pickup points via API', updateRetry(2), () => {\n cy.addDelayBetweenRetries(2000)\n cy.getVtexItems().then((vtex) => {\n cy.request({\n method: 'GET',\n url: searchPickupPoint(vtex.baseUrl),\n headers: {\n ...VTEX_AUTH_HEADER(vtex.apiKey, vtex.apiToken),\n },\n qs: {\n page: 1,\n pageSize: 5,\n },\n ...FAIL_ON_STATUS_CODE,\n }).then((response) => {\n expect(response.status).to.equal(200)\n expect(response.body).to.have.property('paging')\n })\n })\n })\n}\n\nexport function updatePickupPointdata(pickupPointPayload) {\n it(\n `Update a pickup point \"${pickupPointPayload.name}\" as inactive`,\n updateRetry(2),\n () => {\n cy.addDelayBetweenRetries(2000)\n cy.getVtexItems().then((vtex) => {\n cy.getPickupPointItem().then((data) => {\n pickupPointPayload.isActive = false\n\n cy.request({\n method: 'POST',\n url: updatePickupPoint(vtex.baseUrl),\n headers: {\n ...VTEX_AUTH_HEADER(vtex.apiKey, vtex.apiToken),\n },\n body: pickupPointPayload,\n\n qs: { id: data[pickupPointPayload.name] },\n\n ...FAIL_ON_STATUS_CODE,\n }).then((response) => {\n expect(response.status).to.equal(200)\n expect(response.body).to.have.property('isActive', false)\n })\n })\n })\n }\n )\n}\n\n```"
}
] |
code_store-locator_5cd8a07a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/support/outputvalidation.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { PRODUCTS } from './common/utils.js'\n\nfunction generatePickupPoint(pickupPointName) {\n return {\n address: {\n country: {\n acronym: 'CAN',\n name: 'CANADA',\n },\n location: {},\n postalCode: '600079',\n city: 'TORONTO',\n state: 'ONTARIO',\n neighborhood: 'BOTAFOGO',\n street: '92 Rue de Strasbourg',\n number: '10025698',\n complement: '3 RD FLOOR',\n reference: 'GREY BUILDING',\n },\n businessHours: [\n {\n dayOfWeek: 1,\n openingTime: '08:00:00',\n closingTime: '20:00:00',\n },\n ],\n id: '45678',\n name: pickupPointName,\n description: 'do it',\n instructions: 'do it properly',\n formatted_address: 'undefined',\n isActive: true,\n }\n}\n\n// NOTE: pickup point name should starts with pickup example\n\nexport default {\n restAPITestCase: {\n pickupPoint1Payload: {\n address: {\n country: {\n acronym: 'IND',\n name: 'INDIA',\n },\n location: {},\n postalCode: '600077',\n city: 'france',\n state: 'TAMILNADU',\n neighborhood: 'BOTAFOGO',\n street: '92 Rue de Strasbourg',\n number: '10025698',\n complement: '3 RD FLOOR',\n reference: 'GREY BUILDING',\n },\n businessHours: [\n {\n dayOfWeek: 1,\n openingTime: '08:00:00',\n closingTime: '20:00:00',\n },\n ],\n id: '45678',\n name: 'pickup example puma',\n description: 'do it',\n instructions: 'do it properly',\n formatted_address: 'undefined',\n isActive: true,\n },\n pickupPoint2Payload: generatePickupPoint('pickup example walmart'),\n /*\n pickupPoint1 is created in cypress/integration/2.1.2-rest_graphql_apis.spec.js\n & in same testcase it is been replaced with pickupPoint2\n */\n pickupPoint3Payload: generatePickupPoint('pickup example adidas'),\n /*\n pickupPoint3 is created in cypress/integration/2.1.2-rest_graphql_apis.spec.js\n & will make it inactive in cypress/integration/2.5-inactive_pickup_scenarios.spec.js\n */\n },\n\n pickupTestCase: {\n productName: PRODUCTS.coconut,\n postalCode: '94536',\n // This pickup will be created in cypress/integration/2.2.2-add_multiple_pickup_points.spec.js\n // & it will be used in cypress/integration/2.4-order_product_via_pick_up_store.spec.js\n pickupPointName: 'pickup example reebok',\n },\n}\n\n```"
}
] |
code_store-locator_2794dd8a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/support/commands.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport 'cypress-file-upload'\nimport selectors from './common/selectors'\nimport storelocatorSelectors, { getAddressLink } from './selectors.js'\n\nconst storelocatorJson = '.storelocator.json'\nconst fileName = 'pickups.xls'\n\n// Save pickupPoint\nCypress.Commands.add(\n 'setPickupPointItem',\n (pickupPointItem, pickupPointValue) => {\n cy.readFile(storelocatorJson).then((items) => {\n items[pickupPointItem] = pickupPointValue\n cy.writeFile(storelocatorJson, items)\n })\n }\n)\n\n// Get pickupPoint\nCypress.Commands.add('getPickupPointItem', () => {\n cy.readFile(storelocatorJson).then((items) => {\n return items\n })\n})\n\nCypress.Commands.add('visitStore', () => {\n cy.intercept('**/event-api/v1/*/event').as('events')\n cy.visit('/api/io/stores')\n cy.wait('@events')\n\n cy.get(selectors.ProfileLabel, { timeout: 20000 })\n .should('be.visible')\n .should('have.contain', `Hello,`)\n})\n\nCypress.Commands.add('verifyPickupPointsInStore', () => {\n cy.getVtexItems().then((vtex) => {\n cy.intercept('POST', `${vtex.baseUrl}/**`, (req) => {\n if (req.body.operationName === 'Session') {\n req.continue()\n }\n }).as('Session')\n cy.visitStore()\n cy.wait('@Session', { timeout: 40000 })\n cy.get(storelocatorSelectors.LoadStores).should('be.visible').click()\n cy.get(storelocatorSelectors.VtexStoreName).contains('pickup example 1')\n cy.get(storelocatorSelectors.VtexStoreName).contains('pickup example 2')\n })\n})\n\nCypress.Commands.add('uploadXLS', () => {\n cy.visit('/admin/app/pickup-points')\n cy.get(storelocatorSelectors.VtexButton).first().should('be.visible')\n cy.contains('Upload a XLS').click()\n cy.get(storelocatorSelectors.UploadInput).attachFile(fileName)\n cy.get(storelocatorSelectors.CloseIcon).should('be.visible').click()\n cy.get(storelocatorSelectors.VtexAlert, { timeout: 15000 }).should(\n 'be.visible'\n )\n})\n\nCypress.Commands.add('verifyDetailsInDetailPage', () => {\n cy.get(storelocatorSelectors.VtexStoreName).then(($els) => {\n const storeLocatorsNames = [...$els].map((el) => el.innerText)\n const indexOfNsmr = storeLocatorsNames.indexOf('pickup example 2')\n\n cy.get(getAddressLink(indexOfNsmr)).click()\n cy.get(storelocatorSelectors.HoursContainer).should('be.visible')\n })\n})\n\n```"
}
] |
code_store-locator_9fdec144
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/support/common.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { updateRetry } from './common/support'\nimport storeLocatorSelectors from './selectors.js'\nimport { INTIAL_PICKUP_POINTS_ENV } from './api_testcase'\nimport selectors from './common/selectors'\n\nexport function addPickUpPoint(pickPointName) {\n cy.visit('/admin/app/pickup-points')\n\n cy.get(storeLocatorSelectors.AddPickUpButton)\n .contains('Add Pickup Point')\n .click()\n cy.get(selectors.PickUpPointName).clear().type(pickPointName)\n cy.get(selectors.PickUpPointId).should('be.visible').type('1')\n cy.get('select')\n .select('United States of America')\n .should('have.value', 'USA')\n /* eslint-disable cypress/no-unnecessary-waiting */\n cy.wait(1000)\n /* eslint-disable cypress/no-unnecessary-waiting */\n cy.get(selectors.PickUpAddress)\n .type('1279 Shinn Street Fremont CA,USA', { delay: 50 })\n .wait(500)\n .type('{downarrow}{enter}')\n cy.get(selectors.CheckBox).click()\n cy.get(selectors.WorkStartTime).eq(1).type('10:00')\n cy.get(selectors.WorkEndTime).eq(1).type('19:00')\n cy.get(storeLocatorSelectors.SaveChanges).contains('Save Changes').click()\n cy.get(storeLocatorSelectors.ChangesSaved, { timeout: 10000 })\n .should('be.visible')\n .contains('Changes saved')\n}\n\nexport function clickLoadAllStores() {\n cy.get('body').then(($body) => {\n if ($body.find(storeLocatorSelectors.LoadStores).length) {\n cy.get(storeLocatorSelectors.LoadStores, { timeout: 15000 })\n .should('be.visible')\n .click()\n }\n })\n}\n\nexport function verifyAllPickUpPoint() {\n cy.visitStore()\n cy.get(storeLocatorSelectors.ListOfStores).should('be.visible')\n clickLoadAllStores()\n\n cy.getPickupPointItem().then((pickupCount) => {\n cy.get(storeLocatorSelectors.MoreItems).should(\n 'have.length',\n pickupCount[INTIAL_PICKUP_POINTS_ENV] + 4\n )\n cy.get(storeLocatorSelectors.MoreItems)\n .its('length')\n .then((itemLen) => {\n for (let i = 0; i < itemLen; i++) {\n clickLoadAllStores()\n cy.get(storeLocatorSelectors.MoreItems)\n .eq(i)\n .scrollIntoView()\n .should('be.visible')\n .click()\n cy.get(storeLocatorSelectors.AddressContainer, {\n timeout: 20000,\n }).should('be.visible')\n cy.get(storeLocatorSelectors.HoursContainer).should('be.visible')\n cy.get(storeLocatorSelectors.BackToPickUpPoint)\n .should('be.visible')\n .click()\n cy.get(storeLocatorSelectors.MoreItems).should('be.visible')\n }\n })\n })\n}\n\nexport function updateShippingPolicyStatus(status) {\n it('Link pickup point', updateRetry(2), () => {\n cy.visit('/admin/app/shipping-strategy/shipping-policy/?id=sha1920ede3r')\n cy.get('#name').should('be.visible')\n cy.get('body').then(($body) => {\n if (\n $body.find(storeLocatorSelectors.ShippingPolicyActiveStatus).length > 0\n ) {\n if (status === true) {\n cy.log('Shipping policy already in active status')\n } else {\n cy.get(storeLocatorSelectors.ShippingPolicyStatusToggle).click()\n cy.get(storeLocatorSelectors.ShippingPolicySaveChanges).click()\n }\n } else if (status === true) {\n cy.get(storeLocatorSelectors.ShippingPolicyStatusToggle).click()\n cy.get(storeLocatorSelectors.ShippingPolicySaveChanges).click()\n } else {\n cy.log('Shipping policy already in inactive status')\n }\n })\n })\n}\n\n```"
}
] |
code_store-locator_b0088308
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/support/apis.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport default {\n getPickupPoints: (baseUrl) => {\n return `${baseUrl}/api/logistics/pvt/configuration/pickuppoints`\n },\n createPickupPoint: (baseUrl) => {\n return `${baseUrl}/api/logistics/pvt/configuration/pickuppoints`\n },\n updatePickupPoint: (baseUrl) => {\n return `${baseUrl}/api/logistics/pvt/configuration/pickuppoints`\n },\n getPickupPointById: (baseUrl, pickupPointid) => {\n return `${baseUrl}/api/logistics/pvt/configuration/pickuppoints/${pickupPointid}`\n },\n deletePickupPoint: (baseUrl, pickupPointid) => {\n return `${baseUrl}/api/logistics/pvt/configuration/pickuppoints/${pickupPointid}`\n },\n searchPickupPoint: (baseUrl) => {\n return `${baseUrl}/api/logistics/pvt/configuration/pickuppoints/_search`\n },\n}\n\n```"
}
] |
code_store-locator_90cdc3d8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/cypress/support/graphql_testcase.js from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport function updateShippingPolicy(data, { status = false, pickup = true }) {\n data.shippingPolicy.isActive = status\n data.shippingPolicy.deliveryChannel = pickup ? 'pickup-in-point' : 'delivery'\n const query =\n 'mutation' +\n '( $shippingPolicy: ShippingPolicyInput!)' +\n '{updateShippingPolicy(shippingPolicy:$shippingPolicy){id, name}}'\n\n return {\n query,\n queryVariables: data,\n }\n}\n\nexport function getStores(latitude, longitude) {\n const query =\n 'query' +\n '( $latitude: Float, $longitude: Float )' +\n '{getStores(latitude:$latitude,longitude:$longitude){items{id name instructions isActive address{postalCode country city state location{latitude longitude}} businessHours{dayOfWeek openingTime closingTime} pickupHolidays{date hourBegin hourEnd}}}}'\n\n return {\n query,\n queryVariables: { latitude, longitude },\n }\n}\n\n```"
}
] |
code_store-locator_971e99cf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/public/metadata/messages/es-AR.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Store Locator\",\n \"headline\": \"Muestra las tiendas comerciales según los puntos de recogida.\",\n \"overview\": \"La aplicación Store Locator obtiene los datos del punto de recogida para mostrar la ubicación de la dirección de las tiendas minoristas.\",\n \"features\": [\n \"Importar automáticamente ubicaciones y su información desde el punto de recogida\",\n \"Generar páginas y rutas para cada tienda\",\n \"Un puñado de \\\"bloques\\\" para usar en cualquier plantilla\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://help-tickets.vtex.com/en/support?app=vtex.store-locator\"\n }\n}\n\n```"
}
] |
code_store-locator_9db8e0df
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/public/metadata/messages/pt-BR.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Store Locator\",\n \"headline\": \"Exibe mapa de lojas com base nos pickup points.\",\n \"overview\": \"O aplicativo Store Locator busca os dados do pickup points para exibir a localização das lojas.\",\n \"features\": [\n \"Importa automaticamente os locais e suas informações do pickup points\",\n \"Gera páginas e rotas para cada loja\",\n \"Gera \\\"blocos\\\" para usar em qualquer modelo no template\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://help-tickets.vtex.com/en/support?app=vtex.store-locator\"\n }\n}\n\n```"
}
] |
code_store-locator_437efb16
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/public/metadata/messages/en-US.json from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Store Locator\",\n \"headline\": \"Displays merchant stores based on the pickup points.\",\n \"overview\": \"The Store Locator app fetches the pickup point data in order to display address location for retail stores.\",\n \"features\": [\n \"Automatically import locations and its info from the pickup point\",\n \"Generate pages and routes for each store\",\n \"Handful \\\"blocks\\\" to use in any template\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://help-tickets.vtex.com/en/support?app=vtex.store-locator\"\n }\n}\n\n```"
}
] |
code_store-locator_ac2b548b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/node/clients/index.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport RequestHub from '../utils/Hub'\nimport Sitemap from '../utils/Sitemap'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get hub() {\n return this.getOrSet('hub', RequestHub)\n }\n\n public get sitemap() {\n return this.getOrSet('sitemap', Sitemap)\n }\n}\n\n```"
}
] |
code_store-locator_9fba96d5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/node/utils/Binding.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { TenantClient } from '@vtex/api'\n\nexport const TENANT_CACHE_TTL_S = 60 * 10\nexport const STORE_PRODUCT = 'vtex-storefront'\n\nexport const getStoreBindings = async (tenant: TenantClient) => {\n const { bindings } = await tenant.info({\n forceMaxAge: TENANT_CACHE_TTL_S,\n })\n\n const storeBindings = bindings.filter(\n (binding) => binding.targetProduct === STORE_PRODUCT\n )\n\n return storeBindings\n}\n\n```"
}
] |
code_store-locator_cb842295
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/node/utils/Hub.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nconst BASE_PATH =\n 'http://logistics.vtexcommercestable.com.br/api/logistics/pvt/configuration/pickuppoints/'\n\nconst routes = {\n getAll: (\n { keyword, latitude, longitude, page = 1 }: any,\n account: string\n ) => {\n let path = `_search?an=${account}`\n\n if (keyword) {\n path += `&keyword=${keyword}`\n } else if (latitude && longitude) {\n path = `_searchsellers?an=${account}&lat=${Number(latitude).toFixed(\n 2\n )}&lon=${Number(longitude).toFixed(2)}&maxDistance=200`\n }\n\n path += `&pageSize=100&page=${page}`\n\n return `${BASE_PATH}${path}`\n },\n}\n\nexport default class RequestHub extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super('', context, {\n ...options,\n headers: {\n Accept: 'application/json',\n 'Proxy-Authorization': context.authToken,\n Authorization: context.authToken,\n VtexIdclientAutCookie: context.authToken,\n },\n })\n }\n\n public getStores(data: any) {\n return this.http.getRaw(routes.getAll(data, this.context.account))\n }\n}\n\n```"
}
] |
code_store-locator_c01516e9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/node/utils/Sitemap.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { AppGraphQLClient } from '@vtex/api'\n\nconst saveIndexMutation = `mutation SaveIndex($index: String!) {\n saveIndex(index: $index)\n}`\n\nexport default class Sitemap extends AppGraphQLClient {\n constructor(ctx: IOContext, opts?: InstanceOptions) {\n super('vtex.store-sitemap@2.x', ctx, opts)\n }\n\n public hasSitemap() {\n return this.http\n .get(\n `http://${this.context.workspace}--${this.context.account}.myvtex.com/sitemap.xml`\n )\n .then((ret: string) => ret.indexOf('store-locator') !== -1)\n }\n\n public async saveIndex() {\n const { tenant } = this.context\n\n return this.graphql.mutate(\n {\n mutate: saveIndexMutation,\n variables: { index: 'store-locator' },\n },\n {\n headers: {\n ...this.options?.headers,\n 'Proxy-Authorization': this.context.authToken,\n VtexIdclientAutCookie: this.context.authToken,\n 'x-vtex-tenant': tenant,\n },\n metric: 'storelocator-save-root-index',\n }\n )\n }\n}\n\n```"
}
] |
code_store-locator_4bc13bb4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/node/utils/GraphQLError.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport default class GraphQLError extends Error {\n public extensions: any\n\n constructor(message: string, details?: any) {\n super(message)\n this.extensions = { message, ...details }\n }\n}\n\n```"
}
] |
code_store-locator_5fd7de0e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/node/graphql/index.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable vtex/prefer-early-return */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { method } from '@vtex/api'\nimport slugify from 'slugify'\n\nimport { getStoreBindings } from '../utils/Binding'\n\nconst Slugify = (str: string) => {\n return slugify(str, { lower: true, remove: /[*+~.()'\"!:@]/g })\n}\n\nconst stripTrailingSlash = (str: string) => {\n return str.endsWith('/') ? str.slice(0, -1) : str\n}\n\nexport const resolvers = {\n Routes: {\n getSitemap: [\n method({\n GET: async (ctx: Context) => {\n const {\n clients: { tenant },\n vtex: { logger },\n } = ctx\n\n try {\n const stores: any = await resolvers.Query.getStores(\n null,\n {\n keyword: null,\n latitude: null,\n longitude: null,\n },\n ctx\n ).catch((error) => {\n logger.error({ error, message: 'getSitemap-getStores-error' })\n\n return null\n })\n\n const [storeBindings] = await getStoreBindings(tenant)\n\n const { canonicalBaseAddress } = storeBindings\n const baseUrl =\n canonicalBaseAddress.indexOf('myvtex') === -1\n ? String(canonicalBaseAddress)\n : String(ctx.vtex.host)\n\n const lastMod = new Date().toISOString()\n const storesMap = `\n <urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n ${stores?.items\n .filter((item: any) => {\n return !!item.isActive\n })\n .map((item: any) => {\n return `<url>\n <loc>https://${stripTrailingSlash(baseUrl)}/store/${Slugify(\n `${item.name} ${item.address.state} ${item.address.postalCode}`\n )}/${String(item.id).replace('1_', '')}</loc>\n <lastmod>${lastMod}</lastmod>\n <changefreq>daily</changefreq>\n <priority>0.8</priority>\n </url>`\n })\n .join('')}\n </urlset>`\n\n ctx.set('Content-Type', 'text/xml')\n ctx.body = storesMap\n ctx.status = 200\n } catch (e) {\n ctx.body = e\n ctx.status = 500\n }\n },\n }),\n ],\n },\n Query: {\n getStores: async (_: any, param: any, ctx: Context) => {\n const {\n clients: { hub, sitemap, vbase },\n vtex: { logger },\n } = ctx\n\n const APP_NAME = 'store-locator'\n const SCHEMA_NAME = 'sitemap'\n\n const saveInVbase = async () => {\n try {\n const res: any = await sitemap.saveIndex()\n\n if (res?.data?.saveIndex) {\n await vbase.saveJSON(APP_NAME, SCHEMA_NAME, {\n alreadyHasSitemap: true,\n })\n\n return true\n }\n\n return false\n } catch (err) {\n logger.error({ error: err, message: 'getStores-saveInBase-error' })\n\n return false\n }\n }\n\n sitemap.hasSitemap().then((has: any) => {\n if (has === false) {\n vbase\n .getJSON(APP_NAME, SCHEMA_NAME, true)\n .then((getResponse: any) => {\n const { alreadyHasSitemap = false } = getResponse ?? {}\n\n !alreadyHasSitemap && saveInVbase()\n })\n .catch((err: any) =>\n logger.error({ error: err, message: 'getStores-getJSON-error' })\n )\n }\n })\n\n let result = await hub.getStores(param).catch((error) => {\n logger.error({\n error,\n message: 'getStores-error',\n param,\n })\n\n return null\n })\n\n if (!result?.data.length && !param.keyword) {\n result = await hub.getStores({}).catch((error) => {\n logger.error({\n error,\n message: 'getStores-error',\n param: {},\n })\n\n return null\n })\n }\n\n // accounts for different reponse structure for Logistics _search and _searchsellers endpoints\n const {\n data,\n data: { paging = { pages: 0 } },\n } = result ?? { data: { items: [], paging: { pages: 0 } } }\n\n const pickuppoints = data.items ? data : { items: data }\n\n const results = [] as any\n\n // API will return errors starting at ?page=100\n const limitPagesTo99 = paging.pages > 99 ? 99 : paging.pages\n\n for (let i = 2; i <= limitPagesTo99; i++) {\n results.push(\n hub.getStores({ ...param, page: i }).catch((error) => {\n logger.error({\n error,\n message: 'getStores-error',\n param: { ...param, page: i },\n })\n\n return null\n })\n )\n }\n\n const remainingData = await Promise.all(results)\n\n remainingData.forEach((newResult: any) => {\n pickuppoints.items.push(...newResult.data.items)\n })\n\n // include for usage statistics\n logger.info({ message: 'getStores', items: pickuppoints?.items?.length })\n\n return {\n items: pickuppoints.items\n .map((item: any) => {\n return {\n ...item,\n address: {\n ...item.address,\n country: item.address.acronym,\n },\n }\n })\n .filter((item: any) => {\n return !!item.isActive\n }),\n }\n },\n },\n}\n\n```"
}
] |
code_store-locator_8fb20576
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/contexts/OptionsContext.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nexport const OptionsContext = React.createContext(false)\n\n```"
}
] |
code_store-locator_67c7cbd6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/typings/global.d.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface BusinessHours {\n openingTime: string\n dayOfWeek: string\n closingTime: string\n}\ninterface HolidayHours {\n date: string\n hourBegin: string\n hourEnd: string\n}\ninterface Address {\n addressId: string\n cacheId: string\n id: string\n userId: string\n receiverName: string\n complement: string\n neighborhood: string\n country: string\n state: string\n number: string\n street: string\n geoCoordinates: [number, number]\n postalCode: string\n city: string\n reference: string\n addressName: string\n addressType: string\n}\ninterface SpecificationGroup {\n businessHours: [BusinessHours]\n pickupHolidays: [HolidayHours]\n isActive: boolean\n distance: number\n friendlyName: string\n id: string\n instructions: string\n seller: string\n address: Address\n}\n\n```"
}
] |
code_store-locator_0fc0ad63
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/typings/graphql.d.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\ndeclare module '*.gql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```"
}
] |
code_store-locator_f120345e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/typings/vtex.styleguide.d.ts from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n export const PageHeader\n export const Alert\n export const Modal\n export const Box\n export const Card\n export const Checkbox\n export const Dropdown\n export const Spinner\n export const Table\n export const Button\n export const ButtonPlain\n export const IconWarning\n export const IconCheck\n export const Input\n export const InputButton\n export const InputSearch\n export const IconCaretDown\n export const IconCaretUp\n export const IconArrowDown\n export const IconArrowBack\n export const IconArrowUp\n export const IconClose\n export const IconExternalLink\n export const IconSearch\n export const IconSuccess\n export const IconCopy\n export const IconCog\n export const Tooltip\n export const ToastConsumer\n export const ToastProvider\n export const withToast\n export const ButtonWithIcon\n export const Pagination\n export const Collapsible\n export const Textarea\n export const NumericStepper\n export const EmptyState\n export const Tab\n export const Tag\n export const Toggle\n export const Layout\n export const Tabs\n export const Divider\n export const ModalDialog\n export const PageBlock\n}\n\n```"
}
] |
code_store-locator_2e1cfc70
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/queries/getStores.gql from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery getStores($latitude: Float, $longitude: Float, $filterByTag: String) {\n getStores(latitude: $latitude, longitude: $longitude, keyword: $filterByTag)\n @context(provider: \"vtex.store-locator\") {\n items {\n distance\n name\n instructions\n id\n isActive\n address {\n postalCode\n country\n city\n state\n neighborhood\n street\n number\n complement\n reference\n location {\n latitude\n longitude\n }\n }\n pickupHolidays {\n date\n hourBegin\n hourEnd\n }\n businessHours {\n dayOfWeek\n openingTime\n closingTime\n }\n }\n }\n}\n\n```"
}
] |
code_store-locator_2d13f5dc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/queries/orderForm.gql from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery {\n orderForm @context(provider: \"vtex.store-graphql\") {\n shippingData {\n address {\n postalCode\n geoCoordinates\n }\n }\n }\n}\n\n```"
}
] |
code_store-locator_fb0a85ce
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/queries/getStore.gql from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery getStore($id: String!) {\n pickupPoint(id: $id) @context(provider: \"vtex.store-graphql\") {\n businessHours {\n openingTime\n dayOfWeek\n closingTime\n }\n pickupHolidays {\n date\n hourBegin\n hourEnd\n }\n isActive\n distance\n friendlyName\n id\n instructions\n seller\n address {\n addressId\n cacheId\n id\n userId\n receiverName\n complement\n neighborhood\n country\n state\n number\n street\n geoCoordinates\n postalCode\n city\n reference\n addressName\n addressType\n }\n }\n}\n\n```"
}
] |
code_store-locator_262d67d3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/queries/GetGoogleMapsKey.graphql from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery getGoogleMapsKey {\n logistics @context(provider: \"vtex.store-graphql\") {\n googleMapsKey\n }\n}\n\n```"
}
] |
code_store-locator_89ca9722
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/components/Pinpoints.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable jsx-a11y/click-events-have-key-events */\n/* eslint-disable jsx-a11y/no-static-element-interactions */\nimport React, { useState } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport {\n GoogleMap,\n Marker,\n InfoWindow,\n useJsApiLoader,\n} from '@react-google-maps/api'\nimport slugify from 'slugify'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { useCssHandles } from 'vtex.css-handles'\n\nconst Slugify = (str: string) => {\n return slugify(str, { lower: true, remove: /[*+~.()'\"!:@]/g })\n}\n\nconst CSS_HANDLES = [\n 'markerInfo',\n 'markerInfoStoreName',\n 'markerInfoAddress',\n 'markerInfoLink',\n] as const\n\n// let initialLoad = false\nconst Pinpoints = (props: any) => {\n const { isLoaded } = useJsApiLoader({\n id: 'google-map-script',\n googleMapsApiKey: props.apiKey,\n })\n\n const [state, setState] = useState({\n markerState: {},\n })\n\n const handles = useCssHandles(CSS_HANDLES)\n\n const { navigate } = useRuntime()\n\n const handleMarkState = (id: string) => {\n const markerState = !state.markerState[id]\n ? {\n [id]: true,\n }\n : {}\n\n setState({\n markerState,\n })\n }\n\n const [lng, lat] = props.center\n const { zoom } = props\n\n const goTo = (item: any) => {\n const { state: _state, postalCode } = item.address\n\n navigate({\n page: 'store.storedetail',\n params: {\n slug: `${Slugify(`${item.name} ${_state} ${postalCode}`)}`,\n store_id: String(item.id).replace('1_', ''),\n },\n })\n }\n\n let icon: any = {\n url:\n props.icon ??\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAANbY1E9YMgAABPBJREFUWIWtl3tMW1Ucxw+0hfEorwIDhdFSKJRnaSnl0ZZXKa9CC4wCo1RhPESWuUQTFd2cuKiJ07hItrnBmFFnXOaymZllWZwic1uMYzGZyZZgMrc/xCnExCjh1Z+/c90qwr0Tj5J8cnO59/zO9/7O9/x+pwQACB8/dzjIrLuB3G6zkfM1xeSdEgN5WZ8lcicrDIkhwYM+Pj4jhJCjxIeMKEKCdzoT4wtfM2SLjxTnkbPVZvI9jqPjaRyhOSiCD+4LuIOBvqwvJ7u06TmxQYHnxL6+SzmR4dCZkgg7MlTQhVddVASIRaLl2KCAC89q1IZxWykn/H8RMOt2kGc06kfwa+cbFHHwTaMVPD1OgMe2ePH0tMC3TVXQqkzAiGTpiQxV/8y98f9JwHzXZrI3X9OJQeGIOQ+gHyfsawXPVicsbW32sozQ/9PnH5QVAC4PvJSbOUDHMwv4wVVPzlSacnHyhaMlBoCBdm6ipQfACRlwwXFLIc2E54Sl0DSNcZgEXG2wkmxZ2LlGTDv0//PkK4HH28GtUoAqVDrxld0iZhLwqj7LJPL1hWtNlQC9reuenBPQ2wI3W2pBIvKFndq0SiYBmsjw5zNl4Vyw1V9/qb4cHkX3ywIDuCu95/OEIToSkkOlQ0wC8O+wE11NjbX6C+mkYrHYC71fkwUc15WaSAONsAoY605V8gqgX75SAL3nE7AjK4UGGmMVcLBBEc/tc9YMuFRyGugQkwBTbNRTyWFSWO52snkAvZOFHtJGRTzHJGC4SKfFgjI/XleOhmr7d7sADfh1g5UWJM/e/Gwjk4CLdWXEGBN1zBQThcvQBp5u57omX+7+M/1V8bG0R5wet5WxFaLpdjvB1Cr9RaLZodwMLuh6ihEtWq/nawBryK+f2UrT7mIcJgEzXC9opm3Ygkaa21eo5d0Rq403WpxHjbd4wKirW8BeMMPaC+hAygKKOGTSN9GGdKbKzC0H/7q3wQSakTYizEDn/UbE3oza673MdW4m29KTd8s2+MN0hwMA2+/fJkd//N7VDMqQYGhPShimon9yOchdl52DScCtVpuX22115M6WOlFKWMjl9iT5mtpAU48HFgj39/vuelNV6K3WWjLVUuOFScAkdsOV3GiupktRRpdisvGvBgV4OPkRsxKIBWm3LqNryllDruH7K2EScKG2ZA1X7BaikYV/4lRu8maBfv0redkQ4e93E7eu/2V8hx7hVsJcB1Zz1VFB3izIqcCtCbgknBcWcd8rpEHQp1Y+OdloJV/ge6thEnDaalzDx8gpq1Ei9ZNM4XJwp59Ldgvd83OnrEUJVxzl5GJ92RqYBBwvL+AFj2mk9KHot2ilg+1uPHCkg1waNEGX6GyVmRcmAaNmPS/vlRrI9gxVdVTABlhEDxRsjAS7/OHBkxVF+CyfFyYBh016XkbNeeSN/JzYQIn4t89tpbARO+KgJs34Pk40hj9K+GAS8KIug5ehe2BRuvG0Rg14/WVfgVZGhQmJZhLwgjZdkD25mSQxRPqpPloGm4KDrr+Np/eDRh05IACTgF61UhAsywQPmx8GSSSQFCo9jz9CCJpRECYBPalKQQbSkkmWLGw/rYrykOCPXMly0qLcJAiTgP2YOiGosezyuF1UQEVczPAxNKDQrqEwCaCuFuKkpYj0qZPcVECHSr7tREUheRe3pxAPEvAHoSjT1B9h9DoAAAAASUVORK5CYII=',\n }\n\n if (props.iconWidth && props.iconHeight) {\n icon = {\n ...icon,\n scaledSize: {\n width: props.iconWidth,\n height: props.iconHeight,\n },\n }\n }\n\n if (!isLoaded) return null\n\n return (\n <GoogleMap\n zoom={zoom}\n center={{ lat, lng }}\n mapContainerStyle={{ height: '100%' }}\n mapContainerClassName={props.className}\n >\n {props.items.map((item: any, i: number) => {\n const { latitude, longitude } = item.address.location\n\n return (\n <Marker\n key={`marker_${i}`}\n icon={icon}\n position={{ lat: latitude, lng: longitude }}\n onClick={() => {\n handleMarkState(item.id)\n }}\n >\n {state.markerState[item.id] && (\n // ||\n // (Object.getOwnPropertyNames(state.markerState).length === 0 &&\n // lat === latitude &&\n // lng === longitude)\n <InfoWindow\n position={{ lat: latitude, lng: longitude }}\n onCloseClick={() => {\n handleMarkState(item.id)\n }}\n >\n <div className={`t-mini ${handles.markerInfo}`}>\n <span className={`b ${handles.markerInfoStoreName}`}>\n {item.name}\n </span>\n <br />\n <span className={handles.markerInfoAddress}>\n {item.address.number ? `${item.address.number} ` : ''}\n {item.address.street}\n {item.address.city ? `, ${item.address.city}` : ''}\n {item.address.state ? `, ${item.address.state}` : ''}\n {item.address.postalCode\n ? ` - ${item.address.postalCode}`\n : ''}\n </span>\n <br />\n <span\n className={`mt2 link c-link underline-hover pointer ${handles.markerInfoLink}`}\n onClick={(e) => {\n e.preventDefault()\n goTo(item)\n }}\n >\n <FormattedMessage id=\"store/more-details\" />\n </span>\n </div>\n </InfoWindow>\n )}\n </Marker>\n )\n })}\n </GoogleMap>\n )\n}\n\nexport default Pinpoints\n\n```"
}
] |
code_store-locator_7e7aee48
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/components/Listing.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable jsx-a11y/no-static-element-interactions */\n/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */\n/* eslint-disable jsx-a11y/click-events-have-key-events */\nimport type { FC } from 'react'\nimport React from 'react'\nimport { injectIntl, FormattedMessage } from 'react-intl'\nimport PropTypes from 'prop-types'\nimport slugify from 'slugify'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { useCssHandles } from 'vtex.css-handles'\n\nconst CSS_HANDLES = [\n 'addressList',\n 'addressListItem',\n 'addressListFirstItem',\n 'addressStoreName',\n 'addressStoreAddress',\n 'addressStoreAddressGroupA',\n 'addressStoreAddressNumber',\n 'addressStoreAddressStreet',\n 'addressListLink',\n] as const\n\nconst Slugify = (str: string) => {\n return slugify(str, { lower: true, remove: /[*+~.()'\"!:@]/g })\n}\n\nconst Listing: FC<any> = ({ items, onChangeCenter }) => {\n const handles = useCssHandles(CSS_HANDLES)\n const { navigate } = useRuntime()\n\n const handleChangeCenter = (item: any, zoom: number) => {\n const { latitude, longitude } = item.address.location\n\n onChangeCenter([longitude, latitude], zoom)\n }\n\n const goTo = (item: any) => {\n const { state: _state, postalCode } = item.address\n\n navigate({\n page: 'store.storedetail',\n params: {\n slug: `${Slugify(`${item.name} ${_state} ${postalCode}`)}`,\n store_id: String(item.id).replace('1_', ''),\n },\n })\n }\n\n return (\n items.length && (\n <ul className={`list ph3 mt0 ${handles.addressList}`}>\n {items.map((item: any, i: number) => {\n return (\n <li\n key={`key_${i}`}\n className={`pointer mb0 ph3 pv5 ${\n !i ? handles.addressListFirstItem : ''\n } ${handles.addressListItem} ${\n !i ? 'bt' : ''\n } bb bl br b--light-gray hover-bg-light-gray`}\n onClick={() => {\n handleChangeCenter(item, 12)\n }}\n >\n <span className={`t-mini b ${handles.addressStoreName}`}>\n {item.name}\n </span>\n <br />\n <span className={`t-mini ${handles.addressStoreAddress}`}>\n <span className={handles.addressStoreAddressGroupA}>\n <span className={handles.addressStoreAddressNumber}>\n {item.address.number ? `${item.address.number} ` : ''}\n </span>\n <span className={handles.addressStoreAddressStreet}>\n {item.address.street}\n </span>\n </span>\n {item.address.city ? `, ${item.address.city}` : ''}\n {item.address.state ? `, ${item.address.state}` : ''}\n {item.address.postalCode ? ` - ${item.address.postalCode}` : ''}\n </span>\n <br />\n <span\n className={`mt2 link c-link underline-hover pointer ${handles.addressListLink}`}\n onClick={(e) => {\n e.stopPropagation()\n goTo(item)\n }}\n >\n <FormattedMessage id=\"store/more-details\" />\n </span>\n </li>\n )\n })}\n </ul>\n )\n )\n}\n\nListing.propTypes = {\n items: PropTypes.array,\n onChangeCenter: PropTypes.func,\n}\n\nexport default injectIntl(Listing)\n\n```"
}
] |
code_store-locator_5d41eaa1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/components/Map.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport React from 'react'\nimport { GoogleMap, Marker, useJsApiLoader } from '@react-google-maps/api'\n\nconst Map = (props: any) => {\n const { zoom } = props\n const { isLoaded } = useJsApiLoader({\n id: 'google-map-script',\n googleMapsApiKey: props.apiKey,\n })\n\n const [lng, lat] = props.center\n let icon: any = {\n url: props.icon ?? null,\n }\n\n if (props.iconWidth && props.iconHeight) {\n icon = {\n ...icon,\n scaledSize: {\n width: props.iconWidth,\n height: props.iconHeight,\n },\n }\n }\n\n if (!isLoaded) return null\n\n return (\n <GoogleMap\n zoom={zoom}\n center={{ lat, lng }}\n mapContainerStyle={{ height: '100%' }}\n >\n <Marker icon={icon} position={{ lat, lng }} />\n </GoogleMap>\n )\n}\n\nexport default Map\n\n```"
}
] |
code_store-locator_7bd30c46
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-locator/react/__tests__/index.test.tsx from the store-locator VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\ndescribe('Orders List Scenarios', () => {\n it('should work', () => {\n expect(1).toBe(1)\n })\n})\n\n```"
}
] |
code_paypalcp-checkout-ui-settings_2f7dda51
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of paypalcp-checkout-ui-settings/checkout-ui-custom/checkout5-custom.css from the paypalcp-checkout-ui-settings VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/* /files/checkout5-custom.css */\n\n/* Displays the option to enter a foreign document */\n.document-box { display: block; }\n\n/* Displays the option to enter an international phone */\n.phone-box { display: block; }\n\n```"
}
] |
code_paypalcp-checkout-ui-settings_a27e569a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of paypalcp-checkout-ui-settings/checkout-ui-custom/checkout6-custom.js from the paypalcp-checkout-ui-settings VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable camelcase */\n/* eslint-disable no-undef */\nconst MAX_TIME_EXPIRATION = 1000 * 60 * 5 // 5 minutes\nconst GRAPHQL_ENDPOINT = '/_v/private/graphql/v1'\nconst ISO3_ENDPOINT =\n '/_v/vtex.connector-paypal-commerce-platform/v0/country-code/'\n\n// const GATEWAY_CALLBACK_ENDPOINT = '/api/checkout/pub/gatewayCallback/'\nconst SETTINGS_ENDPOINT = `/_v/vtex.connector-paypal-commerce-platform/v0/settings`\nconst OrderFormFragment = `id\n items {\n additionalInfo {\n brandName\n }\n attachments {\n name\n content\n }\n attachmentOfferings {\n name\n required\n schema\n }\n bundleItems {\n additionalInfo {\n brandName\n }\n attachments {\n name\n content\n }\n attachmentOfferings {\n name\n required\n schema\n }\n availability\n detailUrl\n id\n imageUrls {\n at1x\n at2x\n at3x\n }\n listPrice\n measurementUnit\n name\n offerings {\n id\n name\n price\n type\n attachmentOfferings {\n name\n required\n schema\n }\n }\n price\n productCategories\n productCategoryIds\n productRefId\n productId\n quantity\n seller\n sellingPrice\n skuName\n skuSpecifications {\n fieldName\n fieldValues\n }\n unitMultiplier\n uniqueId\n refId\n }\n parentAssemblyBinding\n parentItemIndex\n sellingPriceWithAssemblies\n options {\n assemblyId\n id\n quantity\n seller\n inputValues\n options {\n assemblyId\n id\n quantity\n seller\n inputValues\n options {\n assemblyId\n id\n quantity\n seller\n inputValues\n }\n }\n }\n availability\n detailUrl\n id\n imageUrls {\n at1x\n at2x\n at3x\n }\n listPrice\n manualPrice\n measurementUnit\n modalType\n name\n offerings {\n id\n name\n price\n type\n attachmentOfferings {\n name\n required\n schema\n }\n }\n price\n priceTags {\n identifier\n isPercentual\n name\n rawValue\n value\n }\n productCategories\n productCategoryIds\n productRefId\n productId\n quantity\n seller\n sellingPrice\n skuName\n skuSpecifications {\n fieldName\n fieldValues\n }\n unitMultiplier\n uniqueId\n refId\n priceTags {\n identifier\n isPercentual\n rawValue\n value\n name\n ratesAndBenefitsIdentifier {\n description\n id\n featured\n name\n matchedParameters\n }\n }\n isGift\n priceDefinition {\n calculatedSellingPrice\n total\n sellingPrices {\n quantity\n value\n }\n }\n }\n canEditData\n loggedIn\n userProfileId\n userType\n marketingData {\n coupon\n utmCampaign\n utmMedium\n utmSource\n utmiCampaign\n utmiPart\n utmiPage\n }\n totalizers {\n id\n name\n value\n }\n shipping {\n countries\n availableAddresses {\n addressId\n addressType\n city\n complement\n country\n neighborhood\n number\n postalCode\n receiverName\n reference\n state\n street\n isDisposable\n geoCoordinates\n }\n selectedAddress {\n addressId\n addressType\n city\n complement\n country\n neighborhood\n number\n postalCode\n receiverName\n reference\n state\n street\n isDisposable\n geoCoordinates\n }\n deliveryOptions {\n id\n deliveryChannel\n price\n estimate\n isSelected\n }\n pickupOptions {\n id\n address {\n addressId\n addressType\n city\n complement\n country\n neighborhood\n number\n postalCode\n receiverName\n reference\n state\n street\n isDisposable\n geoCoordinates\n }\n deliveryChannel\n price\n estimate\n isSelected\n friendlyName\n additionalInfo\n storeDistance\n transitTime\n businessHours {\n dayNumber\n closed\n closingTime\n openingTime\n }\n }\n isValid\n }\n paymentData {\n paymentSystems {\n id\n name\n groupName\n validator {\n regex\n mask\n cardCodeRegex\n cardCodeMask\n weights\n useCvv\n useExpirationDate\n useCardHolderName\n useBillingAddress\n }\n stringId\n requiresDocument\n isCustom\n description\n requiresAuthentication\n dueDate\n }\n payments {\n paymentSystem\n bin\n accountId\n tokenId\n installments\n referenceValue\n value\n }\n installmentOptions {\n paymentSystem\n installments {\n count\n hasInterestRate\n interestRate\n value\n total\n }\n }\n availableAccounts {\n accountId\n paymentSystem\n paymentSystemName\n cardNumber\n bin\n }\n isValid\n }\n clientProfileData {\n email\n firstName\n lastName\n document\n documentType\n phone\n isValid\n }\n clientPreferencesData {\n locale\n optInNewsletter\n }\n messages {\n couponMessages {\n code\n }\n generalMessages {\n code\n text\n status\n }\n }\n value\n allowManualPrice\n customData {\n customApps {\n fields\n id\n major\n }\n }`\n\nconst CREATE_ORDER_MUTATION = `mutation CreateOrder($input: CreateOrderInput!) {\n createOrder(input: $input)\n @context(provider: \"vtex.connector-paypal-commerce-platform\")\n }`\n\nconst UPDATE_ORDER_MUTATION = `mutation UpdateOrder($input: UpdateOrderInput!) {\n updateOrder(input: $input)\n @context(provider: \"vtex.connector-paypal-commerce-platform\")\n }\n `\n\nconst PLACE_ORDER_MUTATION = `mutation PlaceOrder($orderFormId: String!, $paypalOrderId: String!) {\n placeOrder(\n input: { orderFormId: $orderFormId, paypalOrderId: $paypalOrderId }\n ) @context(provider: \"vtex.connector-paypal-commerce-platform\") {\n orderGroup\n checkoutAuth\n }\n }\n `\n\nconst COMPLETE_ORDER_MUTATION = `mutation CompleteOrder($orderFormId: String!, $orderGroup: String!, $checkoutAuth: String!) {\n completeOrder(\n input: { orderFormId: $orderFormId, orderGroup: $orderGroup, checkoutAuth: $checkoutAuth }\n ) @context(provider: \"vtex.connector-paypal-commerce-platform\") {\n orderGroup\n checkoutAuth\n }\n }\n `\n\nconst ORDERFORM_QUERY = `query getOrderForm($orderFormId: ID) {\n orderForm(orderFormId: $orderFormId, refreshOutdatedData: true)\n @context(provider: \"vtex.checkout-graphql\", scope: \"private\") {\n ${OrderFormFragment}\n }\n }`\n\nconst ESTIMATE_SHIPPING_MUTATION = `mutation estimateShipping($addressInput: AddressInput) {\n estimateShipping(address: $addressInput)\n @context(provider: \"vtex.checkout-graphql\") {\n ${OrderFormFragment}\n }\n }`\n\nconst SELECT_DELIVERY_OPTION_MUTATION = `mutation selectDeliveryOption($deliveryOptionId: String) {\n selectDeliveryOption(deliveryOptionId: $deliveryOptionId)\n @context(provider: \"vtex.checkout-graphql\") {\n ${OrderFormFragment}\n }\n }`\n\nconst SELECT_PICKUP_OPTION_MUTATION = `mutation selectPickupOption($pickupOptionId: String) {\n selectPickupOption(pickupOptionId: $pickupOptionId)\n @context(provider: \"vtex.checkout-graphql\") {\n ${OrderFormFragment}\n }\n }`\n\nconst generateItemsArray = (orderForm, currency) => {\n let hasDeliveryErrors = false\n\n const returnArray = orderForm.items.map((item) => {\n if (item.availability === 'cannotBeDelivered') {\n hasDeliveryErrors = true\n }\n\n const name =\n item.name.length > 127 ? `${item.name.substring(0, 124)}...` : item.name\n\n const description =\n item.skuName.length > 127\n ? `${item.skuName.substring(0, 124)}...`\n : item.skuName\n\n return {\n name,\n unit_amount: {\n value: item.isGift ? '0.00' : (item.price / 100).toFixed(2),\n currency_code: currency,\n },\n quantity: item.quantity * item.unitMultiplier,\n description,\n sku: item.id,\n }\n })\n\n if (hasDeliveryErrors) return []\n\n return returnArray\n}\n\nconst generateShippingOptions = (orderForm, currency, pickupEnabled) => {\n if (\n !orderForm?.shipping?.deliveryOptions?.length &&\n (!pickupEnabled || !orderForm?.shipping?.pickupOptions?.length)\n ) {\n return []\n }\n\n const shippingOptions = orderForm.shipping.deliveryOptions.map((option) => {\n return {\n id: option.id,\n label: option.id,\n type: 'SHIPPING',\n selected: option.isSelected,\n amount: {\n value: (option.price / 100).toFixed(2),\n currency_code: currency,\n },\n }\n })\n\n const pickupOptions = pickupEnabled\n ? orderForm.shipping.pickupOptions.map((option) => {\n return {\n id: option.id,\n label: option.friendlyName,\n type: 'PICKUP',\n selected: option.isSelected,\n amount: {\n value: (option.price / 100).toFixed(2),\n currency_code: currency,\n },\n }\n })\n : []\n\n return [...pickupOptions, ...shippingOptions]\n}\n\nconst getSelectedPickupLocation = (orderForm) => {\n if (!orderForm?.shipping?.pickupOptions?.length) {\n return null\n }\n\n return orderForm.shipping.pickupOptions.filter(\n (option) => option.isSelected\n )[0]\n}\n\nconst generateBreakdown = (totalizers, currency) => {\n const breakdown = {}\n let totalTax = 0\n\n totalizers.forEach((totalizer) => {\n if (totalizer.id === 'Items') {\n breakdown.item_total = {\n value: (totalizer.value / 100).toFixed(2),\n currency_code: currency,\n }\n\n return\n }\n\n if (totalizer.id === 'Shipping') {\n breakdown.shipping = {\n value: (totalizer.value / 100).toFixed(2),\n currency_code: currency,\n }\n\n return\n }\n\n if (totalizer.id === 'Discounts') {\n breakdown.discount = {\n value: Math.abs(totalizer.value / 100).toFixed(2),\n currency_code: currency,\n }\n\n return\n }\n\n if (totalizer.id.toLowerCase().includes('tax')) {\n totalTax += totalizer.value\n }\n })\n\n breakdown.tax_total = {\n value: (totalTax / 100).toFixed(2),\n currency_code: currency,\n }\n\n return breakdown\n}\n\n!(() => {\n console.info('PayPal Smart Buttons')\n let checkPayPalSettings = null\n\n // Used to remove cache from requests\n const isWorkspace = () => {\n return window.__RUNTIME__.workspace !== 'master'\n }\n\n let payPalSettings\n const storedPayPalSettings = JSON.parse(\n window.sessionStorage.getItem('paypal-settings')\n )\n\n if (storedPayPalSettings?.time) {\n const now = new Date().getTime()\n const sessionStorageCheckoutTime = new Date(\n storedPayPalSettings.time\n ).getTime()\n\n if (now - sessionStorageCheckoutTime < MAX_TIME_EXPIRATION) {\n payPalSettings = storedPayPalSettings\n }\n }\n\n window.payPalSettings = window.payPalSettings || payPalSettings\n\n const handleShippingUpdate = async (address, rootPath) => {\n const { city, country_code, postal_code, state } = address\n\n const countryCode =\n country_code.length === 2\n ? await fetch(`${rootPath}${ISO3_ENDPOINT}${country_code}`)\n .then((response) => response.json())\n .then((response) => response.code)\n : country_code\n\n const addressInput = {\n neighborhood: 'N/A',\n city,\n country: countryCode,\n postalCode: postal_code,\n state,\n isDisposable: true,\n }\n\n return fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: ESTIMATE_SHIPPING_MUTATION,\n variables: { addressInput },\n }),\n })\n }\n\n const handleSelectShippingOption = async (data, rootPath) => {\n const { selected_shipping_option } = data\n\n if (selected_shipping_option.type === 'PICKUP') {\n return fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: SELECT_PICKUP_OPTION_MUTATION,\n variables: { pickupOptionId: selected_shipping_option.id },\n }),\n })\n }\n\n return fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: SELECT_DELIVERY_OPTION_MUTATION,\n variables: { deliveryOptionId: selected_shipping_option.id },\n }),\n })\n }\n\n const checkSelectedShippingOption = async (currentOrderForm, rootPath) => {\n if (\n !currentOrderForm?.shipping?.deliveryOptions?.length ||\n currentOrderForm.shipping.deliveryOptions.some((opt) => opt.isSelected)\n ) {\n return currentOrderForm\n }\n\n const {\n city,\n country: country_code,\n postalCode: postal_code,\n state,\n } = currentOrderForm.shipping.selectedAddress\n\n await handleShippingUpdate(\n {\n city,\n country_code,\n postal_code,\n state,\n },\n rootPath\n )\n\n return fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: SELECT_DELIVERY_OPTION_MUTATION,\n variables: {\n deliveryOptionId: currentOrderForm.shipping.deliveryOptions[0].id,\n },\n }),\n })\n .then((response) => response.json())\n .then(({ data: selectResult }) => {\n const newOrderForm = selectResult?.selectDeliveryOption\n\n if (!newOrderForm) {\n return currentOrderForm\n }\n\n return newOrderForm\n })\n }\n\n const renderButtons = async () => {\n if (\n typeof paypal === 'undefined' ||\n $('#paypal-button-container').children().length\n ) {\n return\n }\n const rootPath = window?.vtex?.renderRuntime?.rootPath ?? ''\n\n const {\n layout,\n color,\n shape,\n showTagline,\n immediateCapture,\n sellerEmail,\n merchantId,\n enablePickup = false,\n } = window.payPalSettings\n\n const { orderFormId } = vtexjs.checkout\n const currency = window?.vtexjs?.checkout?.orderForm?.storePreferencesData?.currencyCode || 'USD'\n\n paypal\n .Buttons({\n style: {\n layout,\n color,\n shape,\n ...(layout === 'horizontal' ? { tagline: showTagline } : {}),\n },\n createOrder(_data, _actions) {\n return fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: ORDERFORM_QUERY,\n variables: {\n orderFormId,\n },\n }),\n })\n .then((response) => response.json())\n .then(({ data }) => {\n const { orderForm } = data\n\n return checkSelectedShippingOption(orderForm, rootPath).then(\n (newOrderForm) => {\n const items = generateItemsArray(newOrderForm, currency)\n\n if (!items.length) return null\n\n const shippingOptions = generateShippingOptions(\n newOrderForm,\n currency,\n enablePickup\n )\n\n const breakdown = generateBreakdown(\n newOrderForm.totalizers,\n currency\n )\n\n return fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: CREATE_ORDER_MUTATION,\n variables: {\n input: {\n intent: immediateCapture ? 'CAPTURE' : 'AUTHORIZE',\n amount: {\n value: (newOrderForm.value / 100).toFixed(2),\n currency_code: currency,\n breakdown,\n },\n payee: {\n email_address: sellerEmail,\n merchant_id: merchantId,\n },\n items,\n shipping: {\n options:\n shippingOptions && shippingOptions.length > 0\n ? shippingOptions\n : null,\n },\n },\n },\n }),\n })\n .then((response) => response.json())\n .then(({ data: newData }) => {\n if (!newData) return null\n\n return newData.createOrder\n })\n }\n )\n })\n },\n onShippingChange(data, actions) {\n const { shipping_address } = data\n\n // always run the shipping estimate mutation to make sure we have the latest orderForm\n return handleShippingUpdate(shipping_address, rootPath)\n .then((response) => response.json())\n .then(({ data: result }) => {\n if (!result) {\n return actions.reject()\n }\n\n let newOrderForm = result.estimateShipping\n\n if (!newOrderForm) {\n return actions.reject()\n }\n\n const { shipping, totalizers } = newOrderForm\n\n if (\n !shipping?.deliveryOptions?.length &&\n !shipping?.pickupOptions?.length\n ) {\n return actions.reject()\n }\n\n const newItems = generateItemsArray(newOrderForm, currency)\n\n if (!newItems?.length) return actions.reject()\n\n // if the selected shipping option in paypal hasn't been selected in VTEX,\n // select it and then patch the paypal order with the new orderForm data.\n // This conditional is for delivery options, see below for pickup\n if (\n data.selected_shipping_option?.id &&\n shipping.deliveryOptions.find(\n (option) =>\n option.id === data.selected_shipping_option.id &&\n (option.price / 100).toFixed(2) ===\n data.selected_shipping_option.amount.value &&\n !option.isSelected\n )\n ) {\n return handleSelectShippingOption(data, rootPath)\n .then((response) => response.json())\n .then(({ data: selectResult }) => {\n if (!selectResult) {\n return actions.reject()\n }\n\n newOrderForm = selectResult.selectDeliveryOption\n\n if (!newOrderForm) {\n return actions.reject()\n }\n\n const { totalizers: newTotalizers } = newOrderForm\n\n const newShippingOptions = generateShippingOptions(\n newOrderForm,\n currency,\n enablePickup\n )\n\n const newBreakdown = generateBreakdown(\n newTotalizers,\n currency\n )\n\n const input = {\n orderId: data.orderID,\n amount: {\n value: (newOrderForm.value / 100).toFixed(2),\n currency_code: currency,\n breakdown: newBreakdown,\n },\n payee: {\n email_address: sellerEmail,\n merchant_id: merchantId,\n },\n items: newItems,\n shipping: {\n options: newShippingOptions,\n },\n }\n\n return fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: UPDATE_ORDER_MUTATION,\n variables: { input },\n }),\n })\n .then((response) => response.json())\n .then(({ data: updateOrderResult }) => {\n if (!updateOrderResult?.updateOrder) {\n return actions.reject()\n }\n\n return actions.resolve()\n })\n })\n }\n\n // pickup\n if (\n data.selected_shipping_option?.id &&\n shipping.pickupOptions?.find(\n (option) =>\n option.id === data.selected_shipping_option.id &&\n (option.price / 100).toFixed(2) ===\n data.selected_shipping_option.amount.value &&\n !option.isSelected\n )\n ) {\n return handleSelectShippingOption(data, rootPath)\n .then((response) => response.json())\n .then(({ data: selectResult }) => {\n if (!selectResult) {\n return actions.reject()\n }\n\n newOrderForm = selectResult.selectPickupOption\n\n if (!newOrderForm) {\n return actions.reject()\n }\n\n const { totalizers: newTotalizers } = newOrderForm\n\n const newShippingOptions = generateShippingOptions(\n newOrderForm,\n currency,\n enablePickup\n )\n\n const newBreakdown = generateBreakdown(\n newTotalizers,\n currency\n )\n\n const pickupLocation = getSelectedPickupLocation(\n newOrderForm\n )\n\n if (!pickupLocation) {\n return actions.reject()\n }\n\n const input = {\n orderId: data.orderID,\n amount: {\n value: (newOrderForm.value / 100).toFixed(2),\n currency_code: currency,\n breakdown: newBreakdown,\n },\n payee: {\n email_address: sellerEmail,\n merchant_id: merchantId,\n },\n items: newItems,\n shipping: {\n options: newShippingOptions,\n name: {\n full_name: `S2S ${pickupLocation.friendlyName}`,\n },\n address: {\n address_line_1: pickupLocation.address.street,\n admin_area_2: pickupLocation.address.city,\n admin_area_1: pickupLocation.address.state,\n postal_code: pickupLocation.address.postalCode,\n country_code: data.shipping_address.country_code,\n },\n },\n }\n\n return fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: UPDATE_ORDER_MUTATION,\n variables: { input },\n }),\n })\n .then((response) => response.json())\n .then(({ data: updateOrderResult }) => {\n if (!updateOrderResult?.updateOrder) {\n return actions.reject()\n }\n\n return actions.resolve()\n })\n })\n }\n\n const newShippingOptions = generateShippingOptions(\n newOrderForm,\n currency,\n enablePickup\n )\n\n const newBreakdown = generateBreakdown(totalizers, currency)\n\n const isPickup = data.selected_shipping_option?.type === 'PICKUP'\n\n const pickupLocation = getSelectedPickupLocation(newOrderForm)\n\n if (isPickup && !pickupLocation) {\n return actions.reject()\n }\n\n const input = {\n orderId: data.orderID,\n amount: {\n value: (newOrderForm.value / 100).toFixed(2),\n currency_code: currency,\n breakdown: newBreakdown,\n },\n payee: {\n email_address: sellerEmail,\n merchant_id: merchantId,\n },\n items: newItems,\n shipping: {\n options: newShippingOptions,\n ...(isPickup && {\n name: {\n full_name: `S2S ${pickupLocation.friendlyName}`,\n },\n address: {\n address_line_1: pickupLocation.address.street,\n admin_area_2: pickupLocation.address.city,\n admin_area_1: pickupLocation.address.state,\n postal_code: pickupLocation.address.postalCode,\n country_code: data.shipping_address.country_code,\n },\n }),\n },\n }\n\n return fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: UPDATE_ORDER_MUTATION,\n variables: { input },\n }),\n })\n .then((response) => response.json())\n .then(({ data: updateOrderResult }) => {\n if (!updateOrderResult?.updateOrder) {\n return actions.reject()\n }\n\n return actions.resolve()\n })\n })\n .catch(() => {\n return actions.reject()\n })\n },\n onApprove(data) {\n vtex.checkout.MessageUtils.showPaymentMessage()\n\n fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: PLACE_ORDER_MUTATION,\n variables: {\n orderFormId,\n paypalOrderId: data.orderID,\n },\n }),\n })\n .then((response) => response.json())\n .then(async (result) => {\n if (\n !result?.data?.placeOrder?.orderGroup ||\n !result?.data?.placeOrder?.checkoutAuth\n ) {\n vtex.checkout.MessageUtils.hidePaymentMessage()\n vtex.checkout.MessageUtils.showPaymentUnauthorizedMessage()\n\n return\n }\n\n document.cookie = result.data.placeOrder.checkoutAuth\n\n return fetch(`${rootPath}${GRAPHQL_ENDPOINT}`, {\n method: 'POST',\n body: JSON.stringify({\n query: COMPLETE_ORDER_MUTATION,\n variables: {\n orderFormId,\n orderGroup: result.data.placeOrder.orderGroup,\n checkoutAuth: result.data.placeOrder.checkoutAuth,\n },\n }),\n })\n .then((response) => response.json())\n .then(async (finalResult) => {\n if (!finalResult?.data?.completeOrder?.orderGroup) {\n vtex.checkout.MessageUtils.hidePaymentMessage()\n vtex.checkout.MessageUtils.showPaymentUnauthorizedMessage()\n\n return\n }\n\n vtex.checkout.MessageUtils.hidePaymentMessage()\n\n window.location = `${rootPath}/checkout/orderPlaced/?og=${result.data.placeOrder.orderGroup}`\n })\n })\n .catch(() => {\n vtex.checkout.MessageUtils.hidePaymentMessage()\n vtex.checkout.MessageUtils.showPaymentUnauthorizedMessage()\n })\n },\n onCancel() {\n vtexjs.checkout\n .getOrderForm()\n .then(() => console.info('User closed PayPal Checkout'))\n },\n })\n .render('#paypal-button-container')\n }\n\n const createDiv = () => {\n if (\n $('#paypal-button-container').size()\n ) {\n return\n }\n const [buttonContainer] = document.getElementsByClassName('cart-links')\n const paypalDiv = document.createElement('div')\n\n paypalDiv.id = 'paypal-button-container'\n\n if (buttonContainer) {\n buttonContainer.appendChild(paypalDiv)\n }\n }\n\n const loadPayPalScript = async () => {\n const {\n production,\n productionClientId,\n productionBNCode,\n sandboxClientId,\n sandboxBNCode,\n merchantId,\n immediateCapture,\n disablePayPalCredit,\n disableCards,\n } = window.payPalSettings\n\n const currency = window?.vtexjs?.checkout?.orderForm?.storePreferencesData?.currencyCode || 'USD'\n\n const script = document.createElement('script')\n\n const disabledPayments = []\n\n if (disableCards) disabledPayments.push('card')\n if (disablePayPalCredit) disabledPayments.push('credit')\n\n script.src = `https://www.paypal.com/sdk/js?client-id=${\n production ? productionClientId : sandboxClientId\n }&merchant-id=${merchantId}¤cy=${currency}&intent=${\n immediateCapture ? 'capture' : 'authorize'\n }&commit=true${\n disabledPayments.length\n ? `&disable-funding=${disabledPayments.join(',')}`\n : ``\n }`\n script.setAttribute(\n 'data-partner-attribution-id',\n production ? productionBNCode : sandboxBNCode\n )\n document.body.appendChild(script)\n }\n\n const initializePayPal = async () => {\n if (!window.payPalSettings?.showOnCartPage) {\n return\n }\n\n if (window.location.hash !== '#/cart') {\n const paypalButtons = document.getElementById('paypal-button-container')\n\n if (paypalButtons) {\n paypalButtons.remove()\n }\n\n return\n }\n\n createDiv()\n await loadPayPalScript()\n const checkPayPalScript = setInterval(() => {\n if (typeof paypal !== 'undefined') {\n clearInterval(checkPayPalScript)\n renderButtons()\n }\n }, 500)\n }\n\n const handlePayPalSettings = () => {\n if (!payPalSettings) return\n\n window.payPalSettings = payPalSettings\n initializePayPal()\n }\n\n const fetchPayPalSettings = () => {\n const rootPath = window?.vtex?.renderRuntime?.rootPath ?? ''\n\n const ts = new Date().getTime()\n\n $.ajax({\n url: `${rootPath}${SETTINGS_ENDPOINT}${isWorkspace() ? `?v=${ts}` : ''}`,\n }).then((response) => {\n if (Object.keys(response).length === 0) {\n window.sessionStorage.removeItem('paypal-settings')\n\n return\n }\n\n response.time = new Date().toISOString()\n\n window.sessionStorage.setItem('paypal-settings', JSON.stringify(response))\n payPalSettings = response\n handlePayPalSettings()\n })\n }\n\n // Wait until we have the vtex runtime to call the functions\n checkPayPalSettings = setInterval(() => {\n if (typeof window?.vtex?.renderRuntime !== 'undefined') {\n clearInterval(checkPayPalSettings)\n if (isWorkspace() || !payPalSettings) {\n fetchPayPalSettings()\n } else {\n handlePayPalSettings()\n }\n }\n }, 500)\n\n\n $(window).on(\"orderFormUpdated.vtex\", function(evt, orderForm) {\n initializePayPal()\n })\n\n})();\n \n```"
}
] |
code_paypalcp-checkout-ui-settings_3244a168
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of paypalcp-checkout-ui-settings/checkout-ui-custom/checkout-confirmation-custom.js from the paypalcp-checkout-ui-settings VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n// WARNING: THE USAGE OF CUSTOM SCRIPTS IS NOT SUPPORTED. VTEX IS NOT LIABLE FOR ANY DAMAGES THIS MAY CAUSE.\n// THIS MAY BREAK YOUR STORE AND STOP SALES. IN CASE OF ERRORS, PLEASE DELETE THE CONTENT OF THIS SCRIPT.\n\n```"
}
] |
code_paypalcp-checkout-ui-settings_20b55c96
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of paypalcp-checkout-ui-settings/checkout-ui-custom/checkout5-custom.js from the paypalcp-checkout-ui-settings VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n// WARNING: THE USAGE OF CUSTOM SCRIPTS IS NOT SUPPORTED. VTEX IS NOT LIABLE FOR ANY DAMAGES THIS MAY CAUSE. THIS MAY BREAK YOUR STORE AND STOP SALES. IN CASE OF ERRORS, PLEASE DELETE THE CONTENT OF THIS SCRIPT.\n\n```"
}
] |
code_paypalcp-checkout-ui-settings_574df8c0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of paypalcp-checkout-ui-settings/docs/README.md from the paypalcp-checkout-ui-settings VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/paypalcp-checkout-ui-settings) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# PayPalCP Checkout UI Settings\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nAn app to inject the necessary scripts to render PayPal Smart Payment Buttons in Checkout V6. \n\nFor more information see the [PayPal Commerce Platform app documentation](https://developers.vtex.com/docs/guides/vtex-connector-paypal-commerce-platform).\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```"
}
] |
code_elfsight_dc323875
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of elfsight/docs/README.md from the elfsight VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/elfsight) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Elfsight\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nElfsight first party integration app. The [solution](https://elfsight.com/) provides widgets that help website owners to increase sales, engage visitors, collect leads and more.\n\n\n\n## Configuration \n\n1. Adding the app as a theme dependency in the `manifest.json` file;\n\n```json\n\"dependencies\": {\n \"vtex.elfsight\": \"1.x\"\n}\n```\n\n2. Add the block `elfsight`, responsible for rendering your Elfsight widget, to your theme `blocks.json` file. Notice: the block can be added to any page template you want. \n3. Declare in it the prop `appId` whose value must be the app ID of the widget provided by Elfsight. For example:\n\n\n```diff\n \"footer-layout.desktop\": {\n \"children\": [\n+ \"elfsight#foobar\"\n ]\n },\n\n+ \"elfsight#foobar\": {\n+ \"props\": {\n+ \"appId\": \"4a13d81d-20f3-4661-b472-9de777efe3ed\"\n+ }\n+ }\n```\n\n### `elfsight` props\n\n| Prop name | Type | Description | Default value |\n| ------------ | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | \n| `appId` | `string` | The app ID of the widget provided by Elfsight. The format should be as follows: `XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX`. | `undefined` |\n\nYou should get the app ID from the Elfsight admin:\n\n\n\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```"
}
] |
code_elfsight_ae9ce533
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of elfsight/react/Elfsight.tsx from the elfsight VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\n\ninterface Props {\n appId?: string\n}\n\nconst Elfsight: FC<Props> = ({ appId }) => {\n if (!appId) {\n return null\n }\n\n return <div className={`elfsight-app-${appId}`} />\n}\n\nexport default Elfsight\n\n```"
}
] |
code_elfsight_32c85fdf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of elfsight/react/package.json from the elfsight VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^25.1.5\",\n \"@types/node\": \"^13.11.0\",\n \"@types/react\": \"^16.9.31\",\n \"@types/react-intl\": \"^3.0.0\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"apollo-client\": \"^2.6.8\",\n \"graphql\": \"^14.5.4\",\n \"react-intl\": \"^3.11.0\",\n \"typescript\": \"3.8.3\"\n },\n \"version\": \"1.0.0\"\n}\n\n```"
}
] |
code_elfsight_4015481f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of elfsight/store/interfaces.json from the elfsight VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"elfsight\": {\n \"component\": \"Elfsight\"\n }\n}\n\n```"
}
] |
code_elfsight_a2799032
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of elfsight/react/typings/events.d.ts from the elfsight VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface PixelMessage extends MessageEvent {\n data:\n | ProductViewData\n | ProductClickData\n | OrderPlacedData\n | OrderPlacedTrackedData\n | PageViewData\n | ProductImpressionData\n | AddToCartData\n | RemoveToCartData\n | CartChangedData\n | HomePageInfo\n | ProductPageInfoData\n | SearchPageInfoData\n | UserData\n | CartIdData\n}\n\nexport interface EventData {\n event: string\n eventName: string\n currency: string\n}\n\nexport interface PageInfoData extends EventData {\n event: 'pageInfo'\n eventName: 'vtex:pageInfo'\n accountName: string\n pageTitle: string\n pageUrl: string\n}\n\nexport interface UserData extends PageInfoData {\n eventType: 'userData'\n eventName: 'vtex:userData'\n firstName?: string\n lastName?: string\n document?: string\n id?: string\n email?: string\n phone?: string\n isAuthenticated: boolean\n}\n\nexport interface CartIdData extends PageInfoData {\n eventType: 'cartId'\n eventName: 'vtex:cartId'\n cartId: string\n}\n\nexport interface HomePageInfo extends PageInfoData {\n eventType: 'homeView'\n}\n\nexport interface ProductPageInfoData extends PageInfoData {\n eventType: 'productPageInfo'\n}\n\nexport interface SearchPageInfoData extends PageInfoData {\n eventType:\n | 'internalSiteSearchView'\n | 'categoryView'\n | 'departmentView'\n | 'emptySearchView'\n category?: CategoryMetaData\n department?: DepartmentMetaData\n search?: SearchMetaData\n}\n\ninterface CategoryMetaData {\n id: string\n name: string\n}\n\ninterface DepartmentMetaData {\n id: string\n name: string\n}\n\ninterface SearchMetaData {\n term: string\n category: CategoryMetaData\n results: number\n}\n\nexport interface PageViewData extends EventData {\n event: 'pageView'\n eventName: 'vtex:pageView'\n pageTitle: string\n pageUrl: string\n referrer: string\n}\n\nexport interface AddToCartData extends EventData {\n event: 'addToCart'\n eventName: 'vtex:addToCart'\n items: CartItem[]\n}\n\nexport interface RemoveToCartData extends EventData {\n event: 'removeFromCart'\n eventName: 'vtex:removeFromCart'\n items: CartItem[]\n}\n\nexport interface CartChangedData extends EventData {\n event: 'cartChanged'\n eventName: 'vtex:cartChanged'\n items: CartItem[]\n}\n\nexport interface OrderPlacedData extends Order, EventData {\n event: 'orderPlaced'\n eventName: 'vtex:orderPlaced'\n}\n\nexport interface OrderPlacedTrackedData extends Order, EventData {\n event: 'orderPlacedTracked'\n eventName: 'vtex:orderPlacedTracked'\n}\n\nexport interface ProductViewData extends EventData {\n event: 'productView'\n eventName: 'vtex:productView'\n product: Product\n}\n\nexport interface ProductClickData extends EventData {\n event: 'productClick'\n eventName: 'vtex:productClick'\n product: ProductSummary\n}\n\nexport interface ProductImpressionData extends EventData {\n event: 'productImpression'\n eventName: 'vtex:productImpression'\n impressions: Impression[]\n product?: ProductSummary // deprecated, use impressions list!\n position?: number // deprecated, use impressions list!\n list: string\n}\n\ninterface CartItem {\n brand: string\n category: string\n detailUrl: string\n imageUrl: string\n name: string\n price: number\n productId: string\n productRefId: string\n quantity: number\n skuId: string\n variant: string\n}\n\nexport interface Order {\n accountName: string\n corporateName: string\n coupon: string\n currency: string\n openTextField: string\n orderGroup: string\n salesChannel: string\n visitorAddressCity: string\n visitorAddressComplement: string\n visitorAddressCountry: string\n visitorAddressNeighborhood: string\n visitorAddressNumber: string\n visitorAddressPostalCode: string\n visitorAddressState: string\n visitorAddressStreet: string\n visitorContactInfo: string[]\n visitorContactPhone: string\n visitorType: string\n transactionId: string\n transactionDate: string\n transactionAffiliation: string\n transactionTotal: number\n transactionShipping: number\n transactionSubtotal: number\n transactionDiscounts: number\n transactionTax: number\n transactionCurrency: string\n transactionPaymentType: PaymentType[]\n transactionShippingMethod: ShippingMethod[]\n transactionLatestShippingEstimate: Date\n transactionProducts: ProductOrder[]\n transactionPayment: {\n id: string\n }\n}\n\nexport interface Impression {\n product: ProductSummary\n position: number\n}\n\nexport interface PaymentType {\n group: string\n paymentSystemName: string\n installments: number\n value: number\n}\n\nexport interface ShippingMethod {\n itemId: string\n selectedSla: string\n}\n\nexport interface ProductOrder {\n id: string\n name: string\n sku: string\n skuRefId: string\n skuName: string\n productRefId: string\n ean: string\n slug: string\n brand: string\n brandId: string\n seller: string\n sellerId: string\n category: string\n categoryId: string\n categoryTree: string[]\n categoryIdTree: string[]\n priceTags: PriceTag[]\n originalPrice: number\n price: number\n sellingPrice: number\n tax: number\n quantity: number\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n components: any[]\n measurementUnit: string\n unitMultiplier: number\n}\n\nexport interface PriceTag {\n identifier: string\n isPercentual: boolean\n value: number\n}\n\nexport interface Product {\n brand: string\n brandId: string\n categories: string[]\n categoryId: string\n categoryTree: Array<{ id: string; name: string }>\n detailUrl: string\n items: Item[]\n linkText: string\n productId: string\n productName: string\n productReference: string\n selectedSku: Item\n}\n\nexport interface Item {\n itemId: string\n name: string\n ean: string\n referenceId: { Key: string; Value: string }\n imageUrl: string\n sellers: Seller[]\n}\n\nexport interface ProductSummary {\n brand: string\n brandId: string\n categories: string[]\n items: ItemSummary[]\n linkText: string\n productId: string\n productName: string\n productReference: string\n sku: ItemSummary\n}\n\ninterface ItemSummary {\n itemId: string\n ean: string\n name: string\n referenceId: { Key: string; Value: string }\n seller: Seller\n sellers: Seller[]\n}\n\nexport interface Seller {\n commertialOffer: CommertialOffer\n sellerId: string\n}\n\nexport interface CommertialOffer {\n Price: number\n ListPrice: number\n AvailableQuantity: number\n}\n\n```"
}
] |
code_elfsight_a5a5abd8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of elfsight/react/typings/vtex.render-runtime.d.ts from the elfsight VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime' {\n export const canUseDOM: boolean\n}\n\n```"
}
] |
code_elfsight_08d30cc2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of elfsight/react/typings/global.d.ts from the elfsight VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Window extends Window {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dataLayer: any[]\n}\n\n```"
}
] |
code_pixel-manager_74ce5364
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pixel-manager/react/usePixel.ts from the pixel-manager VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useContext } from 'react'\n\nimport { PixelContext } from './PixelContext'\n\nconst usePixel = () => {\n return useContext(PixelContext)\n}\n\nexport default usePixel\n\n```"
}
] |
code_pixel-manager_be8a1c02
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pixel-manager/react/usePixelEventCallback.ts from the pixel-manager VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useEffect, useRef } from 'react'\n\nimport type { PixelData } from './PixelEventTypes'\n\nexport const shouldCallEventHandler = (\n pixelEventData: PixelData,\n eventId: string | undefined,\n eventName: PixelData['event']\n) => {\n const receivedEventId = Boolean(eventId)\n const receivedEventName = Boolean(eventName)\n const hasEventId = Boolean(pixelEventData.id)\n const hasEventName = Boolean(pixelEventData.event)\n\n // These checks are to make sure that handlers are only called when\n // both the 'eventId' (if received) and the 'eventName' (if received)\n // match the event being processed.\n // If any of those arguments were NOT received, only the one that was\n // received should be taken into account.\n if (receivedEventId && hasEventId && pixelEventData.id === eventId) {\n return (\n !receivedEventName || (hasEventName && pixelEventData.event === eventName)\n )\n }\n\n if (receivedEventName && hasEventName && pixelEventData.event === eventName) {\n return !receivedEventId || (hasEventId && pixelEventData.id === eventId)\n }\n\n return false\n}\n\nconst usePixelEventCallback = ({\n eventId,\n eventName,\n handler,\n}: {\n eventId?: string\n eventName?: PixelData['event']\n handler: (e?: MessageEvent) => void\n}) => {\n const savedHandler = useRef(handler)\n\n useEffect(() => {\n savedHandler.current = handler\n }, [handler])\n\n useEffect(() => {\n const isSupported = Boolean(window?.addEventListener)\n\n if (!isSupported || (!eventId && !eventName)) {\n return\n }\n\n const customEventHandler = (e: MessageEvent) => {\n const pixelEventData = e.data as PixelData\n\n if (shouldCallEventHandler(pixelEventData, eventId, eventName)) {\n savedHandler.current(e)\n }\n }\n\n window.addEventListener('message', customEventHandler)\n\n return () => {\n window.removeEventListener('message', customEventHandler)\n }\n }, [eventId, eventName, savedHandler])\n}\n\nexport default usePixelEventCallback\n\n```"
}
] |
code_pixel-manager_750f56d6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pixel-manager/react/package.json from the pixel-manager VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.pixel-manager\",\n \"version\": \"1.9.0\",\n \"private\": true,\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"graphql\": \"^14.0.2\",\n \"hoist-non-react-statics\": \"^3.2.1\",\n \"ramda\": \"^0.26.1\",\n \"react-apollo\": \"^2.3.3\"\n },\n \"devDependencies\": {\n \"@types/hoist-non-react-statics\": \"^3.0.1\",\n \"@types/jest\": \"^24.0.3\",\n \"@types/prop-types\": \"^15.5.8\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@types/react\": \"^16.7.17\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"graphql-tag\": \"^2.10.0\",\n \"react\": \"^16.8.1\",\n \"react-dom\": \"^16.8.1\",\n \"typescript\": \"3.9.7\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.128.2/public/@types/vtex.render-runtime\"\n }\n}\n\n```"
}
] |
code_pixel-manager_b3701ad8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pixel-manager/react/PixelEventTypes.ts from the pixel-manager VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport type EventName =\n | 'addToCart'\n | 'cart'\n | 'cartChanged'\n | 'cartId'\n | 'cartLoaded'\n | 'categoryView'\n | 'checkout'\n | 'checkoutOption'\n | 'departmentView'\n | 'finishPayment'\n | 'homeView'\n | 'installWebApp'\n | 'internalSiteSearchView'\n | 'openDrawer'\n | 'orderPlaced'\n | 'otherView'\n | 'pageComponentInteraction'\n | 'pageInfo'\n | 'pageView'\n | 'productClick'\n | 'productComparison'\n | 'productImpression'\n | 'productView'\n | 'promotionClick'\n | 'promoView'\n | 'removeFromCart'\n | 'sendPayments'\n | 'newsletterSubscription'\n | 'viewCart'\n | 'beginCheckout'\n | 'addPaymentInfo'\n | 'addShippingInfo'\n | 'addToWishlist'\n | 'share'\n | 'login'\n | 'search'\n | 'signUp'\n | 'refund'\n\nexport interface PixelData {\n id?: string\n event?: EventName\n [data: string]: unknown\n}\n\n```"
}
] |
code_pixel-manager_0c03bedd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pixel-manager/react/PixelContext.tsx from the pixel-manager VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport hoistNonReactStatics from 'hoist-non-react-statics'\nimport React, { useContext, createContext, PureComponent } from 'react'\n\nimport type { PixelData } from './PixelEventTypes'\n\ninterface PixelEvent extends Event {\n data: any\n}\n\nexport interface PixelContextType {\n push: (data: PixelData) => void\n}\n\ndeclare let process: {\n env: {\n NODE_ENV: 'production' | 'development'\n VTEX_APP_ID: string\n }\n}\n\ninterface Props {\n currency: string\n}\n\nexport const PixelContext = createContext<PixelContextType>({\n push: () => undefined,\n})\n\nconst getDisplayName = <T extends Record<string, any>>(\n comp: React.ComponentType<T>\n) => (comp.displayName ?? comp.name) || 'Component'\n\nexport const usePixel = () => useContext(PixelContext)\n\n/**\n * withPixel is the HOC Component that provides an event subscription to the\n * Wrapped Component. This component will be used by the installed apps.\n */\nexport function withPixel<T>(\n WrappedComponent: React.ComponentType<T & PixelContextType>\n) {\n const PixelComponent: React.FC<T> = (props) => {\n const { push } = usePixel()\n\n return <WrappedComponent {...props} push={push} />\n }\n\n PixelComponent.displayName = `withPixel(${getDisplayName(WrappedComponent)})`\n\n return hoistNonReactStatics(PixelComponent, WrappedComponent)\n}\n\nclass PixelProvider extends PureComponent<Props> {\n private pixelContextValue: PixelContextType\n\n constructor(props: Props) {\n super(props)\n\n this.pixelContextValue = {\n push: this.push,\n }\n }\n\n public componentDidMount() {\n window.addEventListener('message', this.handleWindowMessage)\n }\n\n public componentWillUnmount() {\n window.removeEventListener('message', this.handleWindowMessage)\n }\n\n /**\n * Push event to iframe\n */\n public push = (data: PixelData) => {\n // Add all events to window when is linking to ease debugging\n // **Don't make those if's one!**\n if (process.env.NODE_ENV === 'development') {\n if (typeof window !== 'undefined') {\n window.pixelManagerEvents = window.pixelManagerEvents || []\n window.pixelManagerEvents.push(data)\n }\n }\n\n this.handlePixelEvent(data)\n }\n\n public render() {\n return (\n <PixelContext.Provider value={this.pixelContextValue}>\n {this.props.children}\n </PixelContext.Provider>\n )\n }\n\n private handleWindowMessage = (e: PixelEvent) => {\n if (e.data.pageComponentInteraction) {\n this.push({\n data: e.data,\n event: 'pageComponentInteraction',\n })\n }\n }\n\n private enhanceEvent = (event: PixelData, currency: string) => ({\n currency,\n eventName: `vtex:${event.event}`,\n ...event,\n })\n\n private handlePixelEvent = (event: PixelData) => {\n const eventData = this.enhanceEvent(event, this.props.currency)\n\n try {\n window.postMessage(eventData, window.origin)\n } catch (e) {\n // IE and Edge have a bug on postMessage inside promises.\n // Ignoring for now, will try to find a workaround that\n // makes postMessage work on those browsers.\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14719328/\n }\n }\n}\n\nexport default {\n Pixel: withPixel,\n withPixel,\n PixelProvider,\n usePixel,\n}\n\n```"
}
] |
code_pixel-manager_60b66445
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pixel-manager/react/typings/globals.d.ts from the pixel-manager VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Window extends Window {\n pixelManagerEvents: any[]\n}\n\n```"
}
] |
code_pixel-manager_e84315aa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pixel-manager/react/__tests__/usePixelEventCallback.test.ts from the pixel-manager VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { shouldCallEventHandler } from '../usePixelEventCallback'\nimport type { PixelData } from '../PixelEventTypes'\n\nconst mockPixelEventData: PixelData = {\n id: 'test',\n event: 'addToCart',\n}\n\ndescribe('shouldCallEventHandler function', () => {\n describe('Should not call the event handler', () => {\n it(\"If eventName from input matches 'event' property but eventId doesn't match 'id' property\", () => {\n const eventNameFromInput = 'addToCart'\n const eventIdFromInput = 'not-test'\n\n expect(\n shouldCallEventHandler(\n mockPixelEventData,\n eventIdFromInput,\n eventNameFromInput\n )\n ).toBe(false)\n })\n\n it(\"If id from input matches 'id' property but eventName doesn't match 'event' property\", () => {\n const eventNameFromInput = 'openDrawer'\n const eventIdFromInput = 'test'\n\n expect(\n shouldCallEventHandler(\n mockPixelEventData,\n eventIdFromInput,\n eventNameFromInput\n )\n ).toBe(false)\n })\n\n it(\"If eventName doesn't match 'event' property and no eventId is passed\", () => {\n const eventNameFromInput = 'openDrawer'\n const eventIdFromInput = undefined\n\n expect(\n shouldCallEventHandler(\n mockPixelEventData,\n eventIdFromInput,\n eventNameFromInput\n )\n ).toBe(false)\n })\n\n it(\"If eventId doesn't match 'id' property and no eventName is passed\", () => {\n const eventNameFromInput = undefined\n const eventIdFromInput = 'not-test'\n\n expect(\n shouldCallEventHandler(\n mockPixelEventData,\n eventIdFromInput,\n eventNameFromInput\n )\n ).toBe(false)\n })\n })\n\n describe('Should call the event handler', () => {\n it(\"If eventId and eventName from input match the event's 'id' and 'event' properties\", () => {\n const eventIdFromInput = 'test'\n const eventNameFromInput = 'addToCart'\n\n expect(\n shouldCallEventHandler(\n mockPixelEventData,\n eventIdFromInput,\n eventNameFromInput\n )\n ).toBe(true)\n })\n\n it(\"If eventName from input matches the event's 'event' property and eventId from input is undefined\", () => {\n const eventIdFromInput = undefined\n const eventNameFromInput = 'addToCart'\n\n expect(\n shouldCallEventHandler(\n mockPixelEventData,\n eventIdFromInput,\n eventNameFromInput\n )\n ).toBe(true)\n })\n\n it(\"If eventId from input matches the event's 'id' property and eventName from input is undefined\", () => {\n const eventIdFromInput = 'test'\n const eventNameFromInput = undefined\n\n expect(\n shouldCallEventHandler(\n mockPixelEventData,\n eventIdFromInput,\n eventNameFromInput\n )\n ).toBe(true)\n })\n })\n})\n\n```"
}
] |
code_zendesk-chat_1b39c782
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of zendesk-chat/docs/README.md from the zendesk-chat VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Zendesk Chat\n\nThis app provides a storefront widget for the [Zendesk](https://zendesk.com/) chat functionality to comunicate with your store's customers while they navigate your store.\n\n## Before you start\n\nTo use the chat you need to have an active [Zendesk](https://zendesk.com/) account. Some features are only available for specific plans.\n\n## Installation\n\n1. Open the VTEX App Store and install the [Zendesk Chat](https://apps.vtex.com/vtex-zendesk-chat/p) app on your store.\n2. On VTEX Admin, go to **Extensions Hub > App Management** and click the Zendesk Chat app settings.\n3. Fill in your Zendesk Chat's Account Key, which you can find on Zendesk following [these instructions](https://support.zendesk.com/hc/en-us/articles/4408825772698-How-do-I-find-my-Chat-Account-Key-).\n4. Click `Save`.\n5. Copy the following script and insert it into your website's HTML source code between the `<head>` tags. This code must be inserted into every page where you want to display the Web Widget.\n\n ```html\n <script id=\"ze-snippet\" src=\"https://static.zdassets.com/ekr/snippet.js?key=xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx> </script>\n ```\n> Replace the key value, i.e. `xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`, according to your scenario.\n\n```"
}
] |
code_zendesk-chat_4c284af2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of zendesk-chat/react/index.tsx from the zendesk-chat VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/ban-types */\n/* eslint-disable no-restricted-globals */\nimport { canUseDOM } from 'vtex.render-runtime'\n\nlet fakeBtn: HTMLButtonElement\n\nfunction updateWidgetSettings(o: Record<string, unknown>) {\n window.zE('webWidget', 'updateSettings', o)\n}\n\nfunction setWidgetLocale(locale: string) {\n window.zE('webWidget', 'setLocale', locale)\n}\n\nfunction waitChatToLoad(fn: Function) {\n window.zE(() => window.$zopim(fn))\n}\n\nfunction onWidgetClosed(fn: Function) {\n window.zE('webWidget:on', 'close', fn)\n}\n\nfunction openWidget() {\n window.zE.activate()\n}\n\nfunction shouldOpenChat() {\n const zdStore = JSON.parse(localStorage.getItem('ZD-store') || 'null')\n\n if (zdStore) {\n return zdStore.widgetShown\n }\n\n return localStorage.getItem('zdChatOpen') === 'true'\n}\n\nfunction identifySession() {\n const sessionPromise = window?.__RENDER_8_SESSION__?.sessionPromise\n\n if (!sessionPromise) return\n\n sessionPromise.then((session) => {\n const userEmail: string =\n session?.response?.namespaces?.profile?.email?.value || ''\n\n const firstName: string =\n session?.response?.namespaces?.profile?.firstName?.value || ''\n\n const lastName: string =\n session?.response?.namespaces?.profile?.lastName?.value || ''\n\n const userName = `${firstName} ${lastName}`.trim()\n\n if (userEmail || userName) {\n window.zE.identify({\n name: userName,\n email: userEmail,\n })\n }\n })\n}\n\nfunction bootstrap() {\n const {\n widget: widgetSettings,\n titlePathPreffix = '',\n useAnalytics = false,\n accountKey = null,\n } = window.__zendeskPixel\n\n const IS_MOBILE = window.__RUNTIME__.hints.mobile\n\n const chatTheme = widgetSettings.theme?.theme || widgetSettings.color?.theme\n const btnLabel = widgetSettings.theme?.launcherLabel || 'Chat'\n const btnBgColor = widgetSettings.theme?.launcherColor || chatTheme\n const btnTextColor = widgetSettings.theme?.launcherTextColor\n const btnPosition = widgetSettings.theme?.launcherPosition || 'right'\n const widgetZindex = widgetSettings.theme?.widgetZindex || '999998'\n\n function configureSnippetForVTEX() {\n window.zESettings = window.zESettings || {}\n window.zESettings.analytics = useAnalytics\n\n waitChatToLoad(() => {\n const curLocale = document.documentElement.lang\n\n setWidgetLocale(curLocale)\n\n const titlePath = `${titlePathPreffix}${document.title}`\n\n window.$zopim.livechat.sendVisitorPath({\n url: document.URL,\n title: titlePath,\n })\n\n onWidgetClosed(() => localStorage.setItem('zdChatOpen', 'false'))\n\n identifySession()\n })\n\n const helpCenterSuppress = widgetSettings.helpCenter.suppress\n const { departments } = widgetSettings.chat\n const enabled =\n departments.enabled?.map((value) => {\n const intValue = parseInt(value, 10)\n\n return !isNaN(intValue) ? intValue : value\n }) || []\n\n const select = isNaN(parseInt(departments.select, 10))\n ? departments.select\n : parseInt(departments.select, 10)\n\n const { tags } = departments\n\n updateWidgetSettings({\n webWidget: {\n color: {\n theme: chatTheme,\n launcher: btnBgColor,\n launcherText: btnTextColor,\n },\n position: { horizontal: btnPosition, vertical: 'bottom' },\n zIndex: widgetZindex,\n launcher: {\n label: { '*': btnLabel },\n chatLabel: { '*': btnLabel },\n },\n helpCenter: {\n suppress: helpCenterSuppress,\n },\n chat: {\n departments: {\n enabled,\n select,\n tags,\n },\n },\n },\n })\n }\n\n function addZDSnippet() {\n const script = document.createElement('script')\n\n if (fakeBtn) fakeBtn.disabled = true\n\n script.id = 'ze-snippet'\n script.async = true\n script.src = `https://static.zdassets.com/ekr/snippet.js?key=${accountKey}`\n script.onload = () => {\n const intervalId = setInterval(() => {\n if (window?.zE?.activate == null) {\n return\n }\n\n clearInterval(intervalId)\n\n configureSnippetForVTEX()\n\n openWidget()\n\n if (fakeBtn) {\n document.body.removeChild(fakeBtn)\n }\n }, 400)\n }\n\n document.head.appendChild(script)\n }\n\n function addFakeButton() {\n fakeBtn = document.createElement('button')\n\n fakeBtn.id = 'zendesk-fake-btn'\n fakeBtn.innerHTML = `<svg id=\"zendesk-fake-icon\" x=\"0\" y=\"0\" viewBox=\"0 0 15 16\" xml:space=\"preserve\" aria-hidden=\"true\"><path d=\"M1.3,16c-0.7,0-1.1-0.3-1.2-0.8c-0.3-0.8,0.5-1.3,0.8-1.5c0.6-0.4,0.9-0.7,1-1c0-0.2-0.1-0.4-0.3-0.7c0,0,0-0.1-0.1-0.1 C0.5,10.6,0,9,0,7.4C0,3.3,3.4,0,7.5,0C11.6,0,15,3.3,15,7.4s-3.4,7.4-7.5,7.4c-0.5,0-1-0.1-1.5-0.2C3.4,15.9,1.5,16,1.5,16 C1.4,16,1.4,16,1.3,16z M3.3,10.9c0.5,0.7,0.7,1.5,0.6,2.2c0,0.1-0.1,0.3-0.1,0.4c0.5-0.2,1-0.4,1.6-0.7c0.2-0.1,0.4-0.2,0.6-0.1 c0,0,0.1,0,0.1,0c0.4,0.1,0.9,0.2,1.4,0.2c3,0,5.5-2.4,5.5-5.4S10.5,2,7.5,2C4.5,2,2,4.4,2,7.4c0,1.2,0.4,2.4,1.2,3.3 C3.2,10.8,3.3,10.8,3.3,10.9z\"></path></svg><span>${btnLabel}</span>`\n\n fakeBtn.className =\n 'flex items-center justify-center b br-pill bg-base--inverted c-on-base--inverted pointer'\n\n if (btnTextColor) fakeBtn.style.color = btnTextColor\n if (btnBgColor) fakeBtn.style.backgroundColor = btnBgColor\n\n fakeBtn.addEventListener('click', () => {\n localStorage.setItem('zdChatOpen', 'true')\n addZDSnippet()\n })\n\n document.head.insertAdjacentHTML(\n 'beforeend',\n `<style>\n #zendesk-fake-btn {\n position: fixed;\n ${btnPosition}: 0;\n bottom: 0;\n margin: 15px 20px;\n ${IS_MOBILE ? 'padding: .9em;' : 'padding: .9em 1.5em;'}\n opacity: 1;\n border: 0px;\n z-index: ${widgetZindex};\n font-size: 15px;\n -webkit-appearance: none;\n }\n #zendesk-fake-icon {\n ${!IS_MOBILE ? 'padding-right: 0.57143em;' : ''}\n fill: currentColor;\n width: 1.42em;\n height: 1.42em;\n }\n #zendesk-fake-btn span {\n font-size: 1.1em;\n ${IS_MOBILE ? `display: none;` : ''}\n }\n </style>`\n )\n\n document.body.appendChild(fakeBtn)\n }\n\n if (shouldOpenChat()) {\n addZDSnippet()\n } else {\n addFakeButton()\n }\n}\n\nif (canUseDOM && window.__zendeskPixel) {\n bootstrap()\n}\n\n```"
}
] |
code_zendesk-chat_19692531
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of zendesk-chat/react/package.json from the zendesk-chat VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.5\",\n \"@types/node\": \"^13.11.0\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"apollo-client\": \"^2.6.8\",\n \"graphql\": \"^14.5.4\",\n \"react-intl\": \"^3.11.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.pixel-interfaces\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-interfaces@1.1.1/public/_types/react\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.124.2/public/@types/vtex.render-runtime\"\n },\n \"version\": \"1.4.2\"\n}\n\n```"
}
] |
code_zendesk-chat_1d65a237
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of zendesk-chat/store/interfaces.json from the zendesk-chat VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"pixel.zendesk-chat\": {\n \"component\": \"index\"\n }\n}\n\n```"
}
] |
code_zendesk-chat_8cf6b28e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of zendesk-chat/react/typings/zendesk.d.ts from the zendesk-chat VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/ban-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n// modified from https://gist.github.com/vsaarinen/b0e2dcaf4f7c522d4ff1f672eb996f73\ninterface ZendeskWidget {\n (\n type: 'webWidget:on' | 'webWidget' | 'webWidget:get',\n command: string,\n payload?: any\n ): void\n (type: 'webWidget', command: 'updateSettings', payload: ZendeskSettings): void\n (fn: Function): void\n\n activate: Function\n identify: Function\n}\n\ninterface ZendeskUIString {\n [locale: string]: string\n}\n\ninterface ZendeskField {\n id: string | number\n prefill: ZendeskUIString\n}\n\ninterface ZendeskSettings {\n analytics?: boolean\n cookies?: boolean\n errorReporting?: boolean\n webWidget?: {\n answerBot?: {\n avatar?: {\n url: string\n name: ZendeskUIString\n }\n suppress?: boolean\n title?: ZendeskUIString\n contactOnlyAfterQuery?: boolean\n search?: {\n labels: string[]\n }\n }\n authenticate?: {\n chat?: {\n jwtFn: (callback: (jwtToken: string) => void) => void\n }\n jwtFn?: (callback: (jwtToken: string) => void) => void\n }\n contactForm?: {\n attachments?: boolean\n fields?: ZendeskField[]\n selectTicketForm?: ZendeskUIString\n subject?: boolean\n suppress?: boolean\n title?: ZendeskUIString\n ticketForms?: Array<{ id: number; fields?: ZendeskField[] }>\n }\n contactOptions?: {\n enabled?: boolean\n contactButton?: ZendeskUIString\n contactFormLabel?: ZendeskUIString\n chatLabelOnline?: ZendeskUIString\n chatLabelOffline?: ZendeskUIString\n }\n chat?: {\n concierge?: {\n avatarPath: string\n name: string\n title: ZendeskUIString\n }\n departments?: {\n enabled: string[]\n select?: string\n }\n hideWhenOffline?: boolean\n menuOptions?: {\n emailTranscript?: boolean\n }\n notifications?: {\n mobile?: {\n disable?: boolean\n }\n }\n offlineForm?: {\n greeting?: ZendeskUIString\n }\n prechatForm?: {\n greeting?: ZendeskUIString\n departmentLabel?: ZendeskUIString\n }\n profileCard?: {\n avatar?: boolean\n rating?: boolean\n title?: boolean\n }\n suppress?: boolean\n tags?: string\n title?: ZendeskUIString\n }\n color?: {\n theme?: string\n launcher?: string\n launcherText?: string\n button?: string\n resultLists?: string\n header?: string\n articleLinks?: string\n }\n helpCenter?: {\n messageButton?: ZendeskUIString\n originalArticleButton?: boolean\n searchPlaceholder?: ZendeskUIString\n suppress?: boolean\n title?: ZendeskUIString\n chatButton?: ZendeskUIString\n filter?: {\n category?: string\n section?: string\n label_names?: string\n }\n }\n launcher?: {\n label?: ZendeskUIString\n mobile?: {\n labelVisible?: boolean\n }\n badge?: {\n label?: ZendeskUIString\n image?: string\n layout?: 'image_right' | 'image_left' | 'image_only' | 'text_only'\n }\n chatLabel?: ZendeskUIString\n }\n navigation?: {\n popoutButton?: {\n enabled?: boolean\n }\n }\n offset?: {\n horizontal?: string\n vertical?: string\n mobile?: {\n horizontal?: string\n vertical?: string\n }\n }\n position?: {\n horizontal: 'left' | 'right'\n vertical: 'top' | 'bottom'\n }\n talk?: {\n nickname?: string\n suppress?: boolean\n title?: ZendeskUIString\n }\n zIndex?: number\n }\n}\n\n```"
}
] |
code_zendesk-chat_ddbdc45f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of zendesk-chat/react/typings/global.d.ts from the zendesk-chat VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\n/* eslint-disable @typescript-eslint/naming-convention */\nimport type { useRuntime } from 'vtex.render-runtime'\n\nexport {}\n\ndeclare global {\n interface Window {\n __RUNTIME__: ReturnType<typeof useRuntime>\n\n __RENDER_8_SESSION__: {\n sessionPromise: Promise<{ response: any }>\n }\n\n __zendeskPixel: {\n widget: {\n // @deprecated. Use `theme`\n color?: {\n theme: string\n }\n theme: {\n launcherLabel: string\n launcherColor: string\n launcherTextColor: string\n launcherPosition: string\n theme: string\n widgetZindex: string\n }\n helpCenter: {\n suppress: unknown\n }\n chat: {\n departments: {\n enabled: string[]\n select: string\n tags: string[]\n }\n }\n }\n titlePathPreffix: string\n useAnalytics: boolean\n accountKey: string\n }\n\n zESettings: ZendeskSettings\n zE: ZendeskWidget\n\n $zopim: {\n (arg: Function): unknown\n livechat: {\n sendVisitorPath: Function\n }\n }\n }\n}\n\n```"
}
] |
code_buybox-resolver_eddbf4f0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/docs/README.md from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# VTEX Buybox Resolver\n\n> ⚠️ This app is no longer maintained by VTEX. This means support and maintenance are no longer provided.\n\nThis app is an implementation of the VTEX Buybox protocol to sort sellers, that is defined by the schema GraphQL [buybox-graphql](https://github.com/vtex-apps/buybox-graphql).\n\n```"
}
] |
code_buybox-resolver_d83e64a6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/graphql/schema.graphql from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\n# To really understand GraphQL, go to https://graphql.org/learn/\n\ntype Book {\n authors: [String!]\n cacheId: ID!\n id: ID!\n name: String\n}\n\n# It is necessary to generate input types for creating books\n# ref: http://graphql.org/graphql-js/mutations-and-input-types/\ninput BookInput {\n authors: [String!]\n cacheId: ID\n id: ID\n name: String\n}\n\ntype Query {\n # Cache control can only be set at root fields\n book(id: ID!): Book\n books(from: Int = 0, to: Int = 4): [Book] @cacheControl(scope: PUBLIC, maxAge: SHORT)\n total: Int\n\n \"\"\"\n Returns a markdown source given an id\n \"\"\"\n source(id: ID!): String\n}\n\ntype Mutation {\n # You should always return the whole object in a mutation, not only a boolean. This will help in browser caching\n delete(id: String): Boolean\n editBook(id: ID!, book: BookInput!): Book\n newBook(book: BookInput!): Book\n}\n\n```"
}
] |
code_buybox-resolver_d532779a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/service.json from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 1,\n \"minReplicas\": 2,\n \"maxReplicas\": 5\n}\n\n```"
}
] |
code_buybox-resolver_0adcdfb5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/package.json from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"@gocommerce/utils\": \"^0.6.11\",\n \"atob\": \"^2.1.2\",\n \"axios\": \"^0.23.0\",\n \"graphql\": \"^14.5.8\",\n \"graphql-tools\": \"^4.0.6\",\n \"qs\": \"^6.6.0\",\n \"vtex.buybox-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.buybox-graphql@0.1.0/public\",\n \"ramda\": \"^0.26.1\"\n },\n \"devDependencies\": {\n \"@types/atob\": \"^2.1.2\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/node\": \"^12.0.0\",\n \"@types/qs\": \"^6.5.1\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.4\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"typescript\": \"3.9.7\",\n \"vtex.buybox-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.buybox-graphql@0.1.0/public/@types/vtex.buybox-graphql\",\n \"vtex.catalog-api-proxy\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.catalog-api-proxy@0.10.2/public/_types/react\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit && tslint -c tslint.json './**/*.ts'\"\n },\n \"version\": \"0.1.2\"\n}\n\n```"
}
] |
code_buybox-resolver_6d821823
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/globals.ts from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n IOContext,\n ParamsContext,\n RecorderState,\n SegmentData,\n ServiceContext,\n MessagesLoaderV2,\n} from '@vtex/api'\nimport { MetricsAccumulator } from '@vtex/api'\n\nimport type { Clients } from './clients'\n\nif (!global.metrics) {\n console.error('No global.metrics at require time')\n global.metrics = new MetricsAccumulator()\n}\n\ndeclare global {\n type Context = ServiceContext<Clients, State, CustomContext>\n\n interface State extends RecorderState {\n messagesTenantLanguage?: MessagesLoaderV2\n messagesBindingLanguage?: MessagesLoaderV2\n }\n\n interface CustomContext extends ParamsContext {\n cookie: string\n originalPath: string\n vtex: CustomIOContext\n }\n\n interface CustomIOContext extends IOContext {\n segment?: SegmentData\n }\n}\n\n```"
}
] |
code_buybox-resolver_7bc28df6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/index.ts from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Cached, RecorderState } from '@vtex/api'\nimport { LRUCache, Service } from '@vtex/api'\nimport schema from 'vtex.buybox-graphql/graphql'\n\nimport { Clients } from './clients'\nimport { schemaDirectives } from './directives'\nimport { resolvers } from './resolvers'\n\nconst THREE_SECONDS_MS = 3 * 1000\n\nconst searchCache = new LRUCache<string, Cached>({ max: THREE_SECONDS_MS })\n\nmetrics.trackCache('search', searchCache)\n\nexport default new Service<Clients, RecorderState, CustomContext>({\n clients: {\n implementation: Clients,\n options: {\n default: {\n retries: 2,\n timeout: THREE_SECONDS_MS,\n },\n },\n },\n graphql: {\n resolvers,\n schema,\n schemaDirectives,\n },\n})\n\n```"
}
] |
code_buybox-resolver_1da4210a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/directives/withSegment.ts from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\nimport atob from 'atob'\n\n/**\n * Warning: we stopped using the segment client to decode the segment token for us because it added unnecessary overhead for now.\n * If the getSegment API evolves to do more than a decode we must stop decoding it here and start calling the API once again.\n */\nexport class WithSegment extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root, args, ctx: Context, info) => {\n const {\n vtex: { segmentToken },\n clients: { segment },\n } = ctx\n\n ctx.vtex.segment = segmentToken\n ? JSON.parse(atob(segmentToken))\n : await segment.getSegment()\n\n return resolve(root, args, ctx, info)\n }\n }\n}\n\n```"
}
] |
code_buybox-resolver_3b72e409
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/directives/index.ts from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { WithSegment } from './withSegment'\n\nexport const schemaDirectives = {\n withSegment: WithSegment,\n}\n\n```"
}
] |
code_buybox-resolver_5b9d27fc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/clients/search.ts from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n InstanceOptions,\n IOContext,\n RequestConfig,\n SegmentData,\n} from '@vtex/api'\nimport { AppClient } from '@vtex/api'\nimport { stringify } from 'qs'\n\nconst inflightKey = ({ baseURL, url, params, headers }: RequestConfig) => {\n return `${\n baseURL! +\n url! +\n stringify(params, { arrayFormat: 'repeat', addQueryPrefix: true })\n }&segmentToken=${headers['x-vtex-segment']}`\n}\n\nexport class Search extends AppClient {\n private basePath: string\n\n private addSalesChannel = (url: string, salesChannel?: string | number) => {\n if (!salesChannel) {\n return url\n }\n\n return url.concat(`&sc=${salesChannel}`)\n }\n\n private addCompleteSpecifications = (url: string) => {\n if (!url.includes('?')) {\n return `${url}?compSpecs=true`\n }\n\n return `${url}&compSpecs=true`\n }\n\n constructor(ctx: IOContext, opts?: InstanceOptions) {\n super('vtex.catalog-api-proxy@0.x', ctx, opts)\n\n this.basePath = ctx.sessionToken\n ? '/proxy/authenticated/catalog'\n : '/proxy/catalog'\n }\n\n public productBySku = (skuId: string, salesChannel?: string | number) =>\n this.get<SearchProduct[]>(\n this.addCompleteSpecifications(\n this.addSalesChannel(\n `/pub/products/search?fq=skuId:${skuId}`,\n salesChannel\n )\n ),\n {\n metric: 'search-productBySku',\n }\n )\n\n private get = <T = any>(url: string, config: RequestConfig = {}) => {\n const segmentData: SegmentData | undefined = (\n this.context as CustomIOContext\n ).segment\n\n const { channel: salesChannel = '' } = segmentData ?? {}\n\n config.params = {\n ...config.params,\n ...(!!salesChannel && { sc: salesChannel }),\n }\n config.inflightKey = inflightKey\n\n return this.http.get<T>(`${this.basePath}${url}`, config)\n }\n}\n\n```"
}
] |
code_buybox-resolver_bb2114d2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/clients/checkout.ts from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext, RequestConfig } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nimport { statusToError } from '../utils'\n\nexport class Checkout extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n },\n })\n }\n\n private getChannelQueryString = () => {\n const { segment } = this.context as CustomIOContext\n const channel = segment?.channel\n const queryString = channel ? `?sc=${channel}` : ''\n\n return queryString\n }\n\n public simulation = (simulation: SimulationPayload) =>\n this.post<OrderForm>(\n this.routes.simulation(this.getChannelQueryString()),\n simulation,\n {\n metric: 'checkout-simulation',\n }\n )\n\n protected post = <T>(url: string, data?: any, config: RequestConfig = {}) => {\n return this.http\n .post<T>(url, data, config)\n .catch(statusToError) as Promise<T>\n }\n\n private get routes() {\n const base = '/api/checkout/pub'\n\n return {\n simulation: (queryString: string) =>\n `${base}/orderForms/simulation${queryString}`,\n }\n }\n}\n\n```"
}
] |
code_buybox-resolver_78a66059
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/clients/index.ts from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport { Search } from './search'\nimport { Checkout } from './checkout'\n\nexport class Clients extends IOClients {\n public get search() {\n return this.getOrSet('search', Search)\n }\n\n public get checkout() {\n return this.getOrSet('checkout', Checkout)\n }\n}\n\n```"
}
] |
code_buybox-resolver_6c60af8c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/typings/Checkout.ts from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface OrderFormMarketingData {\n utmCampaign?: string\n utmMedium?: string\n utmSource?: string\n utmiCampaign?: string\n utmiPart?: string\n utmipage?: string\n marketingTags?: string\n}\n\ninterface CheckoutAddress {\n addressType: string\n receiverName: string\n addressId: string\n postalCode: string\n city: string\n state: string\n country: string\n street: string\n number: string\n neighborhood: string\n complement: string\n reference: string | null\n geoCoordinates: [number, number]\n}\n\ninterface OrderFormItem {\n id: string\n name: string\n detailUrl: string\n imageUrl: string\n productRefId: string\n skuName: string\n quantity: number\n uniqueId: string\n productId: string\n refId: string\n ean: string\n priceValidUntil: string\n price: number\n tax: number\n listPrice: number\n sellingPrice: number\n rewardValue: number\n isGift: boolean\n parentItemIndex: number | null\n parentAssemblyBinding: string | null\n productCategoryIds: string\n priceTags: string[]\n measurementUnit: string\n additionalInfo: {\n brandName: string\n brandId: string\n offeringInfo: any | null\n offeringType: any | null\n offeringTypeId: any | null\n }\n productCategories: Record<string, string>\n seller: string\n sellerChain: string[]\n availability: string\n unitMultiplier: number\n}\n\ninterface LogisticsInfo {\n itemIndex: number\n selectedSla: string\n selectedDeliveryChannel: string\n addressId: string\n slas: Array<{\n id: string\n deliveryChannel: string\n name: string\n deliveryIds: Array<{\n courierId: string\n warehouseId: string\n dockId: string\n courierName: string\n quantity: number\n }>\n shippingEstimate: string\n shippingEstimateDate: string | null\n lockTTL: string | null\n availableDeliveryWindows: any[]\n deliveryWindow: string | null\n price: number\n listPrice: number\n tax: number\n pickupStoreInfo: {\n isPickupStore: boolean\n friendlyName: string | null\n\n address: CheckoutAddress | null\n additionalInfo: any | null\n dockId: string | null\n }\n pickupPointId: string | null\n pickupDistance: number\n polygonName: string | null\n }>\n shipsTo: string[]\n itemId: string\n deliveryChannels: Array<{ id: string }>\n}\n\ninterface OrderForm {\n items: OrderFormItem[]\n ratesAndBenefitsData: {\n rateAndBenefitsIdentifiers: any[]\n teaser: any[]\n }\n paymentData: {\n installmentOptions: Array<{\n paymentSystem: string\n bin: string | null\n paymentName: string | null\n paymentGroupName: string | null\n value: number\n installments: Array<{\n count: number\n hasInterestRate: false\n interestRate: number\n value: number\n total: number\n sellerMerchantInstallments: Array<{\n count: number\n hasInterestRate: false\n interestRate: number\n value: number\n total: number\n }>\n }>\n }>\n paymentSystems: Array<{\n id: string\n name: string\n groupName: string\n validator: {\n regex: string\n mask: string\n cardCodeRegex: string\n cardCodeMask: string\n weights: number[]\n useCvv: boolean\n useExpirationDate: boolean\n useCardHolderName: boolean\n useBillingAddress: boolean\n }\n stringId: string\n template: string\n requiresDocument: boolean\n isCustom: boolean\n description: string | null\n requiresAuthentication: boolean\n dueDate: string\n availablePayments: any | null\n }>\n payments: any[]\n giftCards: any[]\n giftCardMessages: any[]\n availableAccounts: any[]\n availableTokens: any[]\n }\n selectableGifts: any[]\n logisticsInfo: LogisticsInfo[]\n marketingData: OrderFormMarketingData | null\n postalCode: string\n country: string\n messages: any[]\n subscriptionData: any | null\n itemMetadata: {\n items: MetadataItem[]\n }\n}\n\ninterface PayloadItem {\n id: string\n quantity: number\n seller: string\n parentItemIndex?: number | null\n parentAssemblyBinding?: string | null\n}\n\ninterface SimulationPayload {\n country?: string\n items: PayloadItem[]\n postalCode?: string\n isCheckedIn?: boolean\n priceTables?: string[]\n marketingData?: Record<string, string>\n}\n\n```"
}
] |
code_buybox-resolver_eee35de3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of buybox-resolver/node/typings/ItemMetadata.ts from the buybox-resolver VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/**\n * Assembly options related types\n */\n\ninterface CompositionItem {\n id: string\n minQuantity: number\n maxQuantity: number\n initialQuantity: number\n priceTable: string\n seller: string\n}\n\ninterface Composition {\n minQuantity: number\n maxQuantity: number\n items: CompositionItem[]\n}\n\ninterface AssemblyOption {\n id: string\n name: string\n composition: Composition | null\n inputValues: InputValues\n}\n\ninterface InputValues {\n [key: string]: RawInputValue\n}\n\ninterface RawInputValue {\n maximumNumberOfCharacters: number\n domain: string[]\n}\n\ninterface SearchMetadataItem {\n Name: string\n NameComplete: string\n MainImage: string\n BrandName: string\n CategoryId: number\n ProductId: number\n id: string\n seller: string\n assemblyOptions: AssemblyOption[]\n}\n\ninterface MetadataItem {\n id: string\n name: string\n imageUrl: string\n detailUrl: string\n seller: string\n assemblyOptions: AssemblyOption[]\n skuName: string\n productId: string\n refId: string\n ean: string | null\n}\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.