id
stringlengths
12
53
messages
listlengths
3
3
code_butik_b4b4007f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/es/SKUSelector/components2/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nimport React, { Component } from 'react';\nimport { withRuntimeContext } from 'render';\n\nimport SKUSelector from './SKUSelector';\nimport { SKUSelectorContainerPropTypes } from '../utils/proptypes';\nimport { getMainVariationName, getVariationOptions, getMaxSkuPrice, parseSku } from '../utils/index';\n\nimport './global.css';\n\n/**\n * Display a list of SKU items of a product and its specifications.\n */\n\nvar SKUSelectorContainer = function (_Component) {\n _inherits(SKUSelectorContainer, _Component);\n\n function SKUSelectorContainer() {\n var _temp, _this, _ret;\n\n _classCallCheck(this, SKUSelectorContainer);\n\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.handleSkuSelection = function (skuId) {\n _this.props.onSKUSelected ? _this.props.onSKUSelected(skuId) : _this.redirectToSku(skuId);\n }, _temp), _possibleConstructorReturn(_this, _ret);\n }\n\n SKUSelectorContainer.prototype.redirectToSku = function redirectToSku(skuId) {\n var navigate = this.props.runtime.navigate;\n\n var slug = this.props.productSlug;\n\n navigate({\n page: 'store/product',\n params: { slug: slug },\n query: 'skuId=' + skuId\n });\n };\n\n SKUSelectorContainer.prototype.render = function render() {\n if (!this.props.skuSelected || !this.props.skuSelected.variations || this.props.skuSelected.variations.length === 0) return null;\n\n var skuSelected = this.props.skuSelected && parseSku(this.props.skuSelected);\n var skuItems = this.props.skuItems && this.props.skuItems.map(function (sku) {\n return parseSku(sku);\n });\n var itemId = skuSelected.itemId;\n var variations = skuSelected.variations;\n\n var name = getMainVariationName(variations);\n var mainVariation = {\n name: name,\n value: skuSelected[name],\n options: getVariationOptions(name, skuItems)\n };\n\n var maxSkuPrice = getMaxSkuPrice(skuItems);\n var secondaryVariation = {};\n\n var filteredSkus = skuItems.filter(function (sku) {\n return sku[name] === mainVariation.value;\n });\n\n if (variations.length > 1) {\n secondaryVariation.name = variations.filter(function (variation) {\n return variation !== name;\n })[0];\n secondaryVariation.options = getVariationOptions(secondaryVariation.name, filteredSkus);\n }\n\n return React.createElement(SKUSelector, {\n mainVariation: mainVariation,\n secondaryVariation: secondaryVariation,\n onSelectSku: this.handleSkuSelection,\n maxSkuPrice: maxSkuPrice,\n selectedId: itemId\n });\n };\n\n return SKUSelectorContainer;\n}(Component);\n\nSKUSelectorContainer.propTypes = process.env.NODE_ENV !== \"production\" ? SKUSelectorContainerPropTypes : {};\n\nexport default withRuntimeContext(SKUSelectorContainer);\n```" } ]
code_butik_0fa4a11b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/es/SKUSelector/components2/SKUSelector.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nimport React, { Component } from 'react';\n\nimport Variation from './Variation';\nimport { SKUSelectorPropTypes } from '../utils/proptypes';\n\n/** Renders the main and the secondary variation, if it exists. */\n\nvar SKUSelector = function (_Component) {\n _inherits(SKUSelector, _Component);\n\n function SKUSelector() {\n _classCallCheck(this, SKUSelector);\n\n return _possibleConstructorReturn(this, _Component.apply(this, arguments));\n }\n\n SKUSelector.prototype.render = function render() {\n var _props = this.props,\n selectedId = _props.selectedId,\n onSelectSku = _props.onSelectSku,\n mainVariation = _props.mainVariation,\n secondaryVariation = _props.secondaryVariation,\n maxSkuPrice = _props.maxSkuPrice;\n\n\n return React.createElement(\n 'div',\n { className: 'vtex-sku-selector' },\n React.createElement(Variation, {\n variation: mainVariation,\n onSelectItem: onSelectSku,\n isSelected: function isSelected(sku) {\n return sku[mainVariation.name] === mainVariation.value;\n },\n maxSkuPrice: maxSkuPrice\n }),\n secondaryVariation.name && React.createElement(Variation, {\n variation: secondaryVariation,\n onSelectItem: onSelectSku,\n isSelected: function isSelected(sku) {\n return sku.itemId === selectedId;\n },\n maxSkuPrice: maxSkuPrice\n })\n );\n };\n\n return SKUSelector;\n}(Component);\n\nexport { SKUSelector as default };\n\n\nSKUSelector.propTypes = process.env.NODE_ENV !== \"production\" ? SKUSelectorPropTypes : {};\n```" } ]
code_butik_aa21c807
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/es/SKUSelector/components2/Variation.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nimport React, { Component } from 'react';\n\nimport SelectorItem from './SelectorItem';\nimport { stripUrl, isColor } from '../utils';\n\nvar Variation = function (_Component) {\n _inherits(Variation, _Component);\n\n function Variation() {\n _classCallCheck(this, Variation);\n\n return _possibleConstructorReturn(this, _Component.apply(this, arguments));\n }\n\n Variation.prototype.render = function render() {\n var _props = this.props,\n variation = _props.variation,\n onSelectItem = _props.onSelectItem,\n maxSkuPrice = _props.maxSkuPrice,\n isSelected = _props.isSelected;\n\n\n var displayImage = isColor(variation.name);\n\n return React.createElement(\n 'div',\n { className: 'vtex-sku-selector__container flex flex-column mb7' },\n React.createElement(\n 'div',\n { className: 'vtex-sku-selector__name-container ma1' },\n React.createElement(\n 'span',\n { className: 'vtex-sku-selector__name c-muted-2 db t-small overflow-hidden mb3' },\n variation.name\n ),\n React.createElement(\n 'div',\n { className: 'inline-flex flex-wrap ml2' },\n variation.options.map(function (skuItem) {\n if (!skuItem.images.length) return null;\n var _skuItem$images = skuItem.images,\n skuImage = _skuItem$images[0];\n var _skuItem$sellers = skuItem.sellers,\n seller = _skuItem$sellers[0];\n\n return React.createElement(\n SelectorItem,\n {\n isSelected: isSelected(skuItem),\n key: skuItem.itemId,\n isAvailable: seller.commertialOffer.AvailableQuantity > 0,\n maxPrice: maxSkuPrice,\n skuId: skuItem.itemId,\n price: seller.commertialOffer.Price,\n onClick: function onClick() {\n return onSelectItem(skuItem.itemId);\n },\n isImage: displayImage },\n displayImage ? React.createElement('img', {\n src: stripUrl(skuImage.imageUrl),\n alt: skuImage.imageLabel\n }) : React.createElement(\n 'span',\n { className: 'c-on-base t-body' },\n skuItem[variation.name]\n )\n );\n })\n )\n )\n );\n };\n\n return Variation;\n}(Component);\n\nexport { Variation as default };\n```" } ]
code_butik_6fcd4d52
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport BlurredLoader from './BlurredLoader'\nimport Carousel from './Carousel'\nimport GradientCollapse from './GradientCollapse'\nimport ImageResizer from './ImageResizer'\nimport ProductDescription from './ProductDescription'\nimport ProductName from './ProductName'\nimport ProductPrice from './ProductPrice'\nimport SKUSelector from './SKUSelector'\nimport Video from './Video'\nimport FixedButton from './FixedButton'\n\nexport {\n BlurredLoader,\n Carousel,\n GradientCollapse,\n ImageResizer,\n ProductDescription,\n ProductName,\n ProductPrice,\n SKUSelector,\n Video,\n FixedButton,\n}\n\n```" } ]
code_butik_a91de43d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/Video/Vimeo.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nclass Vimeo extends Component {\n static getThumbUrl = (url, thumbWidth) =>\n new Promise((resolve, reject) => {\n const getUrl = `https://vimeo.com/api/oembed.json?url=${url}`\n fetch(getUrl)\n .then(response => {\n return response.json()\n })\n .then(response => {\n resolve(Vimeo.thumbUrlFromResp(response, thumbWidth))\n })\n .catch(() => reject())\n })\n\n static thumbUrlFromResp(response, thumbWidth) {\n const { height, width } = response\n const thumb = response.thumbnail_url_with_play_button\n\n thumbWidth = thumbWidth || response.thumbnail_width\n const thumbHeight = Math.ceil((thumbWidth * height) / width)\n\n return thumb.replace(\n /_[0123456789]*x[0123456789]*./,\n `_${thumbWidth}x${thumbHeight}.`\n )\n }\n\n constructor(props) {\n super(props)\n\n this.state = { iframe: {} }\n\n const { loop, autoplay, width, height, showTitle, url } = this.props\n const params = `autoplay=${autoplay}&loop=${loop}&title=${showTitle}&width=${width}&height=${height}`\n const getUrl = `https://vimeo.com/api/oembed.json?url=${url}&${params}`\n\n this.iframeRef = React.createRef()\n\n fetch(getUrl)\n .then(response => {\n return response.json()\n })\n .then(response => {\n const { height, width, html, title } = response\n\n const thumbUrl = Vimeo.thumbUrlFromResp(response, props.thumbWidth)\n props.setThumb && props.setThumb(thumbUrl, title)\n\n const src = html.match(/src= *\" *([^\"]*) *\"/)[1] // Get url from response\n\n this.setState({\n iframe: {\n divStyle: { padding: `${(100 * height) / width}% 0 0 0` },\n src: src,\n },\n })\n })\n }\n\n componentDidMount() {\n this.iframeRef.current.onload = () => (this.frameReady = true)\n }\n\n executeCommand = command => () => {\n if (!this.frameReady) return\n\n const vimeoCommand = JSON.stringify({ method: command })\n this.iframeRef.current.contentWindow.postMessage(\n vimeoCommand,\n 'https://player.vimeo.com'\n )\n }\n\n render() {\n const { iframe } = this.state\n const { className, id } = this.props\n\n this.props.playing\n ? this.executeCommand('play')()\n : this.executeCommand('pause')()\n\n return (\n <div style={iframe.divStyle} className={`relative ${className}`}>\n <iframe\n ref={this.iframeRef}\n title={id}\n className=\"absolute top-0 left-0 w-100 h-100\"\n src={iframe.src}\n frameBorder=\"0\"\n allowFullScreen\n allow=\"autoplay\"\n />\n </div>\n )\n }\n}\n\nVimeo.propTypes = {\n url: PropTypes.string.isRequired,\n id: PropTypes.number.isRequired, // Unique ID for iframe title\n setThumb: PropTypes.func,\n thumbWidth: PropTypes.number,\n className: PropTypes.string,\n loop: PropTypes.bool,\n autoplay: PropTypes.bool,\n showTitle: PropTypes.bool,\n width: PropTypes.number,\n height: PropTypes.number,\n playing: PropTypes.bool,\n}\n\nVimeo.defaultProps = {\n loop: true,\n autoplay: false,\n width: null,\n height: null,\n showTitle: false,\n className: '',\n}\n\nexport default Vimeo\n\n```" } ]
code_butik_c2ce3627
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/Video/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport Vimeo from './Vimeo'\nimport Youtube from './Youtube'\n\nclass Video extends Component {\n static getThumbUrl(url, thumbWidth, apiKey) {\n if (url.search('vimeo') !== -1) {\n return Vimeo.getThumbUrl(url, thumbWidth)\n }\n if (url.search('youtube') !== -1) {\n return Youtube.getThumbUrl(url, apiKey)\n }\n return Promise.reject(`Unsupported video url format, ${url}`)\n }\n\n render() {\n const { url } = this.props\n if (url.search('vimeo') !== -1) {\n return <Vimeo {...this.props} />\n }\n if (url.search('youtube') !== -1) {\n return <Youtube {...this.props} />\n }\n return null\n }\n}\n\nVideo.propTypes = {\n /** Video url */\n url: PropTypes.string.isRequired,\n /** Unique id for iFrame */\n id: PropTypes.number.isRequired,\n /** Function that receives the video thumbnail URL as prop */\n setThumb: PropTypes.func,\n /** Desired width for the thumbnail retrieved by the function above */\n thumbWidth: PropTypes.number,\n className: PropTypes.string,\n /** Dynamic prop that pauses and plays the video */\n play: PropTypes.bool,\n apiKey: PropTypes.string,\n}\n\nexport default Video\n\n```" } ]
code_butik_e078889a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/Video/Youtube.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nclass Youtube extends Component {\n static getThumbUrl = (url, apiKey) =>\n new Promise((resolve, reject) => {\n const videoId = Youtube.extractVideoID(url)\n const getUrl = `https://www.googleapis.com/youtube/v3/videos?part=snippet&id=${videoId}&key=${apiKey}`\n fetch(getUrl)\n .then(responseonse => {\n return responseonse.json()\n })\n .then(response => {\n if (response.items.length === 0) {\n reject(`No video found with URL: ${url} and apiKey: ${apiKey}`)\n return\n }\n response = response.items[0].snippet\n\n resolve(response.thumbnails.default.url)\n })\n })\n\n constructor(props) {\n super(props)\n\n this.state = { iframe: {} }\n\n const { loop, autoplay, url, apiKey } = this.props\n const params = `autoplay=${autoplay}&loop=${loop}&enablejsapi=1&iv_load_policy=3&modestbranding=1`\n const videoId = Youtube.extractVideoID(url)\n const getUrl = `https://www.googleapis.com/youtube/v3/videos?part=snippet&id=${videoId}&key=${apiKey}`\n\n this.iframeRef = React.createRef()\n\n fetch(getUrl)\n .then(responseonse => {\n return responseonse.json()\n })\n .then(response => {\n if (response.items.length === 0) return\n response = response.items[0].snippet\n\n const { title } = response\n const { width, height } = response.thumbnails.default\n const thumbUrl = response.thumbnails.default.url\n props.setThumb && props.setThumb(thumbUrl, title)\n\n const src = `https://www.youtube.com/embed/${videoId}?${params}`\n\n this.setState({\n iframe: {\n divStyle: { padding: `${(100 * height) / width}% 0 0 0` },\n src: src,\n },\n })\n })\n }\n\n static extractVideoID = url => {\n const regExp = /^.*((youtu.be\\/)|(v\\/)|(\\/u\\/\\w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#&?]*).*/\n const match = url.match(regExp)\n if (match && match[7].length === 11) {\n return match[7]\n }\n console.error('Could not extract youtube video ID')\n return ''\n }\n\n componentDidMount() {\n this.iframeRef.current.onload = () => (this.frameReady = true)\n }\n\n executeCommand = command => () => {\n if (!this.frameReady) return\n\n const youtubeCommand = JSON.stringify({ event: 'command', func: command })\n this.iframeRef.current.contentWindow.postMessage(\n youtubeCommand,\n 'https://www.youtube.com'\n )\n }\n\n render() {\n const { iframe } = this.state\n const { className, id } = this.props\n\n this.props.playing\n ? this.executeCommand('playVideo')()\n : this.executeCommand('pauseVideo')()\n\n return (\n <div style={iframe.divStyle} className={`relative ${className}`}>\n <iframe\n ref={this.iframeRef}\n title={id}\n className=\"absolute top-0 left-0 w-100 h-100\"\n src={iframe.src}\n frameBorder=\"0\"\n allowFullScreen\n allow=\"autoplay\"\n />\n </div>\n )\n }\n}\n\nYoutube.propTypes = {\n url: PropTypes.string.isRequired,\n id: PropTypes.number.isRequired, // Unique ID for iframe title\n setThumb: PropTypes.func,\n className: PropTypes.string,\n loop: PropTypes.bool,\n autoplay: PropTypes.bool,\n width: PropTypes.number,\n height: PropTypes.number,\n playing: PropTypes.bool,\n apiKey: PropTypes.string.isRequired, // API key necessary for youtube requests\n}\n\nYoutube.defaultProps = {\n loop: true,\n autoplay: false,\n width: null,\n height: null,\n className: '',\n}\n\nexport default Youtube\n\n```" } ]
code_butik_31b886cb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/ImageResizer/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nclass ImageResizer extends React.Component {\n constructor(props) {\n super(props)\n this.canvas = React.createRef()\n }\n\n componentDidMount() {\n this.drawImage()\n }\n\n drawImage = () => {\n const { src } = this.props\n\n if (!src) return\n\n const image = new Image()\n\n image.onload = () => {\n const { minRatio } = this.props\n\n if (!this.canvas || !this.canvas.current) {\n return\n }\n\n const canvas = this.canvas.current\n\n const width =\n image.width >= image.height * minRatio\n ? image.width\n : image.height * minRatio\n\n const height = image.height\n\n const canvasContext = canvas.getContext('2d')\n canvas.width = width\n canvas.height = height\n\n canvasContext.drawImage(image, (width - image.width) / 2, 0)\n }\n image.src = src\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.src !== this.props.src) {\n this.drawImage()\n }\n }\n\n render() {\n const { alt, className } = this.props\n return <canvas ref={this.canvas} alt={alt} className={className} />\n }\n}\n\nImageResizer.propTypes = {\n src: PropTypes.string,\n alt: PropTypes.string,\n minRatio: PropTypes.number,\n className: PropTypes.string,\n}\n\nexport default ImageResizer\n\n```" } ]
code_butik_fbcf04aa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/ProductDescription/global.css from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.vtex-product-specifications-loader {\n height: 26em;\n}\n\n.border-collapse {\n border-collapse: collapse;\n}\n\n```" } ]
code_butik_62f408e5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/ProductDescription/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport { FormattedMessage, injectIntl, intlShape } from 'react-intl'\nimport HtmlParser from 'react-html-parser'\nimport GradientCollapse from '../GradientCollapse'\n\nimport './global.css'\n\n/**\n * Product Description Component.\n * Render the description and technical specifications of a product\n */\nclass ProductDescription extends Component {\n render() {\n const { specifications, description } = this.props\n\n if (!description && !specifications) {\n return null\n }\n\n const specificationItems = specifications.map(specification => {\n return {\n property: specification.name,\n specifications: specification.values[0],\n }\n })\n\n return (\n <div className=\"vtex-product-description flex-l\">\n <div className=\"w-100 w-60-l\">\n {description && (\n <React.Fragment>\n <div className=\"lh-solid b c-on-base mb5\">\n <FormattedMessage id=\"product-description.title\" />\n </div>\n\n <div className=\"c-muted-1\">\n <GradientCollapse collapseHeight={220}>\n {HtmlParser(description)}\n </GradientCollapse>\n </div>\n </React.Fragment>\n )}\n </div>\n {specifications && specifications.length > 0 && (\n <div className=\"vtex-product-specifications mt6 mt0-l w-100 w-40-l pl8-l\">\n <div className=\"vtex-product-specifications__title lh-solid b c-on-base mb5\">\n <FormattedMessage id=\"technicalspecifications.title\" />\n </div>\n <GradientCollapse collapseHeight={220}>\n <table className=\"vtex-product-specifications__table w-100 bg-base border-collapse\">\n <thead>\n <tr>\n <th className=\"w-50 b--muted-4 bb bt c-muted-2 t-body tl pa5\">\n <FormattedMessage id=\"product-description.property\" />\n </th>\n <th className=\"w-50 b--muted-4 bb bt c-muted-2 t-body tl pa5\">\n <FormattedMessage id=\"product-description.specification\" />\n </th>\n </tr>\n </thead>\n <tbody>\n {specificationItems.map((specification, i) => (\n <tr key={i}>\n <td className=\"w-50 b--muted-4 bb pa5\">\n {specification.property}\n </td>\n <td className=\"w-50 b--muted-4 bb pa5\">\n {specification.specifications}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </GradientCollapse>\n </div>\n )}\n </div>\n )\n }\n}\n\nProductDescription.defaultProps = {\n specifications: [],\n}\n\nProductDescription.propTypes = {\n /** Product description string */\n description: PropTypes.string,\n /** Intl object to provides internationalization */\n intl: intlShape.isRequired,\n /** Specifications that will be displayed on the table */\n specifications: PropTypes.arrayOf(\n PropTypes.shape({\n /** Specification name */\n name: PropTypes.string.isRequired,\n /** Specifications value */\n values: PropTypes.arrayOf(PropTypes.string).isRequired,\n })\n ),\n}\n\nexport default injectIntl(ProductDescription)\n\n```" } ]
code_butik_2da201fd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/ProductDescription/README.md from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Product Description\nProduct Description is a canonical component that any VTEX app can import.\n\nTo import it into your code: \n```js\nimport ProductDescription from components2\n```\n\n## Usage\nYou can use it in your code like a React component with the jsx tag: `<ProductDescription />`. \n```jsx\n<ProductDescription specifications={product.specs}>\n <span>{product.description}</span>\n</ProductDescription>\n```\n\n| Prop name | Type | Description |\n| ------------------------ | ---------- | --------------------------------------------------------------------------- |\n| `children` | `Node!` | Children component which contains the product description |\n| `specifications` | `Array` | Specifications that will be displayed on the table |\n| `specifications[n].name` | `String` | Specification name |\n| `specifications[n].value`| `String` | Specifications value |\n\nSee an example at [Product Details](https://github.com/vtex-apps/product-details) app\n\n```" } ]
code_butik_a5c4886e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/FixedButton/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment } from 'react'\nimport BottomExtraSpace from './BottomExtraSpace'\nimport NoSsr from '@material-ui/core/NoSsr'\n\nexport default props => (\n <Fragment>\n <div className=\"fixed bottom-0 left-0 w-100 z-999\">{props.children}</div>\n <NoSsr>\n <BottomExtraSpace>{props.children}</BottomExtraSpace>\n </NoSsr>\n </Fragment>\n)\n\n```" } ]
code_butik_8df32915
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/FixedButton/BottomExtraSpace.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport ReactDOM from 'react-dom'\n\nclass BottomExtraSpace extends Component {\n constructor(props) {\n super(props)\n\n this.ref = React.createRef()\n this.state = { mounted: false }\n this.el = document.createElement('div')\n }\n\n componentDidMount() {\n this.fixedRoot = this.ref.current\n\n while (this.fixedRoot &&\n window.getComputedStyle(this.fixedRoot)\n .getPropertyValue('overflow') !== 'auto') { this.fixedRoot = this.fixedRoot.parentElement }\n\n if (!this.fixedRoot)this.fixedRoot = document.body\n\n this.fixedRoot && this.fixedRoot.appendChild(this.el)\n this.setState({ mounted: true })\n }\n\n componentWillUnmount() {\n this.fixedRoot && this.fixedRoot.removeChild(this.el)\n }\n\n render() {\n const { mounted } = this.state\n\n if (!mounted) return <div ref={this.ref} />\n\n const children = this.props.children\n\n return ReactDOM.createPortal(\n <div className=\"o-0\" tabIndex=\"-1\">\n {children}\n </div>,\n this.el,\n )\n }\n}\n\nBottomExtraSpace.propTypes = {\n children: PropTypes.node,\n}\n\nexport default BottomExtraSpace\n\n```" } ]
code_butik_af78f0f9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/Carousel/global.css from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n/**\n * Swiper 4.4.1\n * Most modern mobile touch slider and framework with hardware accelerated transitions\n * http://www.idangero.us/swiper/\n *\n * Copyright 2014-2018 Vladimir Kharlampidi\n *\n * Released under the MIT License\n *\n * Released on: September 14, 2018\n */\n.swiper-container {\n margin: 0 auto;\n position: relative;\n overflow: hidden;\n list-style: none;\n padding: 0;\n /* Fix of Webkit flickering */\n z-index: 1;\n}\n.swiper-container-no-flexbox .swiper-slide {\n float: left;\n}\n.swiper-container-vertical > .swiper-wrapper {\n -webkit-box-orient: vertical;\n -webkit-box-direction: normal;\n -webkit-flex-direction: column;\n -ms-flex-direction: column;\n flex-direction: column;\n}\n.swiper-wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n z-index: 1;\n display: -webkit-box;\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n -webkit-transition-property: -webkit-transform;\n transition-property: -webkit-transform;\n -o-transition-property: transform;\n transition-property: transform;\n transition-property: transform, -webkit-transform;\n -webkit-box-sizing: content-box;\n box-sizing: content-box;\n}\n.swiper-container-android .swiper-slide,\n.swiper-wrapper {\n -webkit-transform: translate3d(0px, 0, 0);\n transform: translate3d(0px, 0, 0);\n}\n.swiper-container-multirow > .swiper-wrapper {\n -webkit-flex-wrap: wrap;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n}\n.swiper-container-free-mode > .swiper-wrapper {\n -webkit-transition-timing-function: ease-out;\n -o-transition-timing-function: ease-out;\n transition-timing-function: ease-out;\n margin: 0 auto;\n}\n.swiper-slide {\n -webkit-flex-shrink: 0;\n -ms-flex-negative: 0;\n flex-shrink: 0;\n width: 100%;\n height: 100%;\n position: relative;\n -webkit-transition-property: -webkit-transform;\n transition-property: -webkit-transform;\n -o-transition-property: transform;\n transition-property: transform;\n transition-property: transform, -webkit-transform;\n}\n.swiper-slide-invisible-blank {\n visibility: hidden;\n}\n/* Auto Height */\n.swiper-container-autoheight,\n.swiper-container-autoheight .swiper-slide {\n height: auto;\n}\n.swiper-container-autoheight .swiper-wrapper {\n -webkit-box-align: start;\n -webkit-align-items: flex-start;\n -ms-flex-align: start;\n align-items: flex-start;\n -webkit-transition-property: height, -webkit-transform;\n transition-property: height, -webkit-transform;\n -o-transition-property: transform, height;\n transition-property: transform, height;\n transition-property: transform, height, -webkit-transform;\n}\n/* 3D Effects */\n.swiper-container-3d {\n -webkit-perspective: 1200px;\n perspective: 1200px;\n}\n.swiper-container-3d .swiper-wrapper,\n.swiper-container-3d .swiper-slide,\n.swiper-container-3d .swiper-slide-shadow-left,\n.swiper-container-3d .swiper-slide-shadow-right,\n.swiper-container-3d .swiper-slide-shadow-top,\n.swiper-container-3d .swiper-slide-shadow-bottom,\n.swiper-container-3d .swiper-cube-shadow {\n -webkit-transform-style: preserve-3d;\n transform-style: preserve-3d;\n}\n.swiper-container-3d .swiper-slide-shadow-left,\n.swiper-container-3d .swiper-slide-shadow-right,\n.swiper-container-3d .swiper-slide-shadow-top,\n.swiper-container-3d .swiper-slide-shadow-bottom {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n z-index: 10;\n}\n.swiper-container-3d .swiper-slide-shadow-left {\n background-image: -webkit-gradient(linear, right top, left top, from(rgba(0, 0, 0, 0.5)), to(rgba(0, 0, 0, 0)));\n background-image: -webkit-linear-gradient(right, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n background-image: -o-linear-gradient(right, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n background-image: linear-gradient(to left, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n}\n.swiper-container-3d .swiper-slide-shadow-right {\n background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, 0.5)), to(rgba(0, 0, 0, 0)));\n background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n}\n.swiper-container-3d .swiper-slide-shadow-top {\n background-image: -webkit-gradient(linear, left bottom, left top, from(rgba(0, 0, 0, 0.5)), to(rgba(0, 0, 0, 0)));\n background-image: -webkit-linear-gradient(bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n background-image: -o-linear-gradient(bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n background-image: linear-gradient(to top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n}\n.swiper-container-3d .swiper-slide-shadow-bottom {\n background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.5)), to(rgba(0, 0, 0, 0)));\n background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n background-image: -o-linear-gradient(top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));\n}\n/* IE10 Windows Phone 8 Fixes */\n.swiper-container-wp8-horizontal,\n.swiper-container-wp8-horizontal > .swiper-wrapper {\n -ms-touch-action: pan-y;\n touch-action: pan-y;\n}\n.swiper-container-wp8-vertical,\n.swiper-container-wp8-vertical > .swiper-wrapper {\n -ms-touch-action: pan-x;\n touch-action: pan-x;\n}\n.swiper-button-prev,\n.swiper-button-next {\n position: absolute;\n top: 50%;\n width: 27px;\n height: 44px;\n margin-top: -22px;\n z-index: 10;\n cursor: pointer;\n background-size: 27px 44px;\n background-position: center;\n background-repeat: no-repeat;\n}\n.swiper-button-prev.swiper-button-disabled,\n.swiper-button-next.swiper-button-disabled {\n opacity: 0.35;\n cursor: auto;\n pointer-events: none;\n}\n.swiper-button-prev,\n.swiper-container-rtl .swiper-button-next {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M0%2C22L22%2C0l2.1%2C2.1L4.2%2C22l19.9%2C19.9L22%2C44L0%2C22L0%2C22L0%2C22z'%20fill%3D'%23007aff'%2F%3E%3C%2Fsvg%3E\");\n left: 10px;\n right: auto;\n}\n.swiper-button-next,\n.swiper-container-rtl .swiper-button-prev {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M27%2C22L27%2C22L5%2C44l-2.1-2.1L22.8%2C22L2.9%2C2.1L5%2C0L27%2C22L27%2C22z'%20fill%3D'%23007aff'%2F%3E%3C%2Fsvg%3E\");\n right: 10px;\n left: auto;\n}\n.swiper-button-prev.swiper-button-white,\n.swiper-container-rtl .swiper-button-next.swiper-button-white {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M0%2C22L22%2C0l2.1%2C2.1L4.2%2C22l19.9%2C19.9L22%2C44L0%2C22L0%2C22L0%2C22z'%20fill%3D'%23ffffff'%2F%3E%3C%2Fsvg%3E\");\n}\n.swiper-button-next.swiper-button-white,\n.swiper-container-rtl .swiper-button-prev.swiper-button-white {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M27%2C22L27%2C22L5%2C44l-2.1-2.1L22.8%2C22L2.9%2C2.1L5%2C0L27%2C22L27%2C22z'%20fill%3D'%23ffffff'%2F%3E%3C%2Fsvg%3E\");\n}\n.swiper-button-prev.swiper-button-black,\n.swiper-container-rtl .swiper-button-next.swiper-button-black {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M0%2C22L22%2C0l2.1%2C2.1L4.2%2C22l19.9%2C19.9L22%2C44L0%2C22L0%2C22L0%2C22z'%20fill%3D'%23000000'%2F%3E%3C%2Fsvg%3E\");\n}\n.swiper-button-next.swiper-button-black,\n.swiper-container-rtl .swiper-button-prev.swiper-button-black {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M27%2C22L27%2C22L5%2C44l-2.1-2.1L22.8%2C22L2.9%2C2.1L5%2C0L27%2C22L27%2C22z'%20fill%3D'%23000000'%2F%3E%3C%2Fsvg%3E\");\n}\n.swiper-button-lock {\n display: none;\n}\n.swiper-pagination {\n position: absolute;\n text-align: center;\n -webkit-transition: 300ms opacity;\n -o-transition: 300ms opacity;\n transition: 300ms opacity;\n -webkit-transform: translate3d(0, 0, 0);\n transform: translate3d(0, 0, 0);\n z-index: 10;\n}\n.swiper-pagination.swiper-pagination-hidden {\n opacity: 0;\n}\n/* Common Styles */\n.swiper-pagination-fraction,\n.swiper-pagination-custom,\n.swiper-container-horizontal > .swiper-pagination-bullets {\n bottom: 10px;\n left: 0;\n width: 100%;\n}\n/* Bullets */\n.swiper-pagination-bullets-dynamic {\n overflow: hidden;\n font-size: 0;\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet {\n -webkit-transform: scale(0.33);\n -ms-transform: scale(0.33);\n transform: scale(0.33);\n position: relative;\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active {\n -webkit-transform: scale(1);\n -ms-transform: scale(1);\n transform: scale(1);\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-main {\n -webkit-transform: scale(1);\n -ms-transform: scale(1);\n transform: scale(1);\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-prev {\n -webkit-transform: scale(0.66);\n -ms-transform: scale(0.66);\n transform: scale(0.66);\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-prev-prev {\n -webkit-transform: scale(0.33);\n -ms-transform: scale(0.33);\n transform: scale(0.33);\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-next {\n -webkit-transform: scale(0.66);\n -ms-transform: scale(0.66);\n transform: scale(0.66);\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-next-next {\n -webkit-transform: scale(0.33);\n -ms-transform: scale(0.33);\n transform: scale(0.33);\n}\n.swiper-pagination-bullet {\n width: 8px;\n height: 8px;\n display: inline-block;\n border-radius: 100%;\n background: #000;\n opacity: 0.2;\n}\nbutton.swiper-pagination-bullet {\n border: none;\n margin: 0;\n padding: 0;\n -webkit-box-shadow: none;\n box-shadow: none;\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n}\n.swiper-pagination-clickable .swiper-pagination-bullet {\n cursor: pointer;\n}\n.swiper-pagination-bullet-active {\n opacity: 1;\n background: currentColor;\n}\n.swiper-container-vertical > .swiper-pagination-bullets {\n right: 10px;\n top: 50%;\n -webkit-transform: translate3d(0px, -50%, 0);\n transform: translate3d(0px, -50%, 0);\n}\n.swiper-container-vertical > .swiper-pagination-bullets .swiper-pagination-bullet {\n margin: 6px 0;\n display: block;\n}\n.swiper-container-vertical > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic {\n top: 50%;\n -webkit-transform: translateY(-50%);\n -ms-transform: translateY(-50%);\n transform: translateY(-50%);\n width: 8px;\n}\n.swiper-container-vertical > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic .swiper-pagination-bullet {\n display: inline-block;\n -webkit-transition: 200ms top, 200ms -webkit-transform;\n transition: 200ms top, 200ms -webkit-transform;\n -o-transition: 200ms transform, 200ms top;\n transition: 200ms transform, 200ms top;\n transition: 200ms transform, 200ms top, 200ms -webkit-transform;\n}\n.swiper-container-horizontal > .swiper-pagination-bullets .swiper-pagination-bullet {\n margin: 0 4px;\n}\n.swiper-container-horizontal > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic {\n left: 50%;\n -webkit-transform: translateX(-50%);\n -ms-transform: translateX(-50%);\n transform: translateX(-50%);\n white-space: nowrap;\n}\n.swiper-container-horizontal > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic .swiper-pagination-bullet {\n -webkit-transition: 200ms left, 200ms -webkit-transform;\n transition: 200ms left, 200ms -webkit-transform;\n -o-transition: 200ms transform, 200ms left;\n transition: 200ms transform, 200ms left;\n transition: 200ms transform, 200ms left, 200ms -webkit-transform;\n}\n.swiper-container-horizontal.swiper-container-rtl > .swiper-pagination-bullets-dynamic .swiper-pagination-bullet {\n -webkit-transition: 200ms right, 200ms -webkit-transform;\n transition: 200ms right, 200ms -webkit-transform;\n -o-transition: 200ms transform, 200ms right;\n transition: 200ms transform, 200ms right;\n transition: 200ms transform, 200ms right, 200ms -webkit-transform;\n}\n/* Progress */\n.swiper-pagination-progressbar {\n background: rgba(0, 0, 0, 0.25);\n position: absolute;\n}\n.swiper-pagination-progressbar .swiper-pagination-progressbar-fill {\n background: currentColor;\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n -webkit-transform: scale(0);\n -ms-transform: scale(0);\n transform: scale(0);\n -webkit-transform-origin: left top;\n -ms-transform-origin: left top;\n transform-origin: left top;\n}\n.swiper-container-rtl .swiper-pagination-progressbar .swiper-pagination-progressbar-fill {\n -webkit-transform-origin: right top;\n -ms-transform-origin: right top;\n transform-origin: right top;\n}\n.swiper-container-horizontal > .swiper-pagination-progressbar,\n.swiper-container-vertical > .swiper-pagination-progressbar.swiper-pagination-progressbar-opposite {\n width: 100%;\n height: 4px;\n left: 0;\n top: 0;\n}\n.swiper-container-vertical > .swiper-pagination-progressbar,\n.swiper-container-horizontal > .swiper-pagination-progressbar.swiper-pagination-progressbar-opposite {\n width: 4px;\n height: 100%;\n left: 0;\n top: 0;\n}\n.swiper-pagination-white .swiper-pagination-bullet-active {\n background: #ffffff;\n}\n.swiper-pagination-progressbar.swiper-pagination-white {\n background: rgba(255, 255, 255, 0.25);\n}\n.swiper-pagination-progressbar.swiper-pagination-white .swiper-pagination-progressbar-fill {\n background: #ffffff;\n}\n.swiper-pagination-black .swiper-pagination-bullet-active {\n background: #000000;\n}\n.swiper-pagination-progressbar.swiper-pagination-black {\n background: rgba(0, 0, 0, 0.25);\n}\n.swiper-pagination-progressbar.swiper-pagination-black .swiper-pagination-progressbar-fill {\n background: #000000;\n}\n.swiper-pagination-lock {\n display: none;\n}\n/* Scrollbar */\n.swiper-scrollbar {\n border-radius: 10px;\n position: relative;\n -ms-touch-action: none;\n background: rgba(0, 0, 0, 0.1);\n}\n.swiper-container-horizontal > .swiper-scrollbar {\n position: absolute;\n left: 1%;\n bottom: 3px;\n z-index: 50;\n height: 5px;\n width: 98%;\n}\n.swiper-container-vertical > .swiper-scrollbar {\n position: absolute;\n right: 3px;\n top: 1%;\n z-index: 50;\n width: 5px;\n height: 98%;\n}\n.swiper-scrollbar-drag {\n height: 100%;\n width: 100%;\n position: relative;\n background: rgba(0, 0, 0, 0.5);\n border-radius: 10px;\n left: 0;\n top: 0;\n}\n.swiper-scrollbar-cursor-drag {\n cursor: move;\n}\n.swiper-scrollbar-lock {\n display: none;\n}\n.swiper-zoom-container {\n width: 100%;\n height: 100%;\n display: -webkit-box;\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-pack: center;\n -webkit-justify-content: center;\n -ms-flex-pack: center;\n justify-content: center;\n -webkit-box-align: center;\n -webkit-align-items: center;\n -ms-flex-align: center;\n align-items: center;\n text-align: center;\n}\n.swiper-zoom-container > img,\n.swiper-zoom-container > svg,\n.swiper-zoom-container > canvas {\n max-width: 100%;\n max-height: 100%;\n -o-object-fit: contain;\n object-fit: contain;\n}\n.swiper-slide-zoomed {\n cursor: move;\n}\n/* Preloader */\n.swiper-lazy-preloader {\n width: 42px;\n height: 42px;\n position: absolute;\n left: 50%;\n top: 50%;\n margin-left: -21px;\n margin-top: -21px;\n z-index: 10;\n -webkit-transform-origin: 50%;\n -ms-transform-origin: 50%;\n transform-origin: 50%;\n -webkit-animation: swiper-preloader-spin 1s steps(12, end) infinite;\n animation: swiper-preloader-spin 1s steps(12, end) infinite;\n}\n.swiper-lazy-preloader:after {\n display: block;\n content: '';\n width: 100%;\n height: 100%;\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D'0%200%20120%20120'%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20xmlns%3Axlink%3D'http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink'%3E%3Cdefs%3E%3Cline%20id%3D'l'%20x1%3D'60'%20x2%3D'60'%20y1%3D'7'%20y2%3D'27'%20stroke%3D'%236c6c6c'%20stroke-width%3D'11'%20stroke-linecap%3D'round'%2F%3E%3C%2Fdefs%3E%3Cg%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(30%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(60%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(90%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(120%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(150%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.37'%20transform%3D'rotate(180%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.46'%20transform%3D'rotate(210%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.56'%20transform%3D'rotate(240%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.66'%20transform%3D'rotate(270%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.75'%20transform%3D'rotate(300%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.85'%20transform%3D'rotate(330%2060%2C60)'%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E\");\n background-position: 50%;\n background-size: 100%;\n background-repeat: no-repeat;\n}\n.swiper-lazy-preloader-white:after {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D'0%200%20120%20120'%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20xmlns%3Axlink%3D'http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink'%3E%3Cdefs%3E%3Cline%20id%3D'l'%20x1%3D'60'%20x2%3D'60'%20y1%3D'7'%20y2%3D'27'%20stroke%3D'%23fff'%20stroke-width%3D'11'%20stroke-linecap%3D'round'%2F%3E%3C%2Fdefs%3E%3Cg%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(30%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(60%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(90%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(120%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(150%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.37'%20transform%3D'rotate(180%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.46'%20transform%3D'rotate(210%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.56'%20transform%3D'rotate(240%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.66'%20transform%3D'rotate(270%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.75'%20transform%3D'rotate(300%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.85'%20transform%3D'rotate(330%2060%2C60)'%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E\");\n}\n@-webkit-keyframes swiper-preloader-spin {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@keyframes swiper-preloader-spin {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n/* a11y */\n.swiper-container .swiper-notification {\n position: absolute;\n left: 0;\n top: 0;\n pointer-events: none;\n opacity: 0;\n z-index: -1000;\n}\n.swiper-container-fade.swiper-container-free-mode .swiper-slide {\n -webkit-transition-timing-function: ease-out;\n -o-transition-timing-function: ease-out;\n transition-timing-function: ease-out;\n}\n.swiper-container-fade .swiper-slide {\n pointer-events: none;\n -webkit-transition-property: opacity;\n -o-transition-property: opacity;\n transition-property: opacity;\n}\n.swiper-container-fade .swiper-slide .swiper-slide {\n pointer-events: none;\n}\n.swiper-container-fade .swiper-slide-active,\n.swiper-container-fade .swiper-slide-active .swiper-slide-active {\n pointer-events: auto;\n}\n.swiper-container-cube {\n overflow: visible;\n}\n.swiper-container-cube .swiper-slide {\n pointer-events: none;\n -webkit-backface-visibility: hidden;\n backface-visibility: hidden;\n z-index: 1;\n visibility: hidden;\n -webkit-transform-origin: 0 0;\n -ms-transform-origin: 0 0;\n transform-origin: 0 0;\n width: 100%;\n height: 100%;\n}\n.swiper-container-cube .swiper-slide .swiper-slide {\n pointer-events: none;\n}\n.swiper-container-cube.swiper-container-rtl .swiper-slide {\n -webkit-transform-origin: 100% 0;\n -ms-transform-origin: 100% 0;\n transform-origin: 100% 0;\n}\n.swiper-container-cube .swiper-slide-active,\n.swiper-container-cube .swiper-slide-active .swiper-slide-active {\n pointer-events: auto;\n}\n.swiper-container-cube .swiper-slide-active,\n.swiper-container-cube .swiper-slide-next,\n.swiper-container-cube .swiper-slide-prev,\n.swiper-container-cube .swiper-slide-next + .swiper-slide {\n pointer-events: auto;\n visibility: visible;\n}\n.swiper-container-cube .swiper-slide-shadow-top,\n.swiper-container-cube .swiper-slide-shadow-bottom,\n.swiper-container-cube .swiper-slide-shadow-left,\n.swiper-container-cube .swiper-slide-shadow-right {\n z-index: 0;\n -webkit-backface-visibility: hidden;\n backface-visibility: hidden;\n}\n.swiper-container-cube .swiper-cube-shadow {\n position: absolute;\n left: 0;\n bottom: 0px;\n width: 100%;\n height: 100%;\n background: #000;\n opacity: 0.6;\n -webkit-filter: blur(50px);\n filter: blur(50px);\n z-index: 0;\n}\n.swiper-container-flip {\n overflow: visible;\n}\n.swiper-container-flip .swiper-slide {\n pointer-events: none;\n -webkit-backface-visibility: hidden;\n backface-visibility: hidden;\n z-index: 1;\n}\n.swiper-container-flip .swiper-slide .swiper-slide {\n pointer-events: none;\n}\n.swiper-container-flip .swiper-slide-active,\n.swiper-container-flip .swiper-slide-active .swiper-slide-active {\n pointer-events: auto;\n}\n.swiper-container-flip .swiper-slide-shadow-top,\n.swiper-container-flip .swiper-slide-shadow-bottom,\n.swiper-container-flip .swiper-slide-shadow-left,\n.swiper-container-flip .swiper-slide-shadow-right {\n z-index: 0;\n -webkit-backface-visibility: hidden;\n backface-visibility: hidden;\n}\n.swiper-container-coverflow .swiper-wrapper {\n /* Windows 8 IE 10 fix */\n -ms-perspective: 1200px;\n}\n\n/*------------------ vtex -----------------------*/\n.gallery-cursor {\n cursor: url('cursor.svg') 8 8, default;\n}\n\n.gallery-thumbs .swiper-slide {\n height: auto;\n}\n\n.gallery-thumbs .swiper-slide:not(.swiper-slide-thumb-active) .thumb-border {\n border-width: 0px;\n}\n\n@media screen and (min-width: 40em) {\n .ml-20-ns {\n margin-left: 20%;\n }\n}\n\n.center-all{\n margin: auto\n}\n\n.border-box{\n box-sizing: border-box;\n}\n\n.top-50{\n top: 50%;\n}\n\n.translate--50y{\n transform: translate(0, -50%);\n}\n\n.vtex__icon-caret-right,\n.vtex__icon-caret-left {\n stroke: white;\n stroke-width: 0.5px;\n -webkit-filter: drop-shadow( 0px 1px 1px #CACBCC );\n filter: drop-shadow( 0px 1px 1px #CACBCC );\n}\n\n.cursor-default:hover{\n cursor: default;\n}\n\n```" } ]
code_butik_8a94b7ca
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/Carousel/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport debounce from 'debounce'\nimport Loader from './Loader.js'\nimport { path } from 'ramda'\nimport BlurredLoader from '../BlurredLoader'\nimport Video from '../Video'\nimport CaretLeft from '@vtex/styleguide/lib/icon/CaretLeft'\nimport CaretRight from '@vtex/styleguide/lib/icon/CaretRight'\nimport placeholder from './noimage.svg'\n\nimport './global.css'\n\nconst Swiper = window.navigator ? require('react-id-swiper').default : null\n\nconst initialState = {\n Swiper: null,\n loaded: [],\n thumbSwiper: null,\n gallerySwiper: null,\n thumbUrl: [],\n alt: [],\n thumbsLoaded: false,\n activeIndex: 0,\n failedImageIndexes: [],\n}\n\nconst placeholderSlide = {\n alt: 'Failed image',\n bestUrlIndex: 0,\n thumbUrl: placeholder,\n type: 'image',\n urls: [placeholder],\n}\n\nclass Carousel extends Component {\n constructor(props) {\n super(props)\n\n this.CaretPrev = props.CaretPrev || CaretLeft\n this.CaretNext = props.CaretNext || CaretRight\n this.state = initialState\n this.setInitialVariablesState()\n }\n\n setInitialVariablesState() {\n const slides = this.props.slides\n\n this.isVideo = []\n this.rebuildGalleryOnUpdate = false\n this.thumbLoadCount = 0\n\n if (slides) {\n const thumbPromises = slides.map((slide, i) => {\n if (slide.type === 'video') {\n try {\n this.isVideo[i] = true\n const thumbUrl = Video.getThumbUrl(\n slide.src,\n slide.thumbWidth,\n slide.apiKey\n )\n return thumbUrl\n .then(url => ({ thumbUrl: url, index: i }))\n .catch(() => Promise.reject(i))\n } catch (error) {\n return Promise.reject(i)\n }\n }\n return Promise.resolve({\n thumbUrl: slide.thumbUrl,\n index: i,\n })\n })\n thumbPromises.forEach(promise => {\n promise.then(this.getThumb).catch(index => {\n this.incrementThumbsLoaded()\n this.setState({\n failedImageIndexes: this.state.failedImageIndexes.concat(index),\n })\n })\n })\n }\n }\n\n debouncedRebuildOnUpdate = debounce(() => {\n this.state.thumbSwiper && this.state.thumbSwiper.update()\n }, 500)\n\n getThumb = ({ thumbUrl, index }) => {\n if (!window.navigator) return // Image object doesn't exist when it's being rendered in the server side\n\n const image = new Image()\n image.onload = () => {\n this.incrementThumbsLoaded()\n }\n image.onerror = () => {\n this.incrementThumbsLoaded()\n this.setState({\n failedImageIndexes: this.state.failedImageIndexes.concat(index),\n })\n }\n image.src = thumbUrl\n }\n\n incrementThumbsLoaded() {\n this.thumbLoadCount++\n if (this.thumbLoadCount === this.props.slides.length) {\n this.setState({ thumbsLoaded: true })\n }\n }\n\n componentDidMount() {\n window.addEventListener('resize', this.debouncedRebuildOnUpdate)\n }\n\n componentWillUnmount() {\n window.removeEventListener('resize', this.debouncedRebuildOnUpdate)\n }\n\n linkThumb = () => {\n const _this = this\n return function() {\n this.visibleSlidesIndexes || (this.visibleSlidesIndexes = []) // Swiper bug fix\n _this.rebuildGalleryOnUpdate = true\n _this.setState({ thumbSwiper: this })\n }\n }\n\n linkGallery = () => {\n const _this = this\n return function() {\n _this.setState({ gallerySwiper: this })\n }\n }\n\n onSlideChange = () => {\n const _this = this\n return function() {\n const { activeIndex } = this\n _this.setState({ activeIndex })\n }\n }\n\n setVideoThumb = i => (url, title) => {\n const thumbUrl = { ...this.state.thumbUrl }\n const alt = { ...this.state.alt }\n\n thumbUrl[i] = url\n alt[i] = title\n\n this.setState({ thumbUrl, alt })\n }\n\n onImageLoad = i => () => {\n const loaded = { ...this.state.loaded }\n loaded[i] = true\n this.setState({ loaded })\n }\n\n renderSlide = (slide, i) => {\n const { loaded } = this.state\n\n if (this.state.failedImageIndexes.includes(i)) {\n slide = placeholderSlide\n }\n\n switch (slide.type) {\n case 'image':\n return (\n <div\n className={`w-100 ${\n loaded[i] ? 'swiper-zoom-container' : 'overflow-hidden'\n }`}>\n <BlurredLoader\n loaderType=\"SPINNER\"\n loaderUrl={slide.thumbUrl}\n realUrls={slide.urls}\n bestUrlIndex={slide.bestUrlIndex}\n alt={slide.alt}\n onload={this.onImageLoad(i)}\n />\n </div>\n )\n case 'video':\n try {\n return (\n <Video\n url={slide.src}\n setThumb={this.setVideoThumb(i)}\n playing={i === this.state.activeIndex}\n id={i}\n apiKey={slide.apiKey}\n />\n )\n } catch (err) {\n console.error(`Error while loading ${slide.src}`)\n return null\n }\n default:\n return null\n }\n }\n\n componentDidUpdate(prevProps) {\n const { gallerySwiper, loaded, activeIndex } = this.state\n const { isVideo } = this\n\n if (prevProps.slides !== this.props.slides) {\n this.setState(initialState, () => this.setInitialVariablesState())\n return\n }\n\n const paginationElement = path(['pagination', 'el'], gallerySwiper)\n if (paginationElement) paginationElement.hidden = isVideo[activeIndex]\n\n const gallerySwiperZoom = path(['zoom'], gallerySwiper)\n\n if (gallerySwiperZoom) {\n loaded[activeIndex]\n ? gallerySwiperZoom.enable()\n : gallerySwiperZoom.disable()\n }\n }\n\n render() {\n const { thumbSwiper, thumbsLoaded } = this.state\n const { rebuildGalleryOnUpdate } = this\n const slides = this.props.slides\n ? this.props.slides.map(slide => ({ ...slide }))\n : []\n\n if (!thumbsLoaded || Swiper == null) {\n return <Loader slidesAmount={slides ? slides.length : 0} />\n }\n\n const caretClassName =\n 'pv7 absolute top-50 translate--50y z-2 pointer c-action-primary'\n const galleryParams = {\n containerClass: 'swiper-container',\n pagination:\n slides.length > 1\n ? {\n el: '.swiper-pagination',\n clickable: true,\n bulletActiveClass:\n 'c-action-primary swiper-pagination-bullet-active',\n }\n : {},\n navigation:\n slides.length > 1\n ? {\n prevEl: '.swiper-caret-prev',\n nextEl: '.swiper-caret-next',\n disabledClass: 'c-disabled cursor-default',\n }\n : {},\n thumbs: {\n swiper: thumbSwiper,\n },\n zoom: {\n maxRatio: 2,\n },\n rebuildOnUpdate: rebuildGalleryOnUpdate,\n resistanceRatio: slides.length > 1 ? 0.85 : 0,\n renderNextButton: () => (\n <span className={`swiper-caret-next pl7 right-1 ${caretClassName}`}>\n <this.CaretNext />\n </span>\n ),\n renderPrevButton: () => (\n <span className={`swiper-caret-prev pr7 left-1 ${caretClassName}`}>\n <this.CaretPrev />\n </span>\n ),\n on: {\n init: this.linkGallery(),\n slideChange: this.onSlideChange(),\n },\n }\n this.rebuildGalleryOnUpdate = false\n\n const thumbnailParams = {\n observer: true,\n containerClass: 'swiper-container h-100',\n watchSlidesVisibility: true,\n watchSlidesProgress: true,\n freeMode: true,\n direction: 'vertical',\n slidesPerView: 'auto',\n touchRatio: 0.4,\n mousewheel: true,\n preloadImages: true,\n on: {\n init: this.linkThumb(),\n },\n shouldSwiperUpdate: true,\n }\n\n return (\n <div className={'w-100 relative overflow-hidden'}>\n <div\n className={`w-20 gallery-thumbs bottom-0 top-0 left-0 absolute pr5 dn\n ${slides.length > 1 ? 'db-ns' : ''}`}>\n <Swiper {...thumbnailParams}>\n {slides.map((slide, i) => {\n if (this.state.failedImageIndexes.includes(i)) {\n slide.thumbUrl = placeholderSlide.thumbUrl\n }\n return (\n <div key={i} className=\"swiper-slide w-100 h-auto mb5\">\n <img\n className=\"w-100 h-auto db\"\n alt={slide.alt ? this.state.alt[i] : ''}\n src={slide.thumbUrl || this.state.thumbUrl[i]}\n />\n <div className=\"absolute absolute--fill b--solid b--muted-2 bw1 thumb-border\" />\n </div>\n )\n })}\n </Swiper>\n </div>\n <div\n className={`w-100 ${\n slides.length > 1 ? 'w-80-ns ml-20-ns' : ''\n } border-box gallery-cursor`}>\n <Swiper {...galleryParams}>\n {slides.map((slide, i) => (\n <div key={i} className=\"swiper-slide center-all\">\n {this.renderSlide(slide, i)}\n </div>\n ))}\n </Swiper>\n </div>\n </div>\n )\n }\n}\n\nCarousel.propTypes = {\n CaretPrev: PropTypes.node,\n CaretNext: PropTypes.node,\n slides: PropTypes.arrayOf(\n PropTypes.oneOfType([\n PropTypes.shape({\n type: PropTypes.string,\n /** Props for type == 'image' */\n urls: PropTypes.arrayOf(PropTypes.string),\n alt: PropTypes.string,\n thumbUrl: PropTypes.string,\n bestUrlIndex: PropTypes.number,\n }),\n PropTypes.shape({\n type: PropTypes.string,\n /** Props for type 'video' */\n src: PropTypes.string,\n thumbWidth: PropTypes.number,\n }),\n ])\n ),\n}\n\nexport default Carousel\n\n```" } ]
code_butik_91bab9aa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/Carousel/Loader.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport ContentLoader from 'react-content-loader'\nimport React from 'react'\n\nexport default props => {\n if (props.slidesAmount === 1) {\n return (\n <div className=\"w-100 aspect-ratio aspect-ratio--1x1\">\n <ContentLoader\n style={{\n position: 'absolute',\n width: '100%',\n height: '100%',\n }}\n height=\"100%\"\n width=\"100%\">\n <rect width=\"100%\" height=\"100%\" />\n </ContentLoader>\n </div>\n )\n }\n\n return (\n <div className=\"w-100 aspect-ratio aspect-ratio--1x1\">\n <ContentLoader\n style={{\n position: 'absolute',\n width: '100%',\n height: '100%',\n }}\n height=\"100%\"\n width=\"100%\">\n <rect className=\"dn db-ns\" width=\"18%\" height=\"18%\" />\n <rect className=\"dn db-ns\" width=\"18%\" height=\"18%\" y=\"20%\" />\n <rect className=\"dn db-ns\" width=\"18%\" height=\"18%\" y=\"40%\" />\n <rect className=\"dn db-ns\" width=\"18%\" height=\"18%\" y=\"60%\" />\n <rect className=\"dn db-ns\" width=\"89%\" height=\"89%\" x=\"20%\" />\n <rect className=\"db dn-ns\" width=\"100%\" height=\"100%\" />\n </ContentLoader>\n </div>\n )\n}\n\n```" } ]
code_butik_6c1ee606
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/GradientCollapse/global.css from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.fade-bottom {\n background-image: linear-gradient(transparent, white);\n}\n\n.pointer-events-none {\n pointer-events: none;\n}\n\n.pointer-events-auto {\n pointer-events: auto;\n}\n\n```" } ]
code_butik_ca565c2f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/GradientCollapse/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport { Transition } from 'react-transition-group'\nimport debounce from 'debounce'\nimport { FormattedMessage } from 'react-intl'\nimport './global.css'\n\nconst transitionStyle = transitionTime => ({\n transition: `${transitionTime}ms ease-in-out`,\n})\n\nclass GradientCollapse extends Component {\n constructor(props) {\n super(props)\n this.state = { isCollapseVisible: true, collapsed: true, maxHeight: 'auto' }\n\n this.wrapper = React.createRef()\n }\n\n calcMaxHeight = () => {\n const { collapseHeight } = this.props\n const wrapper = this.wrapper.current\n\n if (wrapper.scrollHeight > collapseHeight) {\n const maxHeight = wrapper.scrollHeight + 60\n this.setState({ isCollapseVisible: true, maxHeight })\n } else this.setState({ isCollapseVisible: false, maxHeight: 'auto' })\n }\n\n debouncedCalcMaxHeight = debounce(this.calcMaxHeight, 500)\n\n componentDidMount() {\n window.addEventListener('resize', this.debouncedCalcMaxHeight)\n this.calcMaxHeight()\n }\n\n componentWillUnmount() {\n window.removeEventListener('resize', this.debouncedCalcMaxHeight)\n }\n\n render() {\n const { children, collapseHeight } = this.props\n const { collapsed, isCollapseVisible, maxHeight } = this.state\n const height = isCollapseVisible && collapsed ? collapseHeight : maxHeight\n const transitionTime = 600\n const fadeOutTime = 400\n\n return (\n <Transition timeout={transitionTime} in={!collapsed}>\n {state => (\n <div\n style={{\n ...transitionStyle(transitionTime),\n height,\n overflow: 'hidden',\n }}\n className=\"relative\">\n <div ref={this.wrapper} className=\"h-auto\">\n {children}\n </div>\n <div\n className={`${\n isCollapseVisible ? 'flex' : 'dn'\n } absolute bottom-0 pointer-events-none w-100 h-100 flex-column justify-end`}>\n <div\n style={transitionStyle(fadeOutTime)}\n className={`${\n state === 'entered' ? 'o-0' : ''\n } fade-bottom w-100 h-50`}\n />\n <div\n className={`${\n state === 'entered' ? 'bg-transparent' : 'bg-base'\n } tc w-100 pointer-events-auto`}>\n <div\n className=\"c-action-primary t-action pointer ma5\"\n onClick={() => this.setState({ collapsed: !collapsed })}>\n {state === 'entered' || (collapsed && state !== 'exited') ? (\n <FormattedMessage id=\"collapse.showLess\" />\n ) : (\n <FormattedMessage id=\"collapse.showMore\" />\n )}\n </div>\n </div>\n </div>\n </div>\n )}\n </Transition>\n )\n }\n}\n\nGradientCollapse.propTypes = {\n /** Maximum height collapsed */\n collapseHeight: PropTypes.number.isRequired,\n children: PropTypes.node,\n}\n\nexport default GradientCollapse\n\n```" } ]
code_butik_51da19f4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/BlurredLoader/global.css from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.blur-30 {\n filter: blur(30px);\n}\n\n.transition-opacity-1 {\n transition: 1s;\n}\n\n```" } ]
code_butik_eaf5ad64
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/BlurredLoader/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport Spinner from '@vtex/styleguide/lib/Spinner'\nimport LinearProgress from '@material-ui/core/LinearProgress'\nimport { withStyles } from '@material-ui/core/styles'\nimport './global.css'\nimport ImageResizer from '../ImageResizer'\n\nconst styles = { barColorPrimary: { backgroundColor: 'currentColor' } }\nconst LinearProgressWithStyle = withStyles(styles)(LinearProgress)\n\nconst LOAD_STATES = {\n LOADING: 'LOADING',\n TRANSITION: 'TRANSITION',\n LOADED: 'LOADED',\n}\n\nconst imageMinRatio = 2 / 3\n\nexport const LOADER_TYPES = {\n SPINNER: 'SPINNER',\n LINEAR: 'LINEAR',\n}\n\nclass BlurredLoader extends React.Component {\n constructor(props) {\n super(props)\n\n this.state = {\n loadState: LOAD_STATES.LOADING,\n realUrlIndex: null,\n }\n this.timers = {}\n this.loadCounter = 0\n }\n\n generateImage = urlIndex => {\n const { realUrls } = this.props\n const { realUrlIndex } = this.state\n const bestUrlIndex = urlIndex || this.props.bestUrlIndex\n\n if (realUrlIndex && bestUrlIndex <= realUrlIndex) {\n return\n }\n\n const hdImageLoader = new Image()\n hdImageLoader.src = realUrls[bestUrlIndex]\n\n hdImageLoader.onerror = () => {\n let { realUrlIndex } = this.state\n if (!realUrlIndex) realUrlIndex = 0\n\n if (this.loadCounter > 10) return\n this.loadCounter++\n this.generateImage(Math.max(bestUrlIndex - 1, realUrlIndex))\n }\n\n hdImageLoader.onload = () => {\n const { realUrlIndex } = this.state\n if (realUrlIndex && bestUrlIndex <= realUrlIndex) return\n\n this.setState({\n loadState: LOAD_STATES.TRANSITION,\n realUrlIndex: bestUrlIndex,\n })\n\n const timer = setTimeout(() => {\n this.setState({ loadState: LOAD_STATES.LOADED })\n this.props.onload && this.props.onload()\n delete this.timers[timer]\n }, 1000)\n this.timers[timer] = true\n\n if (this.props.bestUrlIndex > bestUrlIndex) {\n this.generateImage()\n }\n }\n }\n\n Loader = () => {\n const { loaderType } = this.props\n const { loadState } = this.state\n switch (loaderType) {\n case LOADER_TYPES.LINEAR:\n return (\n <div\n className={`w-100 top-0 z-2 absolute transition-opacity-1 ${\n loadState === LOAD_STATES.LOADING ? 'o-100' : 'o-0'\n }`}>\n <LinearProgressWithStyle className=\"c-action-primary\" />\n </div>\n )\n case LOADER_TYPES.SPINNER:\n return (\n <div\n className={`absolute z-2 center-all left-0 right-0 top-0 bottom-0 transition-opacity-1 ${\n loadState === LOAD_STATES.LOADING ? 'o-100' : 'o-0'\n }`}\n style={{ height: 40, width: 40 }}>\n <Spinner />\n </div>\n )\n default:\n return null\n }\n }\n\n componentDidMount() {\n this.generateImage()\n }\n\n componentWillUnmount() {\n const keys = Object.keys(this.timers)\n keys.forEach(key => this.timers[key] && clearTimeout(key))\n }\n\n render() {\n const { Loader } = this\n const { className, alt, loaderUrl, realUrls } = this.props\n const { loadState, realUrlIndex } = this.state\n const loaded = loadState === LOAD_STATES.LOADED\n\n return (\n <React.Fragment>\n <ImageResizer\n className={`w-100 ${loaded ? 'db' : 'dn'}`}\n alt={alt}\n src={realUrls[realUrlIndex]}\n minRatio={imageMinRatio}\n />\n {!loaded && (\n <div className=\"relative w-100 db\">\n <Loader />\n <ImageResizer\n alt={alt}\n src={loaderUrl}\n minRatio={imageMinRatio}\n className={`w-100 blur-30 transition-opacity-1 db z-2 o-100 ${className}`}\n />\n <ImageResizer\n alt=\"\"\n src={realUrls[realUrlIndex]}\n minRatio={imageMinRatio}\n className={`absolute z-1 w-100 center left-0 right-0 bottom-0 top-0 transition-opacity-1 db ${\n loadState === LOAD_STATES.LOADING ? 'o-0' : 'o-100'\n }`}\n />\n </div>\n )}\n </React.Fragment>\n )\n }\n}\n\nBlurredLoader.propTypes = {\n className: PropTypes.string,\n alt: PropTypes.string,\n loaderUrl: PropTypes.string.isRequired,\n realUrls: PropTypes.arrayOf(PropTypes.string).isRequired,\n thresholds: PropTypes.arrayOf(PropTypes.number),\n onload: PropTypes.func,\n bestUrlIndex: PropTypes.number,\n loaderType: PropTypes.oneOf([LOADER_TYPES.SPINNER, LOADER_TYPES.LINEAR]),\n}\n\nBlurredLoader.defaultProps = {\n thresholds: [],\n}\n\nexport default BlurredLoader\n\n```" } ]
code_butik_0388a189
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/ProductPrice/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport classNames from 'classnames'\nimport { isNil } from 'ramda'\nimport ContentLoader from 'react-content-loader'\nimport { FormattedMessage, injectIntl } from 'react-intl'\n\nimport PricePropTypes from './propTypes'\nimport Installments from './Installments'\n\n/**\n * The Price component. Shows the prices information of the Product Summary.\n */\nclass Price extends Component {\n static propTypes = PricePropTypes\n\n static defaultProps = {\n showListPrice: true,\n showLabels: true,\n showInstallments: false,\n showSavings: false,\n labelSellingPrice: null,\n }\n\n constructor(props) {\n super(props)\n\n this.currencyOptions = {\n style: 'currency',\n currency: props.currency,\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }\n }\n\n render() {\n const {\n sellingPrice,\n listPrice,\n unavailable,\n showListPrice,\n showInstallments,\n showLabels,\n showSavings,\n showStartingAt,\n labelSellingPrice,\n className,\n loaderClass,\n listPriceContainerClass,\n listPriceLabelClass,\n listPriceClass,\n sellingPriceContainerClass,\n sellingPriceLabelClass,\n sellingPriceClass,\n savingsContainerClass,\n savingsClass,\n installments,\n installmentClass,\n interestRateClass,\n installmentContainerClass,\n startingAtClass,\n unavailableClass,\n styles,\n intl: { formatNumber },\n } = this.props\n\n if ((showListPrice && isNil(listPrice)) || isNil(sellingPrice)) {\n return <Price.Loader loaderClass={loaderClass} {...styles} />\n }\n\n if (unavailable)\n return (\n <div className={unavailableClass}>\n <FormattedMessage id=\"pricing.unavailable\" />\n </div>\n )\n\n const differentPrices = showListPrice && sellingPrice !== listPrice\n\n return (\n <div className={classNames('vtex-price', className)}>\n {differentPrices && (\n <div\n className={classNames(\n 'vtex-price-list__container',\n listPriceContainerClass\n )}>\n {showLabels && (\n <div\n className={classNames(\n 'vtex-price-list__label',\n listPriceLabelClass\n )}>\n <FormattedMessage id=\"pricing.from\" />\n </div>\n )}\n <span className={classNames('vtex-price-list', listPriceClass)}>\n {formatNumber(listPrice, this.currencyOptions)}\n </span>\n </div>\n )}\n <div\n className={classNames(\n 'vtex-price-selling__container',\n sellingPriceContainerClass\n )}>\n {showLabels && (\n <div\n className={classNames(\n 'vtex-price-selling__label',\n sellingPriceLabelClass\n )}>\n {labelSellingPrice || <FormattedMessage id=\"pricing.to\" />}\n </div>\n )}\n {showStartingAt && (\n <span\n className={classNames(\n 'vtex-price-selling__from-tag',\n startingAtClass\n )}>\n <FormattedMessage id=\"pricing.startingAtLabel\" />{' '}\n </span>\n )}\n <div className={classNames('vtex-price-selling', sellingPriceClass)}>\n {formatNumber(sellingPrice, this.currencyOptions)}\n </div>\n </div>\n {showInstallments && (\n <Installments\n installments={installments}\n showLabels={showLabels}\n formatNumber={formatNumber}\n currencyOptions={this.currencyOptions}\n className={installmentContainerClass}\n interestRateClass={interestRateClass}\n installmentClass={installmentClass}\n />\n )}\n {differentPrices && showSavings && (\n <div\n className={classNames(\n 'vtex-price-savings__container',\n savingsContainerClass\n )}>\n <div className={classNames('vtex-price-savings', savingsClass)}>\n <FormattedMessage\n id=\"pricing.savings\"\n values={{\n savings: formatNumber(\n listPrice - sellingPrice,\n this.currencyOptions\n ),\n }}\n />\n </div>\n </div>\n )}\n </div>\n )\n }\n}\n\nPrice.Loader = (loaderProps = {}) => {\n const { loaderClass, ...filteredLoaderProps } = loaderProps\n\n return (\n <div className={classNames('vtex-price vtex-price-loader', loaderClass)}>\n <ContentLoader\n style={{\n width: '100%',\n height: '100%',\n }}\n width={300}\n height={70}\n preserveAspectRatio=\"xMinYMin meet\"\n {...filteredLoaderProps}>\n <rect\n height=\"0.75em\"\n width=\"50%\"\n x=\"25%\"\n {...filteredLoaderProps['vtex-price-list__container--loader']}\n />\n <rect {...filteredLoaderProps['vtex-price-selling__label--loader']} />\n <rect\n height=\"1em\"\n width=\"70%\"\n x=\"15%\"\n y=\"1.25em\"\n {...filteredLoaderProps['vtex-price-selling--loader']}\n />\n <rect\n height=\"0.75em\"\n width=\"80%\"\n x=\"10%\"\n y=\"2.75em\"\n {...filteredLoaderProps['vtex-price-installments--loader']}\n />\n <rect {...filteredLoaderProps['vtex-price-savings--loader']} />\n </ContentLoader>\n </div>\n )\n}\n\nPrice.Loader.displayName = 'Price.Loader'\n\nconst priceWithIntel = injectIntl(Price)\n\npriceWithIntel.schema = {\n title: 'editor.productPrice.title',\n description: 'editor.productPrice.description',\n type: 'object',\n properties: {\n labelSellingPrice: {\n type: 'string',\n title: 'editor.productPrice.labelSellingPrice',\n default: Price.defaultProps.labelSellingPrice,\n isLayout: true,\n },\n showListPrice: {\n type: 'boolean',\n title: 'editor.productPrice.showListPrice',\n default: Price.defaultProps.showListPrice,\n isLayout: true,\n },\n showLabels: {\n type: 'boolean',\n title: 'editor.productPrice.showLabels',\n default: Price.defaultProps.showLabels,\n isLayout: true,\n },\n showInstallments: {\n type: 'boolean',\n title: 'editor.productPrice.showInstallments',\n default: Price.defaultProps.showInstallments,\n isLayout: true,\n },\n showSavings: {\n type: 'boolean',\n title: 'editor.productPrice.showSavings',\n default: Price.defaultProps.showSavings,\n isLayout: true,\n },\n },\n}\n\nexport default priceWithIntel\n\n```" } ]
code_butik_d6316971
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/ProductPrice/Installments.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment } from 'react'\nimport classNames from 'classnames'\nimport { isEmpty } from 'ramda'\nimport { FormattedMessage } from 'react-intl'\nimport PropTypes from 'prop-types'\n\nimport PricePropTypes from './propTypes'\n\n/** Installments component */\nexport default class Installments extends Component {\n static propTypes = {\n /** Classes to be applied to the root element */\n className: PropTypes.string,\n /** Classes to be applied to installment value element */\n installmentClass: PropTypes.string,\n /** Classes to be applied to interest rate element */\n interestRateClass: PropTypes.string,\n /** Product installments to be displayed */\n installments: PricePropTypes.installments,\n /** Pages editor config to display labels */\n showLabels: PropTypes.bool.isRequired,\n /** react-intl function to format the prices*/\n formatNumber: PropTypes.func.isRequired,\n /** Options to be passe to the formatNumber function*/\n currencyOptions: PropTypes.shape({\n style: PropTypes.string.isRequired,\n currency: PropTypes.string.isRequired,\n minimumFractionDigits: PropTypes.number.isRequired,\n maximumFractionDigits: PropTypes.number.isRequired,\n }).isRequired,\n }\n render() {\n const {\n showLabels,\n formatNumber,\n installments,\n currencyOptions,\n className,\n installmentClass,\n interestRateClass,\n } = this.props\n\n if (!installments || isEmpty(installments)) {\n return null\n }\n\n const noInterestRateInstallments = installments.filter(\n installment => !installment.InterestRate\n )\n\n /*\n * - The selected installment will be the one with the highest `NumberOfInstallments`;\n * - If there is no 'interest-free' installments, the normal installments will be analyzed.\n */\n const installment = (isEmpty(noInterestRateInstallments)\n ? installments\n : noInterestRateInstallments\n ).reduce((previous, current) =>\n previous.NumberOfInstallments > current.NumberOfInstallments\n ? previous\n : current\n )\n\n const formattedInstallmentPrice = formatNumber(\n installment.Value,\n currencyOptions\n )\n\n const [installmentsElement, installmentPriceElement, timesElement] = [\n installment.NumberOfInstallments,\n formattedInstallmentPrice,\n <Fragment>x</Fragment>,\n ].map((element, index) => (\n <span className={installmentClass} key={index}>\n {element}\n </span>\n ))\n\n return (\n <div\n className={classNames('vtex-price-installments__container', className)}>\n {showLabels ? (\n <FormattedMessage\n id=\"pricing.installment-display\"\n values={{\n installments: installmentsElement,\n installmentPrice: installmentPriceElement,\n times: timesElement,\n }}\n />\n ) : (\n <Fragment>\n {installmentsElement}\n {timesElement} {installmentPriceElement}\n </Fragment>\n )}\n {!installment.InterestRate && (\n <div\n className={classNames(\n 'vtex-price-installments__interest-rate',\n interestRateClass\n )}>\n <FormattedMessage id=\"pricing.interest-free\" />\n </div>\n )}\n </div>\n )\n }\n}\n\n```" } ]
code_butik_ea01584d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/ProductPrice/README.md from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Product Price\n\nProduct Price is a canonical component that any VTEX app can import.\n\nTo import it into your code:\n\n```js\nimport ProductPrice from components2\n```\n\n## Usage\n\nYou can use it in your code like a React component with the jsx tag: `<ProductPrice />`.\n\n```jsx\n<ProductPrice\n showLabels={showLabels}\n showListPrice={showListPrice}\n showInstallments={showInstallments}\n sellingPrice={commertialOffer.Price}\n listPrice={commertialOffer.ListPrice}\n installments={commertialOffer.Installments}\n/>\n```\n\n### Passing classes to the elements of the component\nEvery prop that ends with `Class` will be passed to an element of the component, see the following code\n```jsx\n<ProductPrice\n className=\"pv4 overflow-hidden\"\n listPriceLabelClass=\"c-muted-4\"\n savingsClass=\"h4 ph5 dib\"\n showLabels={showLabels}\n showListPrice={showListPrice}\n showInstallments={showInstallments}\n sellingPrice={commertialOffer.Price}\n listPrice={commertialOffer.ListPrice}\n installments={commertialOffer.Installments}\n/>\n```\n\n| Prop name | Type | Description |\n| --- | --- | --- |\n| `sellingPrice` | `Number` | Product selling price |\n| `listPrice` | `Number` | Product list price |\n| `showListPrice` | `Boolean!` | Set visibility of list price |\n| `showLabels` | `Boolean!` | Set visibility of labels |\n| `showInstallments` | `Boolean!` | Set visibility of installments |\n| `showSavings` | `Boolean` | Set visibility of savings |\n| `installments` | `Array` | Available installments |\n| `installments.Value` | `Number!` | Installment price |\n| `installments.InterestRate` | `Number!` | Installment interest rate (zero if interest-free) |\n| `installments.TotalValuePlusInterestRate` | `Number` | Calculated total value |\n| `installments.NumberOfInstallments` | `Number!` | Number of installments |\n| `installments.Name` | `String` | Installment offer name |\n| `className` | `String` | Classes to be applied to root element |\n| `loaderClass` | `String` | Classes to be applied to loader root element |\n| `listPriceContainerClass` | `String` | Classes to be applied to container of list price |\n| `listPriceLabelClass` | `String` | Classes to be applied to label of price |\n| `listPriceClass` | `String` | Classes to be applied to price value |\n| `sellingPriceContainerClass` | `String` | Classes to be applied to selling price container |\n| `sellingPriceLabelClass` | `String` | Classes to be applied to selling price label |\n| `sellingPriceClass` | `String` | Classes to be applied to selling price value |\n| `savingsContainerClass` | `String` | Classes to be applied to savings container |\n| `savingsClass` | `String` | Classes to be applied to savings |\n| `installmentClass` | `String` | Classes to be applied to installment element |\n| `installmentContainerClass` | `String` | Classes to be applied to installment container |\n| `interestRateClass` | `String` | Classes to be applied to interest rate element |\n\nSee an example at [Product Summary](https://github.com/vtex-apps/product-summary) app\n\n```" } ]
code_butik_bd608e4a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/ProductPrice/propTypes.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport { intlShape } from 'react-intl'\n\nexport default {\n /** Currency, e.g.: \"BRL\" */\n currency: PropTypes.string,\n /** Product selling price */\n sellingPrice: PropTypes.number,\n /** Product list price */\n listPrice: PropTypes.number,\n /** True if the product is unavailable */\n unavailable: PropTypes.bool,\n /** Set visibility of list price */\n showListPrice: PropTypes.bool.isRequired,\n /** Set visibility of labels */\n showLabels: PropTypes.bool.isRequired,\n /** Set visibility of installments */\n showInstallments: PropTypes.bool.isRequired,\n /** Set visibility of savings */\n showSavings: PropTypes.bool,\n /** Shows 'From ' before the actual price */\n showStartingAt: PropTypes.bool,\n /** Text to the selling price's label */\n labelSellingPrice: PropTypes.string,\n /** Available installments */\n installments: PropTypes.arrayOf(\n PropTypes.shape({\n /** Installment value */\n Value: PropTypes.number.isRequired,\n /** Interest rate (zero if interest-free) */\n InterestRate: PropTypes.number.isRequired,\n /** Calculated total value */\n TotalValuePlusInterestRate: PropTypes.number,\n /** Number of installments */\n NumberOfInstallments: PropTypes.number.isRequired,\n /** Installment offer name */\n Name: PropTypes.string,\n })\n ),\n /** Classes to be applied to root element */\n className: PropTypes.string,\n /** Classes to be applied to loader root element */\n loaderClass: PropTypes.string,\n /** Classes to be applied to container of list price */\n listPriceContainerClass: PropTypes.string,\n /** Classes to be applied to label of price */\n listPriceLabelClass: PropTypes.string,\n /** Classes to be applied to price value */\n listPriceClass: PropTypes.string,\n /** Classes to be applied to selling price container */\n sellingPriceContainerClass: PropTypes.string,\n /** Classes to be applied to selling price label */\n sellingPriceLabelClass: PropTypes.string,\n /** Classes to be applied to selling price value */\n sellingPriceClass: PropTypes.string,\n /** Classes to be applied to savings container */\n savingsContainerClass: PropTypes.string,\n /** Classes to be applied to savings */\n savingsClass: PropTypes.string,\n /** Classes to be applied to installment element */\n installmentClass: PropTypes.string,\n /** Classes to be applied to installment container */\n installmentContainerClass: PropTypes.string,\n /** Classes to be applied to interest rate element */\n interestRateClass: PropTypes.string,\n /** Classes to be applied to the fromLabel */\n startingAtClass: PropTypes.string,\n /** Classes to be applied to the unavailable message */\n unavailableClass: PropTypes.string,\n /** Component and content loader styles */\n styles: PropTypes.object,\n /** intl property to format data */\n intl: intlShape.isRequired,\n}\n\n```" } ]
code_butik_c029f93c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/ProductName/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { Component } from 'react'\nimport ContentLoader from 'react-content-loader'\nimport classNames from 'classnames'\n\n/**\n * Name component. Show name and relevant SKU information of the Product Summary\n */\nclass ProductName extends Component {\n static propTypes = {\n /** Name of the product */\n name: PropTypes.string,\n /** Selected SKU name */\n skuName: PropTypes.string,\n /** Show sku */\n showSku: PropTypes.bool,\n /** Product reference */\n productReference: PropTypes.string,\n /** Show product reference */\n showProductReference: PropTypes.bool,\n /** Brand name */\n brandName: PropTypes.string,\n /** Show brand name */\n showBrandName: PropTypes.bool,\n /** Component and content loader styles */\n styles: PropTypes.object,\n /** Classes to be applied to root element */\n className: PropTypes.string,\n /** Classes to be applied to brandName element */\n brandNameClass: PropTypes.string,\n /** Classes to be applied to skuName element */\n skuNameClass: PropTypes.string,\n /** Classes to be applied to productReference element */\n productReferenceClass: PropTypes.string,\n /** Classes to be applied to loader root element */\n loaderClass: PropTypes.string,\n }\n\n static defaultProps = {\n showBrandName: false,\n showProductReference: false,\n showSku: false,\n }\n\n static Loader = (loaderProps = {}) => (\n <div\n className={classNames(\n 'vtex-product-name vtex-product-name-loader',\n loaderProps.className\n )}>\n <ContentLoader\n style={{\n width: '100%',\n height: '100%',\n }}\n width={456}\n height={100}\n preserveAspectRatio=\"xMinYMin meet\"\n {...loaderProps}>\n <rect\n height=\"1.125em\"\n width=\"75%\"\n x=\"15%\"\n {...loaderProps['vtex-product-name__brand--loader']}\n />\n <rect\n height=\"1.125em\"\n width=\"50%\"\n x=\"25%\"\n y=\"1.75em\"\n {...loaderProps['vtex-product-name__sku--loader']}\n />\n </ContentLoader>\n </div>\n )\n\n render() {\n const {\n productReferenceClass,\n brandNameClass,\n skuNameClass,\n loaderClass,\n className,\n name,\n styles,\n skuName,\n showSku,\n brandName,\n showBrandName,\n productReference,\n showProductReference,\n } = this.props\n\n if (!name) {\n return <ProductName.Loader className={loaderClass} {...styles} />\n }\n\n return (\n <div className={classNames('vtex-product-name', className)}>\n <span\n className={classNames('vtex-product-name__brand', brandNameClass)}>\n {name} {showBrandName && brandName && `- ${brandName}`}\n </span>\n {showSku && skuName && (\n <span className={classNames('vtex-product-name__sku', skuNameClass)}>\n {skuName}\n </span>\n )}\n {showProductReference && productReference && (\n <span\n className={classNames(\n 'vtex-product-name__product-reference',\n productReferenceClass\n )}>\n {`REF: ${productReference}`}\n </span>\n )}\n </div>\n )\n }\n}\n\nProductName.schema = {\n title: 'editor.productName.title',\n description: 'editor.productName.description',\n type: 'object',\n properties: {\n showBrandName: {\n type: 'boolean',\n title: 'editor.productName.showBrandName.title',\n default: false,\n isLayout: true,\n },\n showSku: {\n type: 'boolean',\n title: 'editor.productName.showSku.title',\n default: false,\n isLayout: true,\n },\n showProductReference: {\n type: 'boolean',\n title: 'editor.productName.showProductReference.title',\n default: false,\n isLayout: true,\n },\n },\n}\n\nexport default ProductName\n\n```" } ]
code_butik_b58e5bc2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/ProductName/README.md from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Product Name\nProduct Name is a canonical component that any VTEX app can import.\n\nTo import it into your code: \n```js\nimport ProductName from components2\n```\n\n## Usage\nYou can use it in your code like a React component with the jsx tag: `<ProductName />`. \n```jsx\n<ProductName\n showSku\n showBrandName\n name={product.productName}\n skuName={selectedItem.name}\n brandName={product.brand}\n/>\n```\n\n## Passing classes to the elements of the component\nEvery prop that ends with `Class` will be passed to an element of the component, see the code below\n```jsx\n<ProductName\n skuNameClass=\"some-other-css-class\"\n className=\"pv4 overflow-hidden\"\n brandNameClass=\"c-muted\"\n showSku\n showBrandName\n brandName={product.brand}\n name={product.productName}\n skuName={selectedItem.name}\n/>\n})\n```\n\n| Prop name | Type | Description |\n| --- | --- | --- |\n| `name` | `String!` | Name of the product |\n| `skuName` | `String` | Selected SKU name |\n| `showSku` | `Boolean` | Show product SKU |\n| `productReference` | `String` | Product reference |\n| `showProductReference` | `Boolean` | Show product reference |\n| `brandName` | `String` | Brand name |\n| `showBrandName` | `Boolean` | Show brand name |\n| `className` | `String` | Classes to be applied to root element |\n| `brandNameClass` | `String` | Classes to be applied to brandName element |\n| `skuNameClass` | `String` | Classes to be applied to skuName element |\n| `productReferenceClass` | `String` | Classes to be applied to productReference element |\n| `loaderClass` | `String` | Classes to be applied to loader root element |\n\nSee an example at [Product Details](https://github.com/vtex-apps/product-details) app\n\n```" } ]
code_butik_8f1a1ee5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/SKUSelector/global.css from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n/* Hide the browser's default radio button */\n.vtex-sku-selector__item {\n font-size: 90%;\n margin-bottom: 10px;\n margin-right: 10px;\n height: 36px;\n}\n\n.vtex-sku-selector__item-image {\n padding: 0;\n height: 40px;\n width: 40px;\n}\n\n.diagonal-cross {\n background-image: linear-gradient(\n to top right,\n transparent 44%,\n rgba(0, 0, 0, 0.3) 48%,\n currentColor 48%,\n currentColor 52%,\n transparent 52%\n );\n}\n\n.frame-around {\n bottom: -0.25rem;\n top: -0.25rem;\n left: -0.25rem;\n right: -0.25rem;\n}\n\n```" } ]
code_butik_e0432cea
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/SKUSelector/index.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport PropTypes from 'prop-types'\nimport VariationSelector from './components/VariationSelector'\nimport { Machine } from 'xstate'\nimport { interpret } from 'xstate/lib/interpreter'\nimport hash from 'object-hash'\nimport './global.css'\n\n/**\n * Display a list of SKU items of a product and its specifications.\n */\nclass SKUSelector extends PureComponent {\n constructor(props) {\n super(props)\n\n this.state = {}\n this.visualVariations = []\n this.standardVariations = []\n this.stateMachine = {}\n this.variationsOptions = {}\n }\n\n componentDidMount() {\n const { skus, variations, selectedVariations } = this.props\n if (!variations || !variations.length) return\n\n variations.forEach(variation => {\n /** Separate all variations into visualVariations and standardVariations based on the thumbSrc value */\n if (variation.hasThumbs) this.visualVariations.push(variation.name)\n else this.standardVariations.push(variation.name)\n\n /** Fills variationsOptions with all possible variationOptions */\n this.variationsOptions[variation.name] = {}\n skus.forEach(sku => {\n this.variationsOptions[variation.name][sku[variation.name]] = true\n })\n })\n\n this.stateMachine.interpret = interpret(\n this.createStateMachine(\n skus,\n this.visualVariations,\n this.standardVariations,\n selectedVariations && hash(selectedVariations)\n )\n )\n\n this.setState({ stateMachineStateHash: this.stateMachine.initial })\n this.stateMachine.interpret.onTransition(this.handleStateTransition).start()\n }\n\n handleStateTransition = state => {\n const stateMachineStateHash = state.value\n const { onChange } = this.props\n\n this.setState({ stateMachineStateHash })\n\n const stateMachineState = this.stateMachine.states[stateMachineStateHash]\n\n const selectedVariations = stateMachineState.variations\n const { sku, price } = stateMachineState\n\n const allVariationsSelected = Object.keys(selectedVariations).reduce(\n (accumulator, variation) =>\n accumulator && selectedVariations[variation] !== null,\n true\n )\n\n onChange({\n sku,\n allVariationsSelected,\n selectedVariations,\n price,\n })\n }\n\n /** Returns the variation that has a different label if there is exactly one different variation\n * or undefined otherwise\n * */\n getDifferentVariation = (stateA, stateB) => {\n let counter = 0\n let differentVariation = null\n\n Object.keys(stateA).forEach(variation => {\n if (stateA[variation] !== stateB[variation]) {\n counter++\n differentVariation = variation\n }\n })\n\n if (counter === 1) return differentVariation\n }\n\n /** Creates a state machine whose state is based on the selected variations **/\n createStateMachine = (\n skus,\n visualVariations,\n standardVariations,\n initialState\n ) => {\n const { stateMachine } = this\n stateMachine.id = 'SKUSelector'\n stateMachine.states = {}\n stateMachine.transitions = {}\n\n const { states, transitions } = stateMachine\n\n skus.forEach(sku => {\n /** Creates all possible states without selecting some standardVariations **/\n const bitMaskLimit = 1 << standardVariations.length\n\n for (let bitMask = 0; bitMask < bitMaskLimit; bitMask++) {\n const state = { variations: {} }\n\n visualVariations.forEach(\n variation => (state.variations[variation] = sku[variation])\n )\n\n standardVariations.forEach((variation, variationIndex) => {\n if ((1 << variationIndex) & bitMask)\n state.variations[variation] = sku[variation]\n else state.variations[variation] = null\n })\n\n const stateKey = hash(state.variations)\n\n if (bitMask === 0 && !stateMachine.initial)\n stateMachine.initial = stateKey\n\n if (!states[stateKey] || !states[stateKey].available) {\n if (!states[stateKey]) states[stateKey] = {}\n\n states[stateKey].variations = state.variations\n states[stateKey].sku = sku.sku\n states[stateKey].available = sku.available\n }\n\n if (sku.available) {\n if (states[stateKey].price) {\n const { value, notUnique } = states[stateKey].price\n\n states[stateKey].price.notUnique =\n notUnique || sku.price.notUnique || sku.price.value !== value\n\n states[stateKey].price.value = Math.min(value, sku.price.value)\n } else states[stateKey].price = { ...sku.price }\n }\n }\n })\n\n /** Creates a transition from A to B if there is only one different variation **/\n Object.keys(states).forEach(keyA => {\n states[keyA].on = {}\n\n Object.keys(states).forEach(keyB => {\n const stateA = states[keyA].variations\n const stateB = states[keyB].variations\n\n const differentVariation = this.getDifferentVariation(stateA, stateB)\n if (!differentVariation) return\n\n const action = {\n variation: differentVariation,\n label: stateB[differentVariation],\n }\n\n const actionHash = hash(action)\n transitions[actionHash] = action\n states[keyA].on[actionHash] = keyB\n })\n })\n\n if (initialState && stateMachine.states[initialState])\n stateMachine.initial = initialState\n\n return Machine(stateMachine)\n }\n\n onSelectItem = actionHash => () => {\n this.stateMachine.interpret.send(actionHash)\n }\n\n render() {\n if (!this.props.variations || !this.props.variations.length) return null\n\n const { visualVariations, standardVariations } = this\n const { askToSelectVariations, designTokens } = this.props\n const variations = visualVariations.concat(standardVariations)\n\n const { stateMachineStateHash } = this.state\n if (!stateMachineStateHash) return <div />\n\n const stateMachineStates = this.stateMachine.states\n const stateMachineState = stateMachineStates[stateMachineStateHash]\n\n const transitions = stateMachineState.on\n const selectedVariations = stateMachineState.variations\n\n return (\n <React.Fragment>\n {variations.map((variation, variationIndex) => {\n const selectedItem = selectedVariations[variation]\n\n const items = Object.keys(this.variationsOptions[variation]).reduce(\n (accumulator, label) => {\n const selected = selectedItem === label\n\n const actionHash = hash({\n variation,\n label: selected ? null : label,\n })\n\n const nextStateHash = transitions[actionHash]\n\n if (nextStateHash || selected) {\n const available = selected\n ? stateMachineState.available\n : stateMachineStates[nextStateHash].available\n\n accumulator.push({\n label,\n available,\n thumbSrc: null,\n onSelectItem: this.onSelectItem(actionHash),\n })\n }\n return accumulator\n },\n []\n )\n\n return (\n <VariationSelector\n key={variationIndex}\n variation={{\n name: variation,\n items,\n }}\n designTokens={designTokens}\n selectedItem={selectedItem}\n askToSelectVariation={askToSelectVariations && !selectedItem}\n />\n )\n })}\n </React.Fragment>\n )\n }\n}\n\nSKUSelector.propTypes = {\n /** Variation name, the same used as key in 'skus' */\n variations: PropTypes.arrayOf(\n PropTypes.shape({\n name: PropTypes.string,\n hasThumbs: PropTypes.bool,\n })\n ),\n /** Can just pass vtex product.items */\n skus: PropTypes.arrayOf(\n PropTypes.shape({\n /** Value that will be returned when selected */\n sku: PropTypes.any,\n /** True if it's available, available quantity > 0 */\n available: PropTypes.bool,\n /** Necessary for the component return the minimum price at each state */\n price: PropTypes.shape({\n /** The minimum price of that Sku */\n value: PropTypes.number,\n /** True if this sku have different prices from multiple sellers */\n notUnique: PropTypes.bool,\n }),\n /** Also has the values for each variation as variationName: label */\n })\n ),\n /** selectedVariations in the initial state of the form {variationName: label}\n * for all variations using null if it's not selected */\n selectedVariations: PropTypes.object,\n /** Function called when the state change is triggered. It receives the selected sku,\n * the variations that are selected and a boolean telling if all variations are selected */\n onChange: PropTypes.func,\n /** Boolean prop that displays a warning text beside not selected variations */\n askToSelectVariations: PropTypes.bool,\n /** Used to change internal designs. When set, will replace component className **/\n designTokens: PropTypes.shape({ skuSelectorContainer: PropTypes.string }),\n}\n\nexport default SKUSelector\n\n```" } ]
code_butik_fd8e4001
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/SKUSelector/components/VariationSelector.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport PropTypes from 'prop-types'\nimport ItemSelector from './ItemSelector'\n\nclass VariationSelector extends React.PureComponent {\n render() {\n const {\n variation,\n selectedItem,\n askToSelectVariation,\n designTokens,\n } = this.props\n\n return (\n <div\n className={\n (designTokens && designTokens.skuSelectorContainer) ||\n 'vtex-sku-selector__container flex flex-column mb7'\n }>\n <div className=\"vtex-sku-selector__name-container ma1\">\n <span className=\"vtex-sku-selector__name db t-small overflow-hidden mb3\">\n <span className=\"c-muted-2\">{variation.name}</span>\n {askToSelectVariation ? (\n <span className=\"c-danger ml3 t-mini\">\n <FormattedMessage id=\"sku-selector.select-warning\" />{' '}\n {variation.name}\n </span>\n ) : null}\n </span>\n <div className=\"inline-flex flex-wrap ml2\">\n {variation.items.map((item, i) => (\n <ItemSelector\n selected={selectedItem === item.label}\n key={i}\n handleSelect={item.onSelectItem}\n label={item.label}\n thumbSrc={item.thumbSrc}\n isAvailable={item.available}\n variation={variation.name}\n />\n ))}\n </div>\n </div>\n </div>\n )\n }\n}\n\nVariationSelector.propTypes = {\n variation: PropTypes.shape({\n name: PropTypes.string.isRequired,\n items: PropTypes.arrayOf(\n PropTypes.shape({\n label: PropTypes.string.isRequired,\n available: PropTypes.bool.isRequired,\n thumbSrc: PropTypes.string,\n onSelectItem: PropTypes.func.isRequired,\n })\n ).isRequired,\n }).isRequired,\n /** It's either null when no item is selected or the selected item index */\n selectedItem: PropTypes.string,\n askToSelectVariation: PropTypes.bool,\n designTokens: PropTypes.shape({ skuSelectorContainer: PropTypes.string }),\n}\n\nexport default VariationSelector\n\n```" } ]
code_butik_02112451
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of butik/react/components/SKUSelector/components/ItemSelector.js from the butik VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n\nfunction ItemSelector(props) {\n const {\n selected,\n handleSelect,\n isAvailable,\n thumbSrc,\n label,\n variation,\n } = props\n\n return (\n <div\n className={classNames(\n 'vtex-sku-selector__item relative di pointer flex items-center',\n thumbSrc && 'vtex-sku-selector__item-image'\n )}\n onClick={handleSelect}>\n <div\n className={classNames(\n 'absolute frame-around b--action-primary br3 bw1',\n selected && 'ba'\n )}\n />\n <div\n className={classNames(\n 'w-100 h-100 ba br2 b b--muted-4 z-1 c-muted-5 flex items-center overflow-hidden',\n selected || 'hover-b--muted-2'\n )}>\n <div\n className={classNames(\n 'absolute absolute--fill',\n isAvailable || 'diagonal-cross'\n )}\n />\n <div className={classNames(thumbSrc || 'c-on-base center pl5 pr5 z-1')}>\n {thumbSrc ? <img src={thumbSrc} alt={label} /> : label}\n </div>\n </div>\n </div>\n )\n}\n\nItemSelector.propTypes = {\n label: PropTypes.string,\n selected: PropTypes.bool,\n handleSelect: PropTypes.func,\n thumbSrc: PropTypes.string,\n isAvailable: PropTypes.bool,\n variation: PropTypes.string,\n}\nexport default ItemSelector\n\n```" } ]
code_sms-link_45e7a663
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/docs/README.md from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# VTEX SMSLink\n\nAllows the sending of transactional SMS messages to customers using SMSLink SMS Gateway. This application uses [Feed v3 Hook](https://developers.vtex.com/reference/feed-v3) for receiving status updates from OMS.\n\nThis app handles events sent by the app `vtex.orders-broadcast` and `vtex.return-app`[^1] to notify customers using the SMSLink SMS Gateway API.\n\n## Installation Guide\n\nOpen the VTEX App Store and install this app on your store, or run the following command on VTEX toolbelt:\n`vtex install vtex.smslink@0.x`\n\n## Setup\n\nGo to `https://{accountName}.myvtex.com/admin/apps/`, search for `SMSLink` and fill up the form with the settings you need.\n\n1. `Enable Test Mode` - This option can be used if you are further developing this app. When checked the transactional messages sent through the SMSLink Gateway API will just be simulated and no charges will be incurred on your SMSLink account.\n\n2. `Connection ID` & `Password` - Those fields are mandatory and their values are generated through your SMSLink account in the SMS Gateway (JSON) configuration section.\n\n3. `Send Order received SMS` & `Order received SMS message` - If the `Send Order received SMS` option is checked then the customer will receive a transactional SMS message through the SMSLink SMS Gateway every time the `order-created` event is received. The content of the transactional message is specified inside the `Order received SMS message` input field. The `{order_id}` will automatically be replaced with the customer's `orderId` upon sending.\n\n4. `Send Order cancelled SMS` & `Order cancelled SMS message` - If the `Send Order cancelled SMS` option is checked then the customer will receive a transactional SMS message through the SMSLink SMS Gateway every time the `cancel` event is received. The content of the transactional message is specified inside the `Order cancelled SMS message` input field. The `{order_id}` will automatically be replaced with the customer's `orderId` upon sending.\n\n5. `Send Online payment authorized SMS` & `Online payment Authorized SMS message` - If the `Send Online payment authorized SMS` option is checked then the customer will receive a transactional SMS message through the SMSLink SMS Gateway every time the `payment-approved` event is received. The content of the transactional message is specified inside the `Online payment Authorized SMS message` input field. The `{order_id}` will automatically be replaced with the customer's `orderId` upon sending.\n\n6. `Send Online payment error SMS` & `Online payment error SMS message` - If the `Send Online payment error SMS` option is checked then the customer will receive a transactional SMS message through the SMSLink SMS Gateway every time the `payment-denied` event is received. The content of the transactional message is specified inside the `Online payment error SMS message` input field. The `{order_id}`, `{first_name}`, `{last_name}`, `{email}`, `{order_total}` will automatically be replaced with the customer's order corresponding values upon sending.\n\n7. `Send Return request SMS` & `Return request received SMS message` - If the `Send Return request SMS` option is checked then the customer will receive a transactional SMS message through the `vtex.return-app` ervery time a return request has been recived. The content of the transactional message is specified inside the `Return request received SMS message` input field. The `{request_id}`, `{name}`, `{email}`, `{order_id}`, `{gift_card_code}`, `{gift_card_id}`, `{refunded_amount}` will automatically be replaced with the customer's return request corresponding values upon sending.\n\n8. `Send Returned parcel received by store SMS` & `Send Returned parcel received by store SMS message` - If the `Send Returned parcel received by store SMS` option is checked then the customer will receive a transactional SMS message through the `vtex.return-app` ervery time the status of the return request is changed to `picked`. The content of the transactional message is specified inside the `Send Returned parcel received by store SMS message` input field. The `{request_id}`, `{name}`, `{email}`, `{order_id}`, `{gift_card_code}`, `{gift_card_id}`, `{refunded_amount}` will automatically be replaced with the customer's return request corresponding values upon sending.\n\n9. `Return request finalized SMS` & `Return request finalized SMS message` - If the `Return request finalized SMS` option is checked then the customer will receive a transactional SMS message through the `vtex.return-app` ervery time the the return request is approved. The content of the transactional message is specified inside the `Return request finalized SMS message` input field. The `{request_id}`, `{name}`, `{email}`, `{order_id}`, `{gift_card_code}`, `{gift_card_id}`, `{refunded_amount}` will automatically be replaced with the customer's return request corresponding values upon sending.\n\n10. `Return request denied SMS` & `Return request denied SMS message` - If the `Return request denied SMS` option is checked then the customer will receive a transactional SMS message through the `vtex.return-app` ervery time the the return request is denied. The content of the transactional message is specified inside the `Return request denied SMS message` input field. The `{request_id}`, `{name}`, `{email}`, `{order_id}`, `{gift_card_code}`, `{gift_card_id}`, `{refunded_amount}` will automatically be replaced with the customer's return request corresponding values upon sending.\n\n# How it works?\n\n1. For [Feed V3 Hooks](https://developers.vtex.com/reference/feed-v3)\n\nWhen one of the `order-created`, `cancel`, `payment-approved` or `payment-denied` events is received, the app will check if the corresponding option fields are checked (if it is allowed to send the transactional message or not). If the app is allowed to send the transactional message then it will retrieve the order data and send the message to the customer phone number through the SMSLink SMS Gateway.\n\n2. For `vtex.return-app`[^1]\n\nWhen the return request state changes to one of the following states: `New`, `Picked up from client`, `Approved` or `Denied` the `vtex.return-app` will send a request to the SMSLink app through `https://{accountName}.myvtex.com/sms-link-app/send-sms` route. The SMSLink app will then check if it is allowed to send the transactional message according to the specified event and send the message to the custumer phone number through the SMSLink SMS Gateway.\n\n\n[^1]: The `vtex.smslink` & `vtex.return-app` will be available in future `vtex.return-app` update \n```" } ]
code_sms-link_42b0f0f6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/service.json from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 2,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"workers\": 1,\n \"events\": {\n \"orderCreated\": {\n \"sender\": \"vtex.orders-broadcast\",\n \"topics\": [\"order-created\"]\n },\n \"orderCancelled\": {\n \"sender\": \"vtex.orders-broadcast\",\n \"topics\": [\"cancel\"]\n },\n \"paymentApproved\": {\n \"sender\": \"vtex.orders-broadcast\",\n \"topics\": [\"payment-approved\"]\n },\n \"paymentDenied\": {\n \"sender\": \"vtex.orders-broadcast\",\n \"topics\": [\"payment-denied\"]\n }\n },\n \"routes\": {\n \"sendSMS\": {\n \"path\": \"/sms-link-app/send-sms\",\n \"public\": true,\n \"settingsType\": \"workspace\"\n }\n }\n\n}\n\n```" } ]
code_sms-link_a477872c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/package.json from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"ramda\": \"^0.25.0\",\n \"splunk-events\": \"^1.2.3\",\n \"axios\": \"^0.18.0\",\n \"@vtex/api\": \"6.45.15\",\n \"@vtex/clients\": \"^2.17.0\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/koa\": \"^2.0.39\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.15\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"tslint\": \"^5.14.0\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typescript\": \"3.9.7\",\n \"@vtex/tsconfig\": \"^0.5.6\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'\"\n },\n \"version\": \"0.3.0\"\n}\n\n```" } ]
code_sms-link_9d2c800c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/tslint.json from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"extends\": \"tslint-config-vtex\",\n \"rules\": {\n \"object-literal-sort-keys\": false\n },\n \"jsRules\": {\n \"object-literal-sort-keys\": false\n }\n}\n\n```" } ]
code_sms-link_201fda2e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/index.ts from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n ClientsConfig,\n EventContext,\n RecorderState,\n ServiceContext,\n} from '@vtex/api'\nimport { LRUCache, method, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { sendSMS } from './middlewares/api/sendSMS'\nimport { orderCancelled } from './middlewares/orderCancelled'\nimport { orderCreated } from './middlewares/orderCreated'\nimport { paymentApproved } from './middlewares/paymentApproved'\nimport { paymentDenied } from './middlewares/paymentDenied'\n\nconst TIMEOUT_MS = 800\n\nconst memoryCache = new LRUCache<string, any>({ max: 5000 })\n\nmetrics.trackCache('status', memoryCache)\n\nconst clients: ClientsConfig<Clients> = {\n implementation: Clients,\n options: {\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n status: {\n memoryCache,\n },\n },\n}\n\ndeclare global {\n type Context = ServiceContext<Clients, State>\n\n interface StatusChangeContext extends EventContext<Clients> {\n body: {\n domain: string\n orderId: string\n currentState: string\n lastState: string\n currentChangeDate: string\n lastChangeDate: string\n }\n }\n\n type State = RecorderState\n}\n\nexport default new Service({\n clients,\n events: {\n orderCreated,\n orderCancelled,\n paymentApproved,\n paymentDenied,\n },\n routes: {\n sendSMS: method({\n POST: sendSMS,\n }),\n },\n})\n\n```" } ]
code_sms-link_70d84191
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/clients/sms.ts from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nimport { logEvent } from '../utils/helpers'\n\nexport default class SMSLink extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super('', context, {\n ...options,\n headers: {\n ...(options?.headers ?? {}),\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'X-Vtex-Use-Https': 'true',\n },\n })\n }\n\n public async sendJsonMessage(body: any) {\n this.http\n .post(\n `http://secure.smslink.ro/sms/gateway/communicate/json.php`,\n JSON.stringify(body)\n )\n .then((response: any) => {\n if (response.response_type === 'ERROR') {\n logEvent('Critical', 'Error', 'smslink-send', {\n account: this.context.account,\n message: response.response_message,\n sourceType: 'LOG',\n })\n } else {\n logEvent('Important', 'Info', 'smslink-send', {\n account: this.context.account,\n message: response.response_message,\n sourceType: 'LOG',\n })\n }\n })\n .catch((error) => {\n logEvent('Critical', 'Error', 'smslink-send', {\n account: this.context.account,\n message: error.toString(),\n sourceType: 'LOG',\n })\n })\n }\n}\n\n```" } ]
code_sms-link_c38cd4e1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/clients/index.ts from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\nimport { OMS } from '@vtex/clients'\n\nimport SMSLink from './sms'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get oms() {\n return this.getOrSet('oms', OMS)\n }\n\n public get sms() {\n return this.getOrSet('sms', SMSLink)\n }\n}\n\n```" } ]
code_sms-link_47b73482
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/typings/splunk-events.d.ts from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'splunk-events'\n\ndeclare module 'colossus' {\n import type { Context as KoaContext } from 'koa'\n\n export interface IOContext {\n account: string\n workspace: string\n authToken: string\n params: {\n [param: string]: string\n }\n region: string\n route: string\n }\n\n export interface ColossusContext extends KoaContext {\n vtex: IOContext\n }\n}\n\n```" } ]
code_sms-link_98d3207c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/middlewares/orderCreated.ts from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n formatMessage,\n getSettings,\n isMessageValid,\n logEvent,\n} from '../utils/helpers'\n\nexport async function orderCreated(\n ctx: StatusChangeContext,\n next: () => Promise<any>\n) {\n const {\n clients: { oms, sms },\n } = ctx\n\n if (ctx.body.domain === 'Marketplace') {\n const settings = await getSettings(ctx)\n\n if (\n settings.allowSendOrderReceivedSMS &&\n settings.orderReceivedText &&\n isMessageValid(settings.orderReceivedText)\n ) {\n const order = await oms.order(ctx.body.orderId)\n\n if (order != null) {\n const message = formatMessage(settings.orderReceivedText, order)\n\n // Send message to user\n await sms.sendJsonMessage({\n connection_id: settings.connectionID,\n password: settings.password,\n to: order.clientProfileData.phone,\n message,\n test: settings.enableSandbox ? 1 : 0,\n })\n } else {\n logEvent('Critical', 'Error', 'get-order-info', {\n account: ctx.vtex.account,\n message: `Invalid Order data received for orderId=${ctx.body.orderId} !`,\n sourceType: 'LOG',\n })\n }\n } else if (settings.allowSendOrderReceivedSMS) {\n logEvent('Critical', 'Error', 'get-settings', {\n account: ctx.vtex.account,\n message: 'Empty <message> or invalid character detected!',\n sourceType: 'LOG',\n })\n }\n }\n \n await next()\n}\n\n```" } ]
code_sms-link_fcea875d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/middlewares/orderCancelled.ts from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n formatMessage,\n getSettings,\n isMessageValid,\n logEvent,\n} from '../utils/helpers'\n\nexport async function orderCancelled(\n ctx: StatusChangeContext,\n next: () => Promise<any>\n) {\n const {\n clients: { oms, sms },\n } = ctx\n\n if (ctx.body.domain === 'Marketplace') {\n const settings = await getSettings(ctx)\n if (\n settings.allowCancelledOrderSMS &&\n settings.orderCancelledText &&\n isMessageValid(settings.orderCancelledText)\n ) {\n const order = await oms.order(ctx.body.orderId)\n\n if (order != null) {\n const message = formatMessage(settings.orderCancelledText, order)\n\n // Send message to user\n await sms.sendJsonMessage({\n connection_id: settings.connectionID,\n password: settings.password,\n to: order.clientProfileData.phone,\n message,\n test: settings.enableSandbox ? 1 : 0,\n })\n } else {\n logEvent('Critical', 'Error', 'get-order-info', {\n account: ctx.vtex.account,\n message: `Invalid Order data received for orderId=${ctx.body.orderId} !`,\n sourceType: 'LOG',\n })\n }\n } else if (settings.allowCancelledOrderSMS) {\n logEvent('Critical', 'Error', 'get-settings', {\n account: ctx.vtex.account,\n message: 'Empty <message> or invalid character detected!',\n sourceType: 'LOG',\n })\n }\n\n await next()\n } else {\n await next()\n }\n}\n\n```" } ]
code_sms-link_e4df03ad
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/middlewares/paymentApproved.ts from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n formatMessage,\n getSettings,\n isMessageValid,\n logEvent,\n} from '../utils/helpers'\n\nexport async function paymentApproved(\n ctx: StatusChangeContext,\n next: () => Promise<any>\n) {\n const {\n clients: { oms, sms },\n } = ctx\n\n if (ctx.body.domain === 'Marketplace') {\n const settings = await getSettings(ctx)\n\n if (\n settings.allowPaymentAuthorizedSMS &&\n settings.onlinePaymentAuthorizedText &&\n isMessageValid(settings.onlinePaymentAuthorizedText)\n ) {\n const order = await oms.order(ctx.body.orderId)\n\n if (order != null) {\n const message = formatMessage(settings.onlinePaymentAuthorizedText, order)\n\n // Send message to user\n await sms.sendJsonMessage({\n connection_id: settings.connectionID,\n password: settings.password,\n to: order.clientProfileData.phone,\n message,\n test: settings.enableSandbox ? 1 : 0,\n })\n } else {\n logEvent('Critical', 'Error', 'get-order-info', {\n account: ctx.vtex.account,\n message: `Invalid Order data received for orderId=${ctx.body.orderId} !`,\n sourceType: 'LOG',\n })\n }\n } else if (settings.allowPaymentAuthorizedSMS) {\n logEvent('Critical', 'Error', 'get-settings', {\n account: ctx.vtex.account,\n message: 'Empty <message> or invalid character detected!',\n sourceType: 'LOG',\n })\n }\n }\n \n await next()\n}\n\n```" } ]
code_sms-link_8a1bb189
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/middlewares/paymentDenied.ts from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n formatMessage,\n getSettings,\n isMessageValid,\n logEvent,\n} from '../utils/helpers'\n\nexport async function paymentDenied(\n ctx: StatusChangeContext,\n next: () => Promise<any>\n) {\n const {\n clients: { oms, sms },\n } = ctx\n\n if (ctx.body.domain === 'Marketplace') {\n const settings = await getSettings(ctx)\n\n if (\n settings.allowPaymentErrorSMS &&\n settings.onlinePaymentErrorText &&\n isMessageValid(settings.onlinePaymentErrorText)\n ) {\n const order = await oms.order(ctx.body.orderId)\n\n if (order != null) {\n const message = formatMessage(settings.onlinePaymentErrorText, order)\n\n // Send message to user\n await sms.sendJsonMessage({\n connection_id: settings.connectionID,\n password: settings.password,\n to: order.clientProfileData.phone,\n message,\n test: settings.enableSandbox ? 1 : 0,\n })\n } else {\n logEvent('Critical', 'Error', 'get-order-info', {\n account: ctx.vtex.account,\n message: `Invalid Order data received for orderId=${ctx.body.orderId} !`,\n sourceType: 'LOG',\n })\n }\n } else if (settings.allowPaymentErrorSMS) {\n logEvent('Critical', 'Error', 'get-settings', {\n account: ctx.vtex.account,\n message: 'Empty <message> or invalid character detected!',\n sourceType: 'LOG',\n })\n }\n }\n \n await next()\n}\n\n```" } ]
code_sms-link_5a258e49
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/utils/helpers.ts from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Apps } from '@vtex/api'\nimport axios from 'axios'\nimport type { ColossusContext } from 'colossus'\nimport SplunkEvents from 'splunk-events'\n\nconst SPLUNK_ENDPOINT = 'splunk-heavyforwarder-public.vtex.com'\nconst splunkEvents = new SplunkEvents()\n\nfunction splunkCustomFetcher(context: ColossusContext) {\n const headers = context.headers || {}\n\n return axios({\n ...context,\n headers: {\n ...headers,\n 'Proxy-Authorization': context.vtex.authToken,\n 'X-Vtex-Proxy-To': `https://${SPLUNK_ENDPOINT}:8088`,\n },\n })\n}\n\nsplunkEvents.config({\n debug: true,\n endpoint: `http://${SPLUNK_ENDPOINT}`,\n request: splunkCustomFetcher,\n token: '473bad07-24e0-4c46-964e-d6f059ec8789',\n})\n\nexport const getSettings = (ctx: any) => {\n const apps = new Apps(ctx.vtex)\n\n return apps.getAppSettings(ctx.vtex.userAgent)\n}\n\nexport const isMessageValid = (message: string) => {\n // eslint-disable-next-line no-useless-escape\n return /^[a-zA-Z0-9 \\!\\@\\#\\$\\%\\&\\*\\(\\)\\_\\+\\-\\|\\=\\;\\:\\,\\.\\<\\>\\/\\?\\[\\]\\{\\}\\~\\^\\\\\\\\\"\\'\\`\\\\n\\\\r\\\\t]+$/.test(\n message\n )\n}\n\nexport const formatMessage = (message: string, data: any, type = 'order') => {\n let newMessage = message\n\n const { creationDate } = data\n const estimateDays = data.shippingData?.logisticsInfo?.[0]?.shippingEstimate\n const estimateDate = data.shippingData?.logisticsInfo?.[0]?.shippingEstimateDate\n\n let deliveryDate = estimateDate ? new Date(estimateDate) : new Date(creationDate)\n if (!estimateDate) {\n deliveryDate.setDate(deliveryDate.getDate() + Number(String(estimateDays)?.replace(/\\D/g, '')))\n }\n\n const formattedDeliveryDate = new Intl.DateTimeFormat('ro-RO', { day: \"numeric\", month: \"long\", year: \"numeric\" }).format(deliveryDate)\n\n if (type === 'order') {\n newMessage = newMessage\n .replace('{order_id}', data.orderId)\n .replace('{first_name}', data.clientProfileData.firstName)\n .replace('{last_name}', data.clientProfileData.lastName)\n .replace('{email}', data.clientProfileData.email)\n .replace('{order_total}', (Number(data.value) / 100).toString())\n .replace('{delivery_date}', formattedDeliveryDate)\n }\n\n if (type === 'refund') {\n newMessage = newMessage\n .replace('{name}', data.name)\n .replace('{email}', data.email)\n .replace('{gift_card_code}', data.giftCardCode)\n .replace('{gift_card_id}', data.giftCardId)\n .replace('{refunded_amount}', data.refundedAmount)\n .replace('{request_id}', data.requestId)\n .replace('{order_id}', data.orderId)\n }\n\n return newMessage\n}\n\nexport const logEvent = (\n level: string,\n type: string,\n workflow: string,\n event: any\n) => {\n try {\n splunkEvents.logEvent(level, type, workflow, '-', event)\n } catch (e) {\n return e\n }\n}\n\n```" } ]
code_sms-link_32ff3ca2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of sms-link/node/middlewares/api/sendSMS.ts from the sms-link VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nimport {\n formatMessage,\n getSettings,\n isMessageValid,\n logEvent,\n} from '../../utils/helpers'\n\nexport async function sendSMS(ctx: Context, next: () => Promise<any>) {\n const {\n clients: { sms },\n } = ctx\n\n const settings = await getSettings(ctx)\n const body = await json(ctx.req)\n\n let settingToCheck = false\n let messageToSend = ''\n\n switch (body.event) {\n case 'request-created': {\n settingToCheck = settings.allowSendReturnRequestSMS\n messageToSend = formatMessage(\n settings.sendReturnRequestText,\n body,\n 'refund'\n )\n break\n }\n\n case 'parcel-received': {\n settingToCheck = settings.allowSendReturnedParcelReceivedSMS\n messageToSend = formatMessage(\n settings.sendReturnedParcelReceivedText,\n body,\n 'refund'\n )\n break\n }\n\n case 'request-denied': {\n settingToCheck = settings.allowSendReturnRequestDeniedSMS\n messageToSend = formatMessage(\n settings.sendReturnRequestDeniedText,\n body,\n 'refund'\n )\n break\n }\n\n default: {\n settingToCheck = settings.allowSendReturnRequestFinalizedSMS\n messageToSend = formatMessage(\n settings.sendReturnRequestFinalizedText,\n body,\n 'refund'\n )\n }\n }\n\n if (settingToCheck && messageToSend && isMessageValid(messageToSend)) {\n await sms.sendJsonMessage({\n connection_id: settings.connectionID,\n password: settings.password,\n to: body.phone,\n message: messageToSend,\n test: settings.enableSandbox ? 1 : 0,\n })\n } else if (settingToCheck) {\n logEvent('Critical', 'Error', 'get-settings', {\n account: ctx.vtex.account,\n message: 'Empty <message> or invalid character detected!',\n sourceType: 'LOG',\n })\n }\n\n ctx.status = 200\n ctx.body = 'OK'\n await next()\n}\n\n```" } ]
code_payment-connector-aws-cdk-node-template_7e710ada
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/test/vtex-connector.test.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n// import * as cdk from 'aws-cdk-lib';\n// import { Template } from 'aws-cdk-lib/assertions';\n// import * as VtexConnector from '../lib/vtex-connector-stack';\n\n// example test. To run these tests, uncomment this file along with the\n// example resource in lib/vtex-connector-stack.ts\ntest('SQS Queue Created', () => {\n// const app = new cdk.App();\n// // WHEN\n// const stack = new VtexConnector.VtexConnectorStack(app, 'MyTestStack');\n// // THEN\n// const template = Template.fromStack(stack);\n\n// template.hasResourceProperties('AWS::SQS::Queue', {\n// VisibilityTimeout: 300\n// });\n});\n\n```" } ]
code_payment-connector-aws-cdk-node-template_9541313d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/bin/vtex-connector.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n#!/usr/bin/env node\nimport 'source-map-support/register';\nimport * as cdk from 'aws-cdk-lib';\nimport { VtexConnectorStack } from '../lib/vtex-connector-stack';\n\nconst app = new cdk.App();\nnew VtexConnectorStack(app, 'VtexConnectorStack', {\n /* If you don't specify 'env', this stack will be environment-agnostic.\n * Account/Region-dependent features and context lookups will not work,\n * but a single synthesized template can be deployed anywhere. */\n\n /* Uncomment the next line to specialize this stack for the AWS Account\n * and Region that are implied by the current CLI configuration. */\n // env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },\n\n /* Uncomment the next line if you know exactly what Account and Region you\n * want to deploy the stack to. */\n // env: { account: '123456789012', region: 'us-east-1' },\n\n /* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */\n});\n```" } ]
code_payment-connector-aws-cdk-node-template_87a91847
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/lib/vtex-frontend-stack.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as cdk from \"aws-cdk-lib\";\nimport * as s3 from \"aws-cdk-lib/aws-s3\";\nimport * as s3deploy from \"aws-cdk-lib/aws-s3-deployment\";\nimport * as cloudFront from \"aws-cdk-lib/aws-cloudfront\";\nimport path = require(\"path\");\n\nexport const configureFrontend = (scope: any) => {\n ///////////// FRONTEND\n // Add S3 Bucket\n const s3Site = new s3.Bucket(scope, `FrontEndHackathonVTEX`, {\n bucketName: `${scope.account}-vtexday-hackathon`,\n removalPolicy: cdk.RemovalPolicy.DESTROY,\n autoDeleteObjects: true,\n websiteIndexDocument: \"index.html\",\n websiteErrorDocument: \"index.html\",\n });\n\n\n // Create Origin Access Identity and have s3 grant read access\n const oai = new cloudFront.OriginAccessIdentity(\n scope,\n `frontend-hackathon-vtex-origin-access-id`,\n {}\n );\n s3Site.grantRead(oai);\n\n // Create a new CloudFront Distribution\n const distribution = new cloudFront.CloudFrontWebDistribution(\n scope,\n `myreactapp-cf-distribution`,\n {\n originConfigs: [\n {\n s3OriginSource: {\n s3BucketSource: s3Site,\n originAccessIdentity: oai,\n },\n behaviors: [\n {\n isDefaultBehavior: true,\n compress: true,\n allowedMethods: cloudFront.CloudFrontAllowedMethods.ALL,\n cachedMethods:\n cloudFront.CloudFrontAllowedCachedMethods.GET_HEAD_OPTIONS,\n forwardedValues: {\n queryString: true,\n cookies: {\n forward: \"none\",\n },\n headers: [\n \"Access-Control-Request-Headers\",\n \"Access-Control-Request-Method\",\n \"Origin\",\n ],\n },\n },\n ],\n },\n ],\n comment: `myreactapp - CloudFront Distribution`,\n viewerProtocolPolicy: cloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,\n }\n );\n\n // Setup Bucket Deployment to automatically deploy new assets and invalidate cache\n new s3deploy.BucketDeployment(\n scope,\n `frontend-hackathon-vtex-s3bucketdeployment`,\n {\n sources: [s3deploy.Source.asset(path.join(__dirname, \"../src/frontend/build\"))],\n destinationBucket: s3Site,\n distribution: distribution,\n distributionPaths: [\"/*\"],\n }\n );\n\n // Final CloudFront URL\n new cdk.CfnOutput(scope, \"CloudFront URL\", {\n value: distribution.distributionDomainName,\n });\n\n const enableCorsOnBucket = (bucket: s3.IBucket) => {\n const cfnBucket = bucket.node.findChild(\"Resource\") as s3.CfnBucket;\n cfnBucket.addPropertyOverride(\"CorsConfiguration\", {\n CorsRules: [\n {\n AllowedOrigins: [\"*\"],\n AllowedMethods: [\"HEAD\", \"GET\", \"PUT\", \"POST\", \"DELETE\"],\n ExposedHeaders: [\n \"x-amz-server-side-encryption\",\n \"x-amz-request-id\",\n \"x-amz-id-2\"\n ],\n AllowedHeaders: [\"*\"]\n }\n ]\n });\n };\n enableCorsOnBucket(s3Site);\n};\n\n```" } ]
code_payment-connector-aws-cdk-node-template_6ca2ee8e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/lib/vtex-backend-stack.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Duration } from 'aws-cdk-lib';\nimport { LambdaIntegration, RestApi, Cors } from 'aws-cdk-lib/aws-apigateway';\nimport { Runtime } from 'aws-cdk-lib/aws-lambda';\nimport { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';\nimport * as path from 'path';\nimport * as DynamoDB from \"aws-cdk-lib/aws-dynamodb\";\nimport * as cdk from \"aws-cdk-lib\";\nimport * as sqs from \"aws-cdk-lib/aws-sqs\";\nimport { DynamoEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';\nimport { StartingPosition } from 'aws-cdk-lib/aws-lambda';\nimport { FilterCriteria, FilterRule } from 'aws-cdk-lib/aws-lambda';\nimport { SqsEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';\n\nexport const configureBackend = (scope: any) => {\n const AcquirerAPI = \"testing-12345/v2\"\n\n /////// DynamoDB \n\n // Create a DynamoDB table called PaymentTrackTable\n const PaymentTrackTable = new DynamoDB.Table(scope, \"PaymentTrackTable\", {\n partitionKey: {\n name: \"paymentId\",\n type: DynamoDB.AttributeType.STRING,\n },\n tableName: \"PaymentTrackTable\",\n billingMode: DynamoDB.BillingMode.PAY_PER_REQUEST,\n stream: DynamoDB.StreamViewType.NEW_IMAGE,\n removalPolicy: cdk.RemovalPolicy.DESTROY,\n });\n\n /////// QUEUE\n\n // create an SQS queue called PendingPaymentQueue\n const PendingPaymentQueue = new sqs.Queue(scope, \"PendingPaymentQueue\", {\n queueName: \"PendingPaymentQueue\",\n visibilityTimeout: cdk.Duration.seconds(30),\n receiveMessageWaitTime: cdk.Duration.seconds(10),\n retentionPeriod: cdk.Duration.days(1),\n encryption: sqs.QueueEncryption.SQS_MANAGED,\n });\n\n /////// API GATEWAY\n\n // Create an API Gateway using Lambda Proxy\n const PaymentApi = new RestApi(scope, \"PaymentApi\", {\n restApiName: \"PaymentApi\",\n description: \"PaymentApi\",\n deployOptions: {\n stageName: \"Prod\",\n },\n defaultCorsPreflightOptions: {\n allowOrigins: Cors.ALL_ORIGINS,\n allowMethods: Cors.ALL_METHODS\n }\n });\n\n /////// LAMBDAS\n\n // Create UserPost Lambda function\n const UserApi = new NodejsFunction(scope, \"User\", {\n memorySize: 128,\n timeout: Duration.seconds(5),\n runtime: Runtime.NODEJS_16_X,\n handler: 'handler',\n entry: path.join(__dirname, \"/../src/backend-front/User/handler.ts\"),\n bundling: {\n minify: true\n },\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName\n },\n });\n\n // create Lambda Proxy Integration and resource, and add integration to api resource\n const UserApiLambdaIntegration = new LambdaIntegration(UserApi);\n const UserApiResource = PaymentApi.root.addResource(\"user\");\n UserApiResource.addMethod(\"POST\", UserApiLambdaIntegration);\n\n // Create PendingPaymentStream Lambda function\n const PendingPaymentStream = new NodejsFunction(scope, \"PendingPaymentStream\", {\n memorySize: 128,\n timeout: Duration.seconds(5),\n runtime: Runtime.NODEJS_16_X,\n handler: 'handler',\n entry: path.join(__dirname, \"/../src/backend-connector/PendingPaymentStream/handler.ts\"),\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName,\n PENDING_PAYMENT_QUEUE: PendingPaymentQueue.queueName,\n },\n });\n\n PendingPaymentStream.addEventSource(new DynamoEventSource(PaymentTrackTable, {\n startingPosition: StartingPosition.TRIM_HORIZON,\n batchSize: 1,\n retryAttempts: 10,\n filters: [\n FilterCriteria.filter({\n eventName: FilterRule.isEqual(\"INSERT\"),\n dynamodb: {\n NewImage: { status: { S: FilterRule.isEqual(\"undefined\") } }\n }\n }),\n FilterCriteria.filter({\n eventName: FilterRule.isEqual(\"MODIFY\"),\n dynamodb: {\n NewImage: { status: { S: FilterRule.isEqual(\"undefined\") } }\n }\n })\n ]\n }));\n\n // Create ProcessPendingPayment Lambda function\n const ProcessPendingPayment = new NodejsFunction(scope, \"ProcessPendingPayment\", {\n memorySize: 128,\n timeout: Duration.seconds(5),\n runtime: Runtime.NODEJS_16_X,\n handler: 'handler',\n entry: path.join(__dirname, \"/../src/backend-connector/ProcessPendingPayment/handler.ts\"),\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName,\n PENDING_PAYMENT_QUEUE: PendingPaymentQueue.queueName,\n },\n });\n\n // Add SQS Event Source to Lambda Function\n ProcessPendingPayment.addEventSource(\n new SqsEventSource(PendingPaymentQueue, {\n batchSize: 1,\n enabled: true,\n reportBatchItemFailures: true,\n // retryAttempts: 10,\n // maxConcurrency: 2,\n })\n );\n\n // Create Manifest Lambda function\n const Manifest = new NodejsFunction(scope, \"Manifest\", {\n memorySize: 128,\n timeout: Duration.seconds(5),\n runtime: Runtime.NODEJS_16_X,\n handler: 'handler',\n entry: path.join(__dirname, \"/../src/backend-connector/Manifest/handler.ts\"),\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName\n },\n });\n\n // create Lambda Proxy Integration and resource, and add integration to api resource\n const ManifestLambdaIntegration = new LambdaIntegration(Manifest);\n const ManifestResource = PaymentApi.root.addResource(\"manifest\");\n ManifestResource.addMethod(\"GET\", ManifestLambdaIntegration);\n\n // Create Payment Lambda function\n const Payment = new NodejsFunction(scope, \"Payment\", {\n memorySize: 128,\n timeout: Duration.seconds(5),\n runtime: Runtime.NODEJS_16_X,\n handler: 'handler',\n entry: path.join(__dirname, \"/../src/backend-connector/Payment/handler.ts\"),\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName\n },\n });\n\n // create Lambda Proxy Integration and resource, and add integration to api resource\n const PaymentLambdaIntegration = new LambdaIntegration(Payment);\n const PaymentResource = PaymentApi.root.addResource(\"payments\");\n PaymentResource.addMethod(\"POST\", PaymentLambdaIntegration);\n PaymentTrackTable.grantReadWriteData(Payment);\n\n // Create Cancellation Lambda function\n const Cancellation = new NodejsFunction(scope, \"Cancellation\", {\n memorySize: 128,\n timeout: Duration.seconds(5),\n runtime: Runtime.NODEJS_16_X,\n handler: 'handler',\n entry: path.join(__dirname, \"/../src/backend-connector/Cancellation/handler.ts\"),\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName\n },\n });\n\n // create Lambda Proxy Integration and resource, and add integration to api resource\n const CancellationLambdaIntegration = new LambdaIntegration(Cancellation);\n const PaymentResourceWithId = PaymentResource.addResource(\"{paymentId}\");\n const CancellationResource = PaymentResourceWithId.addResource(\"cancellations\");\n CancellationResource.addMethod(\"POST\", CancellationLambdaIntegration);\n PaymentTrackTable.grantReadWriteData(Cancellation);\n\n // Create Settlement Lambda function\n const Settlement = new NodejsFunction(scope, \"Settlement\", {\n memorySize: 128,\n timeout: Duration.seconds(5),\n runtime: Runtime.NODEJS_16_X,\n handler: 'handler',\n entry: path.join(__dirname, \"/../src/backend-connector/Settlement/handler.ts\"),\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName\n },\n });\n\n // create Lambda Proxy Integration and resource, and add integration to api resource\n const SettlementLambdaIntegration = new LambdaIntegration(Settlement);\n const SettlementResource = PaymentResourceWithId.addResource(\"settlements\");\n SettlementResource.addMethod(\"POST\", SettlementLambdaIntegration);\n PaymentTrackTable.grantReadWriteData(Settlement);\n\n // Create Refund Lambda function\n const Refund = new NodejsFunction(scope, \"Refund\", {\n memorySize: 128,\n timeout: Duration.seconds(5),\n runtime: Runtime.NODEJS_16_X,\n handler: 'handler',\n entry: path.join(__dirname, \"/../src/backend-connector/Refund/handler.ts\"),\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName\n },\n });\n\n // create Lambda Proxy Integration and resource, and add integration to api resource\n const RefundLambdaIntegration = new LambdaIntegration(Refund);\n const RefundResource = PaymentResourceWithId.addResource(\"refunds\");\n RefundResource.addMethod(\"POST\", RefundLambdaIntegration);\n PaymentTrackTable.grantReadWriteData(Refund);\n\n\n /////// PERMISSIONS\n\n //Provide access to Lambdas on PaymentTrackTable\n PaymentTrackTable.grantReadWriteData(Payment);\n PaymentTrackTable.grantReadWriteData(PendingPaymentStream);\n PaymentTrackTable.grantReadWriteData(ProcessPendingPayment);\n PaymentTrackTable.grantStreamRead(PendingPaymentStream);\n\n //Provide access to PendingPaymentStream on\n PendingPaymentQueue.grantSendMessages(PendingPaymentStream);\n PendingPaymentQueue.grantConsumeMessages(ProcessPendingPayment);\n}\n```" } ]
code_payment-connector-aws-cdk-node-template_a9551387
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/lib/vtex-connector-stack.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as cdk from 'aws-cdk-lib';\nimport { Construct } from 'constructs';\nimport { configureBackend } from './vtex-backend-stack';\nimport { configureFrontend } from './vtex-frontend-stack';\n\nexport class VtexConnectorStack extends cdk.Stack {\n constructor(scope: Construct, id: string, props?: cdk.StackProps) {\n super(scope, id, props);\n\n configureFrontend(this);\n configureBackend(this);\n\n }\n}\n\n```" } ]
code_payment-connector-aws-cdk-node-template_6b6c79de
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/src/backend-connector/typings.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n// from https://www.npmjs.com/package/@vtex/payment-provider\nimport type { IncomingHttpHeaders } from 'http2'\nimport type { ParsedUrlQuery } from 'querystring'\n\nfunction contains<T>(value: T, list: T[]) {\n return list.indexOf(value) !== -1\n}\n\nfunction Enum(...args: string[]) {\n return args.reduce((acc, cur) => {\n acc[cur] = cur\n return acc\n }, Object.create(null))\n}\n\n\nexport type Maybe<T> = T | undefined\nexport const RecipientRole = Enum('marketplace', 'seller')\nexport type RecipientRole = typeof RecipientRole\n\nexport const DocumentType = Enum('CNPJ', 'CPF', 'SSN')\nexport type DocumentType = typeof DocumentType\n\nexport interface AuthenticationHeaders extends IncomingHttpHeaders {\n 'x-provider-api-appkey': string\n 'x-provider-api-apptoken': string\n}\n\nexport interface Recipient {\n id: string\n name: string\n documentType: DocumentType\n document: string\n role: RecipientRole\n chargeProcessingFee: boolean\n chargebackLiable: boolean\n amount: number\n}\n\nexport interface Card {\n number: string\n holder: string\n expiration: Expiration\n csc: string\n document: unknown\n}\n\nexport interface TokenizedCard {\n holderToken: string\n bin: string\n numberToken: string\n numberLength: number\n cscToken: string\n expiration: Expiration\n}\n\nexport interface Expiration {\n month: string\n year: string\n}\n\nexport interface MiniCart {\n buyer: Buyer\n shippingAddress: Maybe<Address>\n billingAddress: Maybe<Address>\n items: Maybe<Item[]>\n shippingValue: Maybe<number>\n taxValue: Maybe<number>\n}\n\nexport interface Buyer {\n id: Maybe<string>\n firstName: string\n lastName: string\n document: string\n documentType: Maybe<string>\n corporateName: Maybe<string>\n tradeName: Maybe<string>\n corporateDocument: Maybe<string>\n isCorporate: Maybe<boolean>\n email: Maybe<string>\n phone: Maybe<string>\n createdDate: Maybe<Date>\n}\n\nexport interface Address {\n country: Maybe<string>\n street: Maybe<string>\n number: Maybe<string>\n complement: Maybe<string>\n neighborhood: Maybe<string>\n postalCode: Maybe<string>\n city: Maybe<string>\n state: Maybe<string>\n}\n\nexport interface Item {\n id: Maybe<string>\n name: Maybe<string>\n price: Maybe<number>\n quantity: Maybe<number>\n discount: Maybe<number>\n deliveryType: Maybe<string>\n sellerId: Maybe<string>\n categoryId: Maybe<string>\n}\n\nexport interface SecureProxyTokensResponse{\n tokens: SecureProxyTokens[]\n}\n\ninterface SecureProxyTokens{\n name: String\n placeholder: String\n}\n\nexport interface AppData {\n appName: Maybe<string>\n payload: Maybe<string>\n}\n\nexport interface PaymentIdParam extends ParsedUrlQuery {\n paymentId: string\n}\n\nexport const DebitCard = Enum('Visa Electron', 'Maestro', 'Mastercard Debit')\nexport type DebitCard = typeof DebitCard\n\nexport const CreditCard = Enum(\n 'Visa',\n 'Mastercard',\n 'American Express',\n 'Discover',\n 'JCB',\n 'Diners',\n 'Elo',\n 'Hipercard',\n 'Aura',\n 'Benricompras',\n 'Credz',\n 'Cabal',\n 'Cartes Bancaires (CB)'\n)\nexport type CreditCard = typeof CreditCard\n\nexport const DirectSale = Enum('Venda Direta Credito', 'Venda Direta Debito')\nexport type DirectSale = typeof DirectSale\n\nexport const AdhocCard = Enum('Cobranded', 'Privatelabels')\nexport type AdhocCard = typeof AdhocCard\n\nexport const BankInvoice = Enum('BankInvoice')\nexport type BankInvoice = typeof BankInvoice\n\nexport const Generic = Enum('Promissories', 'Cash')\nexport type Generic = typeof Generic\n\nexport const Voucher = Enum('SPEI', 'Safetypay')\nexport type Voucher = typeof Voucher\n\nexport const Cryptocurrency = Enum('Bitcoin')\nexport type Cryptocurrency = typeof Cryptocurrency\n\nexport type PaymentMethod =\n | CreditCard\n | DebitCard\n | AdhocCard\n | Generic\n | BankInvoice\n | Voucher\n | Cryptocurrency\n | DirectSale\n\nexport interface AvailablePaymentsResponse {\n paymentMethods: PaymentMethod[]\n}\n\nexport type AllowSplitOptions = 'onAuthorize' | 'onCapture' | 'disabled'\nexport interface PaymentMethodInfo {\n name: PaymentMethod\n allowsSplit: AllowSplitOptions\n}\n\nexport type CustomFieldTypeOptions = 'text' | 'select'\nexport type SelectTypeOptions = 'type' | 'value'\nexport interface CustomSelectFields {\n text: string\n value: string\n}\nexport interface CustomFieldOptions {\n name: string\n type: CustomFieldTypeOptions\n options?: CustomSelectFields[]\n}\n\nexport interface ProviderManifestResponse {\n paymentMethods: PaymentMethodInfo[]\n customFields?: CustomFieldOptions[]\n}\n\nexport interface CancellationRequest extends PaymentRequest {\n authorizationId: string\n tid: Maybe<string>\n}\n\nexport interface CancellationResponse extends PaymentResponse {\n cancellationId: Maybe<string> | null\n code: Maybe<string> | null | 'cancel-manually'\n message: Maybe<string> | null\n}\n\nexport interface CustomField {\n name: string\n value: string\n}\n\nexport interface PaymentRequest {\n transactionId: string\n paymentId: string\n requestId: string\n merchantSettings: Maybe<CustomField[]>\n}\n\nexport interface Authorization extends PaymentRequest {\n reference: string\n orderId: string\n paymentMethod: PaymentMethod\n paymentMethodCustomCode: Maybe<string>\n merchantName: string\n value: number\n currency: string\n installments: Maybe<number>\n installmentsInterestRate: Maybe<number>\n installmentsValue: Maybe<number>\n deviceFingerprint: Maybe<string>\n ipAddress: Maybe<string>\n miniCart: MiniCart\n url: Maybe<string>\n callbackUrl: string\n inboundRequestsUrl: string\n returnUrl: Maybe<string>\n recipients: Maybe<Recipient[]>\n}\n\nexport interface CardAuthorization extends Authorization {\n secureProxyTokensUrl: Maybe<string>\n secureProxyUrl: Maybe<string>\n card: Card | TokenizedCard\n paymentMethod: CreditCard | DebitCard | AdhocCard\n}\n\nexport interface CreditCardAuthorization extends CardAuthorization {\n paymentMethod: CreditCard\n}\nexport interface DebitCardAuthorization extends CardAuthorization {\n paymentMethod: DebitCard\n}\nexport interface AdhocCardAuthorization extends CardAuthorization {\n paymentMethod: AdhocCard\n}\n\nexport interface DirectSaleAuthorization extends Authorization {\n paymentMethod: DirectSale\n}\n\nexport interface BankInvoiceAuthorization extends Authorization {\n paymentMethod: BankInvoice\n}\n\nexport type AuthorizationRequest =\n | CreditCardAuthorization\n | DebitCardAuthorization\n | AdhocCardAuthorization\n | BankInvoiceAuthorization\n | DirectSaleAuthorization\n | Authorization\n\nexport const isCardAuthorization = (\n authorization: AuthorizationRequest\n): authorization is CardAuthorization =>\n typeof (authorization as CardAuthorization).card !== 'undefined'\n\nexport const isCreditCardAuthorization = (\n authorization: AuthorizationRequest\n): authorization is CreditCardAuthorization =>\n contains(authorization.paymentMethod, Object.values(CreditCard))\n\nexport const isDebitCardAuthorization = (\n authorization: AuthorizationRequest\n): authorization is DebitCardAuthorization =>\n contains(authorization.paymentMethod, Object.values(DebitCard))\n\nexport const isBankInvoiceAuthorization = (\n authorization: AuthorizationRequest\n): authorization is BankInvoiceAuthorization =>\n authorization.paymentMethod === 'BankInvoice'\n\nexport const isDirectSaleAuthorization = (\n authorization: AuthorizationRequest\n): authorization is DirectSaleAuthorization =>\n contains(authorization.paymentMethod, Object.values(DirectSale))\n\nexport const isTokenizedCard = (\n card: Card | TokenizedCard\n): card is TokenizedCard =>\n typeof (card as TokenizedCard).numberToken !== 'undefined'\n\nexport type AuthorizationStatus = 'approved' | 'denied' | 'undefined'\n\nexport interface PaymentResponse {\n paymentId: string\n code: Maybe<string> | null\n message: Maybe<string> | null\n}\n\nexport interface AuthorizationBase extends PaymentResponse {\n status: AuthorizationStatus\n tid: Maybe<string> | null\n acquirer: Maybe<string> | null\n authorizationId?: Maybe<string> | null\n delayToCancel?: Maybe<number> | null\n delayToAutoSettle?: Maybe<number> | null\n delayToAutoSettleAfterAntifraud?: Maybe<number> | null\n}\n\nexport interface ApprovedAuthorization extends AuthorizationBase {\n tid: string\n authorizationId: string\n nsu?: Maybe<string>\n}\n\nexport interface CreditCardAuthorized extends ApprovedAuthorization {\n delayToAutoSettle: Maybe<number>\n delayToAutoSettleAfterAntifraud: Maybe<number>\n}\n\nexport interface BankInvoiceResponse extends PaymentResponse {\n paymentUrl: string\n identificationNumber: Maybe<string>\n identificationNumberFormatted: Maybe<string>\n barCodeImageType: Maybe<string>\n barCodeImageNumber: Maybe<string>\n delayToCancel: Maybe<number>\n}\n\nexport type BankInvoiceAuthorized = BankInvoiceResponse & ApprovedAuthorization\n\nexport type BankInvoicePending = PendingAuthorization & BankInvoiceResponse\n\nexport interface FailedAuthorization extends AuthorizationBase {\n status: 'denied'\n}\n\nexport interface PendingAuthorization extends AuthorizationBase {\n status: 'undefined'\n delayToCancel: number\n authorizationId: Maybe<string> | null\n paymentAppData: Maybe<AppData> | null\n paymentUrl: Maybe<string> | null\n}\n\nexport type AuthorizationResponse =\n | ApprovedAuthorization\n | CreditCardAuthorized\n | BankInvoiceAuthorized\n | FailedAuthorization\n | PendingAuthorization\n | RedirectResponse\n\nexport interface SettlementRequest extends PaymentRequest {\n value: number\n authorizationId: string\n tid: Maybe<string>\n recipients: Maybe<Recipient[]>\n}\n\nexport interface SettlementResponse extends PaymentResponse {\n settleId: Maybe<string> | null\n value: number\n requestId: string\n}\n\nexport interface RefundRequest extends PaymentRequest {\n value: number\n settleId: string\n tid: Maybe<string>\n recipients: Maybe<Recipient[]>\n}\n\nexport interface RefundResponse extends PaymentResponse {\n requestId: string\n refundId: Maybe<string> | null\n value: number\n code: Maybe<string> | null | 'refund-manually'\n}\n\nexport interface InboundRequest extends PaymentRequest {\n authorizationId: string\n tid: string\n requestData: { body: string }\n}\n\nexport interface InboundResponse extends PaymentResponse {\n responseData: {\n statusCode: number\n contentType: string\n content: string\n }\n requestId: string\n}\n\nexport interface RedirectResponse extends PendingAuthorization {\n redirectUrl: Maybe<string> | null\n}\n\n```" } ]
code_payment-connector-aws-cdk-node-template_2dc9b5ed
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/src/backend-connector/Cancellation/handler.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda';\n\ninterface CancellationEvent extends APIGatewayProxyEventV2 {\n pathParameters: {\n paymentId: string;\n }\n}\n\nexport const handler = async (event: CancellationEvent): Promise<APIGatewayProxyResultV2> => {\n\n const { paymentId } = event.pathParameters;\n\n const cancellationResponse = {\n message: 'add here the cancellation response object!',\n }\n\n return {\n body: JSON.stringify(cancellationResponse),\n statusCode: 200,\n };\n};\n```" } ]
code_payment-connector-aws-cdk-node-template_d312917b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/src/backend-connector/Settlement/handler.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda';\n\ninterface SettlementEvent extends APIGatewayProxyEventV2 {\n pathParameters: {\n paymentId: string;\n }\n}\n\nexport const handler = async (event: SettlementEvent): Promise<APIGatewayProxyResultV2> => {\n\n const { paymentId } = event.pathParameters;\n\n const settlementResponse = {\n message: 'add here the settlement response object!',\n }\n\n return {\n body: JSON.stringify(settlementResponse),\n statusCode: 200,\n };\n};\n```" } ]
code_payment-connector-aws-cdk-node-template_58d96425
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/src/backend-connector/ProcessPendingPayment/handler.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { SQSEvent, SQSHandler } from 'aws-lambda';\nimport { SQS } from 'aws-sdk';\nimport * as AWS from 'aws-sdk';\n\nconst sqs = new AWS.SQS();\n\n// Process Pending Payment\n// Lambda triggered by new item in SQS. \n// Responsible for processing pending payment with adquirencies.\nexport const handler: SQSHandler = async (event: SQSEvent) => {\n\n // Ex 1\n // Read SQS message from event\n const body = JSON.parse(event.Records[0].body);\n\n // Ex 2\n // Delete Message from Queue\n //const sqs = new AWS.SQS();\n //const deleteParams: SQS.DeleteMessageBatchRequest = {\n // Entries: [\n // {\n // Id: event.Records[0].messageId,\n // ReceiptHandle: event.Records[0].receiptHandle,\n // },\n // ],\n // QueueUrl: process.env.PENDING_PAYMENT_QUEUE || '',\n //};\n //\n //try {\n // await sqs.deleteMessageBatch(deleteParams).promise();\n // console.log('Message deleted from queue');\n //} catch (error) {\n // console.error('Error deleting message from queue:', error);\n //}\n\n};\n\n\n```" } ]
code_payment-connector-aws-cdk-node-template_b999b57c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/src/backend-connector/Payment/handler.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda';\nimport AWS from 'aws-sdk';\nimport axios from 'axios';\nimport { AuthorizationRequest, PaymentResponse } from '../typings';\n\nconst TABLE_NAME = process.env.TABLE_NAME;\nconst ddbResource = new AWS.DynamoDB.DocumentClient();\n\n// PaymentPOST\n// Lambda called by API Gateway.\n// Responsible for receiving new transactions from VTEX Gateway\nexport const handler = async (event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> => {\n\n // Ex 1\n // Example of how to get body from POST\n if(event.body) {\n console.log(event.body);\n } else {\n throw new Error('No body found');\n }\n\n const requestBody = JSON.parse(event.body) as AuthorizationRequest;\n\n const itemDict = {\n 'paymentId': requestBody['paymentId'],\n 'paymentMethod': requestBody['paymentMethod'],\n 'currency': requestBody['currency'],\n 'returnUrl': requestBody['returnUrl'],\n 'status': 'undefined'\n };\n\n /// Ex 2\n // How to write data in Dynamodb\n const dynamoResponse = await ddbResource\n .put({\n TableName: TABLE_NAME,\n Item: itemDict,\n ReturnValues: 'NONE',\n ReturnConsumedCapacity: 'TOTAL',\n ConditionExpression: 'attribute_not_exists(paymentId)'\n })\n .promise();\n\n const authorizationResponse = {\n message: 'add here the authorization response object!',\n }\n\n return {\n body: JSON.stringify(authorizationResponse),\n statusCode: 200,\n };\n};\n```" } ]
code_payment-connector-aws-cdk-node-template_d35af20c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/src/backend-connector/Manifest/handler.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n\nimport { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda';\n\nexport const handler = async (event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> => {\n const manifest = {\n \"paymentMethods\": [],\n \"customFields\":[]\n }\n\n return {\n body: JSON.stringify(manifest),\n statusCode: 200,\n headers: {\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'\n },\n };\n};\n```" } ]
code_payment-connector-aws-cdk-node-template_2c0e342f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/src/backend-connector/PendingPaymentStream/handler.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { DynamoDBStreamEvent, DynamoDBStreamHandler } from 'aws-lambda';\nimport AWS from 'aws-sdk';\n\nconst sqs = new AWS.SQS();\n\n// Pending Payment Stream\n// Lambda triggered by DynamoDB stream (INSERT and MODIFY). \n// Responsible for retrieving new records from DynamoDB streams and writing on SQS\nexport const handler: DynamoDBStreamHandler = async (event: DynamoDBStreamEvent) => {\n console.log(event);\n\n // Ex 1 \n // Read DynamoDB stream events\n for (const record of event.Records) {\n // Get the DynamoDB stream record\n const dynamodbRecord = record.dynamodb;\n // Get the new image\n if (!dynamodbRecord) {\n continue;\n }\n const newImage = dynamodbRecord.NewImage;\n\n const itemDict = {\n 'paymentId': newImage?.paymentId.S || '',\n 'paymentMethod': newImage?.paymentMethod.S || '',\n 'currency': newImage?.currency.S || '',\n 'returnUrl': newImage?.returnUrl.S || '',\n 'status': newImage?.status.S || ''\n };\n\n // Ex 2\n // How to get Queue and Write item to SQS queue\n const queueUrl = await sqs.getQueueUrl({ QueueName: process.env.PENDING_PAYMENT_QUEUE || '' }).promise();\n const response = await sqs\n .sendMessage({\n QueueUrl: queueUrl.QueueUrl,\n MessageBody: JSON.stringify(itemDict)\n })\n .promise();\n\n console.log(response);\n console.log('Message sent to SQS queue');\n }\n};\n\n```" } ]
code_payment-connector-aws-cdk-node-template_3bca1e40
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/src/backend-connector/Refund/handler.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda';\n\ninterface RefundEvent extends APIGatewayProxyEventV2 {\n pathParameters: {\n paymentId: string;\n }\n}\n\nexport const handler = async (event: RefundEvent): Promise<APIGatewayProxyResultV2> => {\n\n const { paymentId } = event.pathParameters;\n\n const refundResponse = {\n message: 'add here the refund response object!',\n }\n\n return {\n body: JSON.stringify(refundResponse),\n statusCode: 200,\n };\n};\n```" } ]
code_payment-connector-aws-cdk-node-template_f4d44882
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-node-template/src/backend-front/User/handler.ts from the payment-connector-aws-cdk-node-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda';\n\n/* User\nLambda called by API Gateway.\nResponsible for registering new users in VTEX and acquirers\n */\nexport const handler = async (event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> => {\n\n return {\n body: JSON.stringify('Hello from Lambda!'),\n statusCode: 200,\n // THIS HEADER PART is mandatory for CORS to work\n headers: {\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'POST'\n },\n };\n};\n```" } ]
code_tax-protocol-example_c5b3485c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/docs/README.md from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n\n\n# Tax Protocol Example\n\nA reference app implementing a VTEX IO Tax Protocol service.\n\n## Uses\nThis app is an example to be followed in order to develop a tax service integration with VTEX. \n\n## Clients\nIn this example, there are a few clients implemented for you to use.\n- `Catalog`: can be used to retrieve information regarding produts, in case of needing more data besides those that come on the tax payload\n- `Checkout`: used to configure the tax service in the Checkout\n- `Logistics`: it has a single method that can be used to fetch information about docks.\n- `TaxProvider`: used to connect with the provider's external API.\n- `VtexCommerce`: basic external client that can be used as the class that can be inherited to develop other clients that connectes to VTEX API. \n\n## Parsers\nAs a way to simplify the logic behind the handlers that are implemented in this example, all the code logic that can be necessary to parse the payloads to a specific format is expected to be implemented inside `parsers` directory. This is necessary because both the external provider API and VTEX API expect specific payload formats. Inside the folder, there are two files, `providerToVtex.ts` and `vtexToProvider.ts`.\n\n### VTEX to Provider\nThe provider API will receive a HTTP post request with a well-defined body from the checkout. In case of it expecting a different format, one can implement the loginc inside `vtexToProvider` function. \n\nAn example of the body sent in the checkout post request is:\n```json\n{\n \"orderFormId\": \"e5098ad8c4jk490bb2f6f03400ac1413\",\n \"salesChannel\": \"1\",\n \"items\": [\n {\n \"id\": \"0\",\n \"sku\": \"26\",\n \"ean\": \"12345678909123\",\n \"refId\": null,\n \"unitMultiplier\": 1,\n \"measurementUnit\": \"un\",\n \"targetPrice\": 8.2,\n \"itemPrice\": 8.2,\n \"quantity\": 1,\n \"discountPrice\": 0,\n \"dockId\": \"1125a08\",\n \"freightPrice\": 0,\n \"brandId\": \"2000002\"\n }\n ],\n \"totals\": [\n {\n \"id\": \"Items\",\n \"name\": \"Items Total\",\n \"value\": 820\n },\n {\n \"id\": \"Discounts\",\n \"name\": \"Discounts Total\",\n \"value\": 0\n },\n {\n \"id\": \"Shipping\",\n \"name\": \"Shipping Total\",\n \"value\": 0\n },\n {\n \"id\": \"Tax\",\n \"name\": \"Tax Total\",\n \"value\": 0\n }\n ],\n \"clientEmail\": \"client@email.com\",\n \"shippingDestination\": {\n \"country\": \"BRA\",\n \"state\": \"RJ\",\n \"city\": \"Rio de Janeiro\",\n \"neighborhood\": \"Botafogo\",\n \"postalCode\": \"22250-905\",\n \"street\": \"Praia Botafogo\"\n },\n \"clientData\": {\n \"email\": \"client@email.com\",\n \"document\": \"12345678909\",\n \"corporateDocument\": null,\n \"stateInscription\": null\n },\n \"paymentData\": {\n \"payments\": [\n {\n \"paymentSystem\": \"2\",\n \"bin\": null,\n \"referenceValue\": 820,\n \"value\": 820,\n \"installments\": null\n }\n ]\n }\n}\n```\n\n### Provider to VTEX\nConsidering the request done by the provider to the VTEX Checkout API, it's also possible to implement a parser in order to put the payload in the format that the checkout expects. One can find an example of the expected format:\n\n```json\n{\n \"itemTaxResponse\": [\n\t\t\t{\n\t\t \"id\": \"0\",\n\t\t \"taxes\": [\n\t\t {\n\t\t \"name\": \"TAX 1\",\n\t\t \"description\": \"\",\n\t\t \"value\": 3.48\n\t\t },\n\t\t {\n\t\t \"name\": \"TAX 2\",\n\t\t \"description\": \"\",\n\t\t \"value\": 22\n\t\t }\n\t\t ]\n\t\t }\n\t\t],\n \"hooks\": [\n {\n \"major\": 1,\n \"url\": \"https://master--bufferin.myvtex.com/app/tax-provider/oms/invoice\"\n }\n ]\n}\n```\n\n## GraphQL queries and mutations\nBoth have resolvers that can be tested on GraphiQL. They use the `Checkout` client in order to do POST or GET HTTP requests regarding the Order Form Configuration.\n\n### `getTaxConfiguration` query\nResponsible to fetch information regarding the Tax Configuration of an account, its resolver makes a GET request to `Checkout` and get the Order Form configuration.\n\n### `setTaxConfiguration` mutation\nIt expects a parameter, which can be `activate` or `deactivate` and it does a POST HTTP request to set the Tax Configuration on the Order Form Configuration. In order to do so, it uses a `Checkout` client. \n\nHaving it ready is useful for those integration that need a admin panel to configure the tax service, since it's possible to use React Hooks in order to call the mutation.\n\n## Using GraphiQL to configure the tax service on an account\n\nIn order to test the integration, it's necessary configure the integration on desired account. In order to do so, you can use the GraphiQL route that is available when linking the application to write the necessary mutation.\n\nBelow you can find a mutation example that can be used to configure the tax integration. It's been written and executed on the GraphiQL route that is available when linking the app.\n\n```graphql\nmutation setConfiguration ($operation: String) {\n setTaxConfiguration(operation: $operation) {\n taxConfiguration {\n allowExecutionAfterErrors\n authorizationHeader\n integratedAuthentication\n url\n }\n }\n}\n```\n> Note: `$operation` is a query variable that is configured on the GraphiQL, the GraphQL IDE.\n\nYou can find an image of GraphiQL below:\n\n![image](https://user-images.githubusercontent.com/19495917/89305970-a9ea1800-d645-11ea-9131-cab6efd34cf8.png)\n\n\n## Routes\nThere are two main routes in this example and they are mainly using mocked values so as to simulate their functions.\n\nIt is important to emphasize that for the first two endpoints to work, you **must** have the tax service configured in your account, which can be done by using GraphiQL, as it was explained in the previous step.\n\n- `taxSimulation`: responsible for simulating a Checkout request for tax calculation.\n- `orderInvoice`: public route to send the taxes.\n\n## Testing the example app\n\nAfter having the integration properly configured, you can test those routes using this [Postman collection](https://www.getpostman.com/collections/3b2ee13b0cbba50e0809).\n\n> **Attention!** The authorization header that it's present in the Postman collection is a mocked value to be correctly validated by the handlers. This value is defined in the `utils/constants.ts` file and it's used to configure the tax service when calling the `settings` endpoint.\n\n\n**Upcoming documentation:**\n\n - [Fixing problem with dependency](https://github.com/vtex-apps/tax-protocol-example/pull/9)\n```" } ]
code_tax-protocol-example_878daec4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/graphql/schema.graphql from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Query {\n getTaxConfiguration: TaxConfiguration\n}\n\ntype Mutation {\n setTaxConfiguration(operation: String): OrderFormConfiguration\n}\n\ntype OrderFormConfiguration {\n paymentConfiguration: PaymentConfiguration\n taxConfiguration: TaxConfiguration\n minimumQuantityAccumulatedForItems: Int\n decimalDigitsPrecision: Int\n minimumValueAccumulated: Int\n apps: [App]\n allowMultipleDeliveries: Boolean\n allowManualPrice: Boolean\n maxIntOfWhiteLabelSellers: Int\n maskFirstPurchaseData: Boolean\n recaptchaValidation: Boolean\n}\n\ntype PaymentConfiguration {\n requiresAuthenticationForPreAuthorizedPaymentOption: Boolean\n allowInstallmentsMerge: Boolean\n blockPaymentSession: Boolean\n paymentSystemToCheckFirstInstallment: Boolean\n}\n\ntype TaxConfiguration {\n allowExecutionAfterErrors: Boolean\n authorizationHeader: String\n integratedAuthentication: Boolean\n url: String\n}\n\ntype App {\n fields: [String]\n id: [String]\n major: Int\n}\n\n```" } ]
code_tax-protocol-example_16adfe3e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/service.json from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 512,\n \"ttl\": 43200,\n \"timeout\": 300,\n \"routes\": {\n \"taxSimulation\": {\n \"path\": \"/app/tax-provider/checkout/simulation\",\n \"public\": true\n },\n \"orderInvoice\": {\n \"path\": \"/app/tax-provider/oms/invoice\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_tax-protocol-example_191ec686
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/package.json from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.0.0\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.0.0\",\n \"@vtex/api\": \"6.36.0\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"tslint\": \"^5.14.0\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typescript\": \"3.8.3\"\n },\n \"resolutions\": {\n \"**/**/acorn\": \"^6.4.1\",\n \"**/**/minimist\": \"^0.2.1\",\n \"**/**/kind-of\": \"^6.0.3\",\n \"**/**/handlebars\": \"^4.3.0\",\n \"**/**/js-yaml\": \"^3.13.1\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'\"\n },\n \"version\": \"1.0.3\"\n}\n\n```" } ]
code_tax-protocol-example_86614c60
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/index.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n ClientsConfig,\n ParamsContext,\n RecorderState,\n Service,\n ServiceContext,\n} from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { orderInvoice } from './handlers/orderInvoice'\nimport { taxSimulation } from './handlers/taxSimulation'\nimport { validateCheckoutAuthorization } from './handlers/validateCheckoutAuthorization'\nimport { getTaxConfiguration } from './resolvers/getTaxConfiguration'\nimport { setTaxConfiguration } from './resolvers/setTaxConfiguration'\n\nconst TIMEOUT_MS = 800\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// It's possible to check the implementation of each handler in the handlers folder\nexport default new Service<Clients, RecorderState, ParamsContext>({\n clients,\n graphql: {\n resolvers: {\n Mutation: {\n setTaxConfiguration,\n },\n Query: {\n getTaxConfiguration,\n },\n },\n },\n routes: {\n orderInvoice: [orderInvoice],\n taxSimulation: [validateCheckoutAuthorization, taxSimulation],\n },\n})\n\n```" } ]
code_tax-protocol-example_1a82b8b4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/clients/taxProvider.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\n\nexport class TaxProvider extends ExternalClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n // The first argument is the base URl of your provider API endpoint\n super('baseURL', ctx, options)\n }\n\n public getTaxInformation(_: unknown) {\n /*\n This is the method that will be used to connect to the provider API\n and get the taxes values to be parsed later on in the orderTax handler.\n For instance, it's returning a mocked object that it's already in the format\n that VTEX expects when it's a sync request.\n It receives the request in the format that the provider expects. Replace the\n unknown with the typing of your provider\n */\n return [\n {\n id: '0',\n taxes: [\n {\n name: 'TAX 1',\n value: 100,\n },\n ],\n },\n ]\n }\n}\n\n```" } ]
code_tax-protocol-example_2c5d7acb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/clients/vtexCommerce.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\n\nexport default class VtexCommerce extends ExternalClient {\n constructor(ctx: IOContext, baseRoute: string, options?: InstanceOptions) {\n super(`http://api.vtex.com/api/${baseRoute}`, ctx, {\n ...options,\n headers: {\n VtexIdclientAutCookie: ctx.authToken,\n ...options?.headers,\n },\n params: {\n an: ctx.account,\n ...options?.params,\n },\n })\n }\n}\n\n```" } ]
code_tax-protocol-example_94306de5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/clients/checkout.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { InstanceOptions, IOContext, RequestTracingConfig } from '@vtex/api'\n\nimport { createTracing } from '../utils/tracing'\nimport VtexCommerce from './vtexCommerce'\n\nconst CHECKOUT_ENDPOINT = 'pvt/configuration/orderForm'\n\nexport class Checkout extends VtexCommerce {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, 'checkout', {\n ...options,\n headers: {\n ...(ctx.adminUserAuthToken\n ? {\n VtexIdclientAutCookie: ctx.adminUserAuthToken,\n }\n : {}),\n },\n })\n }\n\n public getOrderFormConfiguration(tracingConfig?: RequestTracingConfig) {\n const metric = 'checkout-getOrderForm'\n return this.http.get<OrderFormConfiguration>(CHECKOUT_ENDPOINT, {\n metric,\n tracing: createTracing(metric, tracingConfig),\n })\n }\n\n public setOrderFormConfiguration(\n body: OrderFormConfiguration,\n userToken: string,\n tracingConfig?: RequestTracingConfig\n ) {\n const metric = 'checkout-setOrderForm'\n return this.http.post(CHECKOUT_ENDPOINT, body, {\n headers: {\n VtexIdclientAutCookie: userToken,\n },\n metric,\n tracing: createTracing(metric, tracingConfig),\n })\n }\n}\n\n```" } ]
code_tax-protocol-example_38e45da6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/clients/logistics.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { InstanceOptions, IOContext, RequestTracingConfig } from '@vtex/api'\n\nimport { createTracing } from '../utils/tracing'\nimport VtexCommerce from './vtexCommerce'\n\nconst routes = {\n docks: (dockId: string) => `pvt/configuration/docks/${dockId}`,\n}\n\nexport class Logistics extends VtexCommerce {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, 'logistics', {\n ...options,\n headers: {\n ...(ctx.adminUserAuthToken\n ? {\n VtexIdclientAutCookie: ctx.adminUserAuthToken,\n }\n : {}),\n },\n })\n }\n\n public getDockById(dockId: string, tracingConfig?: RequestTracingConfig) {\n const metric = 'logistics-getDockById'\n return this.http.get(routes.docks(dockId), {\n metric,\n tracing: createTracing(metric, tracingConfig),\n })\n }\n}\n\n```" } ]
code_tax-protocol-example_cf2d7ca4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/clients/index.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport { Catalog } from './catalog'\nimport { Checkout } from './checkout'\nimport { Logistics } from './logistics'\nimport { TaxProvider } from './taxProvider'\n\nexport class Clients extends IOClients {\n public get checkout() {\n return this.getOrSet('checkout', Checkout)\n }\n\n public get logistics() {\n return this.getOrSet('logistics', Logistics)\n }\n\n public get catalog() {\n return this.getOrSet('catalog', Catalog)\n }\n\n public get taxProvider() {\n return this.getOrSet('taxProvider', TaxProvider)\n }\n}\n\n```" } ]
code_tax-protocol-example_fa39f4fd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/clients/catalog.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { InstanceOptions, IOContext, RequestTracingConfig } from '@vtex/api'\n\nimport { createTracing } from '../utils/tracing'\nimport VtexCommerce from './vtexCommerce'\n\nconst catalogRouteEndpoint = (skuId: string) => `/pvt/stockkeepingunit/${skuId}`\n\nexport class Catalog extends VtexCommerce {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, 'catalog', {\n ...options,\n headers: {\n ...(ctx.authToken\n ? {\n VtexIdclientAutCookie: ctx.authToken,\n }\n : {}),\n },\n })\n }\n\n public getSkuById(skuId: string, tracingConfig?: RequestTracingConfig) {\n const metric = 'catalog-getSkuMetric'\n return this.http.get<OrderFormConfiguration>(catalogRouteEndpoint(skuId), {\n metric,\n tracing: createTracing(metric, tracingConfig),\n })\n }\n}\n\n```" } ]
code_tax-protocol-example_c8717149
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/parsers/vtexToProvider.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const parseVtexToProvider = (checkoutRequest: CheckoutRequest) => {\n // Parse here the checkout request to the expected format\n return checkoutRequest\n}\n\n```" } ]
code_tax-protocol-example_d905db37
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/parsers/providerToVtex.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const parseProviderToVtex = (\n providerResponse: unknown // replace unknown with the typing of your provider\n): TaxResponse => {\n // Parse here your response to the expected format\n return providerResponse as TaxResponse\n}\n\n```" } ]
code_tax-protocol-example_2351df6d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/typings/orderForm.d.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface OrderFormConfiguration {\n paymentConfiguration: PaymentConfiguration\n taxConfiguration: TaxConfiguration | null\n minimumQuantityAccumulatedForItems: number\n decimalDigitsPrecision: number\n minimumValueAccumulated: number\n apps: App[]\n allowMultipleDeliveries: boolean\n allowManualPrice: boolean\n maxNumberOfWhiteLabelSellers: number\n maskFirstPurchaseData: boolean\n recaptchaValidation: boolean\n}\n\ninterface PaymentConfiguration {\n requiresAuthenticationForPreAuthorizedPaymentOption: boolean\n allowInstallmentsMerge: boolean\n blockPaymentSession: boolean\n paymentSystemToCheckFirstInstallment: boolean\n}\n\ninterface TaxConfiguration {\n allowExecutionAfterErrors: boolean\n authorizationHeader: string\n integratedAuthentication: boolean\n url: string | null\n}\n\ninterface App {\n fields: string[]\n id: string\n major: number\n}\n\n```" } ]
code_tax-protocol-example_6bc9843d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/typings/checkoutRequest.d.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface CheckoutRequest {\n orderFormId: string\n salesChannel: string\n items: Item[]\n clientEmail: string\n clientData: Client\n shippingDestination: ShippingInformation\n totals: Total[]\n paymentData: Payment[]\n}\n\ninterface Item {\n id: string\n sku: string\n ean: string\n refId: string | null\n unitMultiplier: number\n measurementUnit: string\n targetPrice: number\n itemPrice: number\n quantity: number\n discountPrice: number | null\n dockId: string\n freightPrice: number\n brandId: string\n}\n\ninterface Client {\n email: string\n document: string\n corporateDocument: string | null\n stateInscription: string | null\n}\n\ninterface Total {\n id: string\n name: string\n value: number\n}\n\ninterface Payment {\n paumentSystem: string\n bin: string | null\n referenceValue: number\n value: number\n installments: number | null\n}\n\ninterface ShippingInformation {\n country: string\n state: string\n city: string\n neighborhood: string\n street: string\n postalCode: string\n}\n\n```" } ]
code_tax-protocol-example_550f1ee3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/typings/taxes.d.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface TaxResponse {\n itemTaxResponse: ItemTaxResponse[]\n hooks: Hook[]\n}\n\ninterface ItemTaxResponse {\n id: string\n taxes: Tax[]\n}\n\ninterface Tax {\n name: string\n value: number\n}\n\ninterface Hook {\n major: number\n url: string\n}\n\n```" } ]
code_tax-protocol-example_fb67c905
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/utils/producstInformation.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const getInfoBySku = async (ctx: Context, body: CheckoutRequest) => {\n const {\n clients: { catalog },\n } = ctx\n\n /*\n Function that uses Catalog client to retrieve SKU information by its ID.\n It can be used in cases of needing more information about the products, such\n as dimensions, weight and etc.\n */\n\n return Promise.all(body.items.map(({ sku }) => catalog.getSkuById(sku)))\n}\n\n```" } ]
code_tax-protocol-example_427950a9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/utils/settings.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\n\nimport { Checkout } from '../clients/checkout'\nimport { AUTHORIZATION_CODE } from './constants'\n/**\n * This method does a POST request to the checkout API\n * so as to activate the tax configuration on a specific\n * account\n */\n// eslint-disable-next-line max-params\nexport async function activateProvider(\n orderForm: OrderFormConfiguration,\n checkout: Checkout,\n account: string,\n workspace: string,\n userToken: string\n) {\n if (orderForm.taxConfiguration) {\n throw new UserInputError('Tax provider already configured')\n }\n\n const body = {\n ...orderForm,\n taxConfiguration: {\n allowExecutionAfterErrors: false,\n authorizationHeader: AUTHORIZATION_CODE,\n integratedAuthentication: false,\n url: `https://${workspace}--${account}.myvtex.com/app/tax-provider/checkout/simulation`,\n },\n }\n await checkout.setOrderFormConfiguration(body, userToken)\n\n return body\n}\n\nexport async function deactivateProvider(\n orderForm: OrderFormConfiguration,\n checkout: Checkout,\n userToken: string\n) {\n if (!orderForm.taxConfiguration) {\n throw new UserInputError('Tax provider is not configured')\n }\n\n const body = {\n ...orderForm,\n taxConfiguration: {\n allowExecutionAfterErrors: false,\n authorizationHeader: AUTHORIZATION_CODE,\n integratedAuthentication: false,\n url: null,\n },\n }\n await checkout.setOrderFormConfiguration(body, userToken)\n\n return body\n}\n\n```" } ]
code_tax-protocol-example_0cabe530
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/utils/constants.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n// This is an uuid that is necessary for the checkout API\nconst AUTHORIZATION_CODE = 'YOUR_AUTHORIZATION_CODE'\n\nconst PROVIDER_NAME = 'YOUR_PROVIDER_NAME'\n\nexport { AUTHORIZATION_CODE, PROVIDER_NAME }\n\n```" } ]
code_tax-protocol-example_898f6436
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/utils/tracing.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { RequestTracingConfig } from '@vtex/api'\n\nexport const createTracing = (\n metric: string,\n tracingConfig?: RequestTracingConfig\n) => ({\n requestSpanNameSuffix: metric,\n ...tracingConfig?.tracing,\n})\n\n```" } ]
code_tax-protocol-example_94c38a16
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/resolvers/getTaxConfiguration.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError } from '@vtex/api'\n\nexport async function getTaxConfiguration(\n _: unknown,\n __: unknown,\n ctx: Context\n) {\n /*\n This resolver is responsible for getting the Tax Configuration from the\n Order Form configuration and it can be use to check how it's configured.\n It uses GraphQL and the query can be made by GraphiQL, a route that is\n exposed when linking the app.\n */\n\n const {\n clients: { checkout },\n vtex: { adminUserAuthToken: userToken },\n } = ctx\n\n if (!userToken) {\n throw new AuthenticationError('No authorization provided')\n }\n\n const { taxConfiguration } = await checkout.getOrderFormConfiguration()\n\n return taxConfiguration\n}\n\n```" } ]
code_tax-protocol-example_632c5db9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/resolvers/setTaxConfiguration.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError, UserInputError } from '@vtex/api'\n\nimport { activateProvider, deactivateProvider } from '../utils/settings'\n\nexport async function setTaxConfiguration(\n _: unknown,\n { operation }: SettingsInput,\n ctx: Context\n) {\n /*\n This resolver is responsible for activating or deactivating the\n tax service on the order form configuration by using GraphQL\n */\n\n const {\n clients: { checkout },\n vtex: { account, adminUserAuthToken: userToken, workspace },\n } = ctx\n\n if (!userToken) {\n throw new AuthenticationError('No authorization provided')\n }\n\n const orderForm = await checkout.getOrderFormConfiguration()\n\n if (operation === 'activate') {\n return activateProvider(orderForm, checkout, account, workspace, userToken)\n }\n if (operation === 'deactivate') {\n return deactivateProvider(orderForm, checkout, userToken)\n }\n throw new UserInputError(\n \"operation must be either 'activate' or 'deactivate'\"\n )\n}\n\ninterface SettingsInput {\n operation: string\n}\n\n```" } ]
code_tax-protocol-example_3047b8e6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/handlers/validateCheckoutAuthorization.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ForbiddenError } from '@vtex/api'\n\nimport { AUTHORIZATION_CODE } from '../utils/constants'\n\nexport async function validateCheckoutAuthorization(\n ctx: Context,\n next: () => Promise<any>\n) {\n const {\n headers: { authorization },\n } = ctx\n\n if (!authorization || authorization !== AUTHORIZATION_CODE) {\n throw new ForbiddenError('Authorization token does not match')\n }\n\n await next()\n}\n\n```" } ]
code_tax-protocol-example_227e3bfd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/handlers/taxSimulation.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nimport { parseProviderToVtex } from '../parsers/providerToVtex'\nimport { parseVtexToProvider } from '../parsers/vtexToProvider'\n// import { getInfoBySku } from '../utils/producstInformation'\n\n/*\nThis handler is responsible for receiving the request from the checkout,\nwhich has an specific format; this request is going to be parsed to have\nthe format that is expected on the provider side. After that, it will call\nthe method that uses the provider API. It will give a response with the\ntaxes information. With that, it's necessary to parse it again to the\nformat that VTEX expects and this will be assigned to the body\n*/\nexport async function taxSimulation(\n ctx: Context,\n next: () => Promise<unknown>\n) {\n const body: CheckoutRequest = await json(ctx.req)\n\n const {\n vtex: { workspace, account },\n clients: { taxProvider },\n } = ctx\n\n // Example of using Catalog Client to retrieve SKU information by ID\n // const productItems = await getInfoBySku(ctx, body)\n\n const orderInformation = parseVtexToProvider(body)\n\n // Client that will retrieve the tax information from the provider's API\n const payload = taxProvider.getTaxInformation(orderInformation)\n\n // Parsing the tax information that was retrieved to the correct format\n const expectedResponse = parseProviderToVtex(payload)\n\n // Mounting the response body\n ctx.body = {\n hooks: [\n {\n major: 1,\n url: `https://${workspace}--${account}.myvtex.com/app/tax-provider/oms/invoice`,\n },\n ],\n itemTaxResponse: expectedResponse,\n }\n\n // Necessary so the Checkout can understand body's format\n ctx.set('Content-Type', 'application/vnd.vtex.checkout.minicart.v1+json')\n\n await next()\n}\n\n```" } ]
code_tax-protocol-example_6c8c0c84
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of tax-protocol-example/node/handlers/orderInvoice.ts from the tax-protocol-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nexport async function orderInvoice(ctx: Context, next: () => Promise<any>) {\n // This is where the order taxes are committed\n\n const body: OrderStatus = await json(ctx.req)\n\n const { status } = body\n\n if (status === 'invoiced') {\n /*\n This is where one can implement a logic that depends\n on the order having its status changed to invoiced.\n */\n }\n\n ctx.status = 200\n ctx.body = { message: 'Order taxes were commited' }\n\n await next()\n}\n\ninterface OrderStatus {\n orderId: string\n status: string\n}\n\n```" } ]
code_geolocation-graphql-interface_8f0d8ad4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of geolocation-graphql-interface/docs/README.md from the geolocation-graphql-interface VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Geolocation GraphQL Interface\n\n⚠️ **This is an ongoing, unsupported, unfinished and undocumented project. We do not guarantee any results after installation.** ⚠️\n\nThis app exports a GraphQL schema for geolocation results for Place Components.\n\n## Usage\n\n### Installation\n\nTo use it in your app, run the `vtex add vtex.geolocation-graphql-interface` command.\n\nYou may then use it in your front end component queries, for example, by writing the file `addressSuggestions.graphql`:\n\n```graphql\nquery AddressSuggestions($searchTerm: String!) {\n addressSuggestions(searchTerm: $searchTerm)\n @context(provider: \"vtex.geolocation-graphql-interface\") {\n description\n mainText\n mainTextMatchInterval {\n offset\n length\n }\n secondaryText\n externalId\n }\n}\n```\n\n> 9\u000f\u000f The only difference from a standard query is the usage of a _directive_: `@context(provider: \"vtex.geolocation-graphql-interface\")`\n\nTo resolve this query, you must have installed in your workspace an app that implements the GraphQL interface. Currently, those are the available resolvers:\n\n- [vtex.google-geolocation-resolver](https://github.com/vtex-apps/google-geolocation-resolver)\n\nHaving zero or more than one resolver installed will result in an error.\n\n### Examples\n\nCurrently, this interface only supports autosuggest related operations, which is commonly used along with a text-based input like the [Location Search component](https://github.com/vtex-apps/place-components/#locationfield-search) used in `vtex.place-components`. In order to get the suggestions, each key-stroke might send a `addressSuggestions` query like:\n\n```graphql\nquery {\n addressSuggestions(searchTerm: \"Praia de bot\") {\n description\n externalId\n }\n}\n```\n\nThis returns address suggestions using the resolver of your choice. Notice that the number of suggestions are handled by the resolver itself.\n\n```graphql\n{\n \"data\": {\n \"addressSuggestions\": [\n {\n \"description\": \"Praia de Botafogo - Botafogo, Rio de Janeiro - RJ, Brasil\",\n \"externalId\": \"SAMPLE_ID_2718\"\n },\n {\n \"description\": \"Praia de Botafogo - Pista Direita - Botafogo, Rio de Janeiro - RJ, Brasil\",\n \"externalId\": \"SAMPLE_ID_0042\"\n },\n {\n \"description\": \"Alameda Praia de Botafogo - Patamares, Salvador - BA, Brasil\",\n \"externalId\": \"SAMPLE_ID_1123\"\n },\n {\n \"description\": \"Acesso Praia de Botafogo - Botafogo, Rio de Janeiro - RJ, Brasil\",\n \"externalId\": \"SAMPLE_ID_1001\"\n },\n {\n \"description\": \"Rua Praia de Botafogo - Vilatur, Saquarema - RJ, Brasil\",\n \"externalId\": \"SAMPLE_ID_8888\"\n }\n ]\n }\n}\n```\n\nIf the user selects the first suggested address, we must use it's `externalId` to make an `address` query:\n\n```graphql\nquery {\n address(id: \"SAMPLE_ID_2718\") {\n city\n neighborhood\n street\n }\n}\n```\n\nWhich returns an address object that can be used to autocomplete an address form.\n\n```graphql\n{\n \"data\": {\n \"address\": {\n \"city\": \"Rio de Janeiro\",\n \"neighborhood\": \"Botafogo\",\n \"street\": \"Praia de Botafogo\"\n }\n }\n}\n```\n\n\n**Upcoming documentation:**\n\n - [CHK-435: Session token](https://github.com/vtex-apps/geolocation-graphql-interface/pull/6)\n\n```" } ]
code_geolocation-graphql-interface_a1b8df51
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of geolocation-graphql-interface/graphql/schema.graphql from the geolocation-graphql-interface VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Query {\n addressSuggestions(\n searchTerm: String!\n sessionToken: String\n \"\"\"\n A two character, case insensitive, ISO 3166-1 Alpha-2 or Alpha-3 compatible country code, used to restrict the suggestion results\n \"\"\"\n country: String\n ): [AddressSuggestion!]!\n\n address(externalId: String!, sessionToken: String): Address!\n\n providerLogo: Image!\n\n sessionToken: String!\n}\n\n```" } ]
code_geolocation-graphql-interface_664460a4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of geolocation-graphql-interface/graphql/types/Address.graphql from the geolocation-graphql-interface VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Address {\n addressId: ID\n addressType: AddressType\n city: String\n complement: String\n country: String\n geoCoordinates: [Float!]\n neighborhood: String\n number: String\n postalCode: String\n receiverName: String\n reference: String\n state: String\n street: String\n}\n\nenum AddressType {\n residential\n commercial\n inStore\n giftRegistry\n pickup\n search\n}\n\n```" } ]
code_geolocation-graphql-interface_1ab29c75
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of geolocation-graphql-interface/graphql/types/AddressSuggestion.graphql from the geolocation-graphql-interface VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype AddressSuggestion {\n description: String!\n mainText: String!\n mainTextMatchInterval: MatchInterval!\n secondaryText: String!\n externalId: String!\n}\n\ntype MatchInterval {\n offset: Int!\n length: Int!\n}\n\n```" } ]
code_checkout-resources_19c47f02
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/docs/README.md from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Checkout Resources\n\nCentralizes all GraphQL operations used in Checkout IO, as well as some utility functions.\n\n## Usage\n\n```ts\nimport OrderFormQuery from 'vtex.checkout-resources/QueryOrderForm'\nimport UpdateItemMutation from 'vtex.checkout-resources/MutationUpdateItem'\n\nconst MyComponent: React.FC = () => {\n const { data } = useQuery(OrderFormQuery)\n const [updateItem] = useMutation(UpdateItemMutation)\n // ...\n}\n```\n\n## Utility functions\n\n### useCheckoutURL()\n\nThis is a React Hook that provides the URL to the Checkout Cart, which varies depending on the version of `vtex.checkout` installed in the account.\n\nReturns an object with a `url` property containing the path to the cart (`/checkout/#/cart` or `/cart`, for instance).\n\n#### Example usage\n\n```tsx\nimport { useCheckoutURL } from 'vtex.checkout-resources/Utils'\n\nconst MyComponent: FunctionComponent = () => {\n const { url } = useCheckoutURL()\n \n return <a href={url}>Go to cart</a>\n}\n```\n\n\n**Upcoming documentation:**\n\n - [Update saveCards mutation](https://github.com/vtex-apps/checkout-resources/pull/26)\n - [Update version of gateway-graphql](https://github.com/vtex-apps/checkout-resources/pull/29)\n```" } ]
code_checkout-resources_96d7a791
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/MutationSaveCards.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport saveCards from './mutations/saveCards.graphql'\n\nexport default saveCards\n\n```" } ]
code_checkout-resources_a7ae75e6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/MutationSelectPickupOption.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport selectPickupOption from './mutations/selectPickupOption.graphql'\n\nexport default selectPickupOption\n\n```" } ]
code_checkout-resources_2abdd399
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/QueryGeolocationInstalled.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport geolocationInstalledQuery from './queries/geolocationInstalled.graphql'\n\nexport default geolocationInstalledQuery\n\n```" } ]
code_checkout-resources_b6aa21e1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/MutationSavePaymentToken.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport savePaymentToken from './mutations/savePaymentToken.graphql'\n\nexport default savePaymentToken\n\n```" } ]
code_checkout-resources_eb31201f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/MutationEstimateShipping.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport estimateShipping from './mutations/estimateShipping.graphql'\n\nexport default estimateShipping\n\n```" } ]
code_checkout-resources_62c4e045
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/Queries.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/** DEPRECATED, being kept just for retrocompatibility.\n * Create individual entry points for each query instead */\n\nimport orderForm from './queries/orderForm.graphql'\nimport cardSessionId from './queries/cardSessionId.graphql'\n\nexport default {\n orderForm,\n cardSessionId,\n}\n\n```" } ]
code_checkout-resources_5675220d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/MutationUpdateOrderFormPayment.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport updateOrderFormPaymentMutation from './mutations/updateOrderFormPayment.graphql'\n\nexport default updateOrderFormPaymentMutation\n```" } ]
code_checkout-resources_74160816
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/MutationUpdateItems.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport updateItems from './mutations/updateItems.graphql'\n\nexport default updateItems\n\n```" } ]
code_checkout-resources_dfa4d081
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/MutationClearOrderFormMessages.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport clearOrderFormMessages from './mutations/clearOrderFormMessages.graphql'\n\nexport default clearOrderFormMessages\n\n```" } ]
code_checkout-resources_e6e7dfd2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/MutationUpdateClientPreferencesData.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport updateClientPreferencesData from './mutations/updateClientPreferencesData.graphql'\n\nexport default updateClientPreferencesData\n\n```" } ]
code_checkout-resources_c20933ef
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/package.json from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.checkout-resources\",\n \"version\": \"0.50.1\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\",\n \"lint\": \"tsc --noEmit && eslint --ext ts,tsx .\"\n },\n \"dependencies\": {\n \"@vtex/css-handles\": \"^1.0.0\",\n \"classnames\": \"^2.2.6\",\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.8.3\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.8.3\",\n \"react-intl\": \"^2.7.2\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/classnames\": \"^2.2.7\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/prop-types\": \"^15.7.0\",\n \"@types/ramda\": \"^0.26.5\",\n \"@types/react\": \"^16.8.10\",\n \"@types/react-intl\": \"^2.3.17\",\n \"@vtex/test-tools\": \"^2.1.1\",\n \"apollo-client\": \"^2.5.1\",\n \"typescript\": \"3.9.7\",\n \"vtex.apps-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.apps-graphql@3.12.0/public/@types/vtex.apps-graphql\",\n \"vtex.checkout-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-graphql@0.60.0/public/@types/vtex.checkout-graphql\",\n \"vtex.checkout-resources\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-resources@0.45.0/public/@types/vtex.checkout-resources\",\n \"vtex.gateway-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.gateway-graphql@1.0.0/public/@types/vtex.gateway-graphql\",\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_checkout-resources_7964e3d6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-resources/react/MutationUpdateOrderFormProfile.tsx from the checkout-resources VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport updateOrderFormProfileMutation from './mutations/updateOrderFormProfile.graphql'\n\nexport default updateOrderFormProfileMutation\n\n```" } ]