id
stringlengths
12
53
messages
listlengths
3
3
code_flow-finance-payment_3f557209
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of flow-finance-payment/react/components/FlowFinanceModal.tsx from the flow-finance-payment VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { ModalDialog } from 'vtex.styleguide'\nimport '../theme.css'\n\ninterface FlowFinanceAuthenticationProps {\n appPayload: string\n}\n\ndeclare const vtex: any\ndeclare const $: any\n\nclass FlowFinanceModal extends Component<FlowFinanceAuthenticationProps> {\n public state = {\n pdfLoaded: false,\n modalOpen: true,\n }\n\n public componentDidMount() {\n vtex.checkout.MessageUtils.hidePaymentMessage()\n }\n\n public respondTransaction = async (status: boolean) => {\n const { callbackUrl, transactionId } = JSON.parse(this.props.appPayload)\n if (!status) {\n vtex.checkout.MessageUtils.showPaymentMessage()\n await fetch(\n `${callbackUrl}?tid=${transactionId}&message=Modal failed or was closed by user&status=denied`,\n {\n method: 'post',\n mode: 'no-cors',\n }\n )\n }\n $(window).trigger('transactionValidation.vtex', [status])\n }\n\n public handleConfirmation = async () => {\n vtex.checkout.MessageUtils.showPaymentMessage()\n this.setState({ modalOpen: false })\n const { inboundRequestsUrl, callbackUrl, accountId, loanId } = JSON.parse(\n this.props.appPayload\n )\n const inbound = inboundRequestsUrl.replace(':action', 'loanAcceptance')\n const userAgent = navigator.userAgent\n const data = {\n userAgent: userAgent,\n accountId: accountId,\n loanId: loanId,\n callbackUrl: callbackUrl,\n }\n await fetch(`${inbound}`, {\n method: 'post',\n mode: 'no-cors',\n body: JSON.stringify(data),\n })\n this.respondTransaction(true)\n }\n\n public render() {\n const { pdfUrl } = JSON.parse(this.props.appPayload)\n\n return (\n <ModalDialog\n centered\n closeOnOverlayClick={false}\n isOpen={this.state.modalOpen}\n title=\"Para continuar você precisa aceitar os termos do contrato de financiamento\"\n confirmation={\n this.state.pdfLoaded\n ? {\n onClick: this.handleConfirmation,\n label: 'Aceito',\n }\n : {\n onClick: () => {\n return false\n },\n label: 'Espere por favor',\n }\n }\n cancelation={{\n onClick: () => this.respondTransaction(false),\n label: 'Cancelar',\n }}\n onClose={() => this.respondTransaction(false)}\n >\n <div style={{ minWidth: '40vw' }}>\n <iframe\n title=\"Flow Finance Loan Agreement\"\n width=\"95%\"\n height={400}\n src={pdfUrl}\n data-testid=\"embedded-pdf\"\n className={`db center`}\n frameBorder=\"0\"\n onLoad={() => this.setState({ pdfLoaded: true })}\n />\n </div>\n </ModalDialog>\n )\n }\n}\n\nexport default FlowFinanceModal\n\n```" } ]
code_actionpay_06d06654
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of actionpay/docs/README.md from the actionpay VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Actionpay\n\nOpen the VTEX APP Store and install the app on your store.\n\nor\n\nRun the following command:\n\n```sh\nvtex install vtex.actionpay@0.x\n```\n\nNext, open the app settings on your admin and fill the form with your Actionpay settings.\n\n```" } ]
code_actionpay_5d971c5d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of actionpay/react/index.tsx from the actionpay VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { canUseDOM } from 'vtex.render-runtime'\nimport { PixelMessage, OrderPlacedData } from './typings/events'\n\nimport {\n getProductPrice,\n getQueryVariable,\n setActionpayCookie,\n createImageTags,\n} from './helpers'\n\nfunction handleMessages(event: PixelMessage) {\n const { actionpayPartnerId: partnerId = '', APRT_DATA = {} } = window\n\n if (!partnerId) return console.log('Actionpay Partner ID not set.')\n\n switch (event.data.eventName) {\n case 'vtex:pageInfo': {\n const { eventType, department, category } = event.data\n let eventData: any = {\n pageType: 1,\n }\n if (eventType === 'departmentView' || eventType === 'categoryView') {\n eventData = {\n ...eventData,\n pageType: 3,\n currentCategory: category || department,\n }\n }\n window.APRT_DATA = { ...APRT_DATA, ...eventData }\n addTrackingScript()\n break\n }\n case 'vtex:productView': {\n const {\n product,\n product: {\n productId: id,\n productName: name,\n categoryTree: [currentCategory],\n },\n } = event.data\n const price = getProductPrice(product)\n const currentProduct = {\n id,\n name,\n price,\n }\n const eventData = {\n pageType: 2,\n currentCategory,\n currentProduct,\n }\n window.APRT_DATA = { ...APRT_DATA, ...eventData }\n addTrackingScript()\n break\n }\n case 'vtex:orderPlaced': {\n const {\n transactionId,\n transactionProducts,\n transactionSubtotal,\n }: OrderPlacedData = event.data\n\n createImageTags(transactionId, transactionSubtotal)\n\n const purchasedProducts = transactionProducts.map(\n ({ id, name, price, quantity }) => ({\n id,\n name,\n price,\n quantity,\n })\n )\n\n const orderInfo = {\n id: transactionId,\n totalPrice: transactionSubtotal,\n }\n\n const eventData = {\n pageType: 6,\n orderInfo,\n purchasedProducts,\n }\n\n window.APRT_DATA = { ...APRT_DATA, ...eventData }\n addTrackingScript()\n break\n }\n default:\n break\n }\n}\n\nfunction addTrackingScript() {\n const { actionpayPartnerId: partnerId = '' } = window\n const script = document.createElement('script')\n script.type = 'text/javascript'\n script.async = script.defer = true\n script.src = `//aprtn.com/code/${partnerId}/`\n var parent =\n document.getElementsByTagName('body')[0] ||\n document.getElementsByTagName('head')[0]\n parent && parent.appendChild(script)\n}\n\nif (canUseDOM) {\n const sourcevar = getQueryVariable('utm_source')\n if (sourcevar && sourcevar === 'actionpay') {\n const actionpay = getQueryVariable('actionpay')\n actionpay && setActionpayCookie('Actionpay', actionpay)\n }\n sourcevar && setActionpayCookie('Origem', sourcevar)\n window.addEventListener('message', handleMessages)\n}\n\n```" } ]
code_actionpay_0738d4dc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of actionpay/react/package.json from the actionpay VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"author\": \"vtex\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"devDependencies\": {\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.7.2\",\n \"@vtex/test-tools\": \"^1.1.0\",\n \"eslint\": \"^5.15.1\",\n \"eslint-config-vtex\": \"^10.1.0\",\n \"eslint-config-vtex-react\": \"^4.1.0\",\n \"prettier\": \"^1.17.1\",\n \"typescript\": \"3.5.2\",\n \"vtex.pixel-interfaces\": \"http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.pixel-interfaces@1.1.0/public/_types/react\",\n \"vtex.render-runtime\": \"http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.render-runtime@8.50.0/public/_types/react\"\n },\n \"version\": \"0.1.3\"\n}\n\n```" } ]
code_actionpay_af09921d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of actionpay/store/interfaces.json from the actionpay VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"pixel.actionpay\": {\n \"component\": \"index\"\n }\n}\n\n```" } ]
code_actionpay_3251f2b3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of actionpay/react/typings/events.d.ts from the actionpay VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface PixelMessage extends MessageEvent {\n data:\n | PageInfo\n | ProductViewData\n | ProductClickData\n | OrderPlacedData\n | PageViewData\n | ProductImpressionData\n | AddToCartData\n | RemoveToCartData\n | CategoryViewData\n | DepartmentViewData\n}\n\nexport interface PageInfo extends EventData {\n event: 'pageInfo'\n eventName: 'vtex:pageInfo'\n}\n\nexport interface EventData {\n event: string\n eventName: string\n eventType: string\n currency: string\n}\n\nexport interface PageViewData extends EventData {\n event: 'pageView'\n eventName: 'vtex:pageView'\n pageTitle: string\n pageUrl: string\n referrer: string\n}\n\nexport interface AddToCartData extends EventData {\n event: 'addToCart'\n eventName: 'vtex:addToCart'\n items: CartItem[]\n}\n\nexport interface RemoveToCartData extends EventData {\n event: 'removeFromCart'\n eventName: 'vtex:removeFromCart'\n items: CartItem[]\n}\n\nexport interface OrderPlacedData extends Order, EventData {\n event: 'orderPlaced'\n eventName: 'vtex:orderPlaced'\n}\n\nexport interface ProductViewData extends EventData {\n event: 'productView'\n eventName: 'vtex:productView'\n product: Product\n}\n\nexport interface ProductClickData extends EventData {\n event: 'productClick'\n eventName: 'vtex:productClick'\n product: Product\n}\n\nexport interface ProductImpressionData extends EventData {\n event: 'productImpression'\n eventName: 'vtex:productImpression'\n impressions: Impression[]\n product?: Product // deprecated, use impressions list!\n position?: number // deprecated, use impressions list!\n list: string\n}\n\ninterface CartItem {\n skuId: string\n variant: string\n price: number\n name: string\n quantity: number\n productRefId: string\n brand: string\n category: string\n}\n\nexport interface Order {\n currency: string\n accountName: string\n orderGroup: string\n salesChannel: string\n coupon: string\n visitorType: string\n visitorContactInfo: string[]\n visitorAddressState: string\n visitorAddressCountry: string\n visitorAddressPostalCode: string\n transactionId: string\n transactionDate: string\n transactionAffiliation: string\n transactionTotal: number\n transactionShipping: number\n transactionSubtotal: number\n transactionDiscounts: number\n transactionTax: number\n transactionCurrency: string\n transactionPaymentType: PaymentType[]\n transactionShippingMethod: ShippingMethod[]\n transactionProducts: ProductOrder[]\n transactionPayment: {\n id: string\n }\n}\n\nexport interface Impression {\n product: Product\n position: number\n}\n\ninterface PaymentType {\n group: string\n paymentSystemName: string\n installments: number\n value: number\n}\n\ninterface ShippingMethod {\n itemId: string\n selectedSla: string\n}\n\ninterface ProductOrder {\n id: string\n name: string\n sku: string\n skuRefId: string\n skuName: string\n productRefId: string\n ean: string\n slug: string\n brand: string\n brandId: string\n seller: string\n sellerId: string\n category: string\n categoryId: string\n categoryTree: string[]\n categoryIdTree: string[]\n priceTags: PriceTag[]\n originalPrice: number\n price: number\n sellingPrice: number\n tax: number\n quantity: number\n components: any[]\n measurementUnit: string\n unitMultiplier: number\n}\n\ninterface PriceTag {\n identifier: string\n isPercentual: boolean\n value: number\n}\n\ninterface Product {\n brand: string\n categoryId?: string // inconsistency\n categories: string[]\n productId: string\n productName: string\n selectedSku?: string // inconsistency\n items: Item[]\n sku: Item\n [key: string]: any\n}\n\ninterface Item {\n itemId: string\n name: string\n seller?: Seller\n [key: string]: any\n}\n\ninterface Seller {\n commertialOffer: CommertialOffer\n [key: string]: any\n}\n\ninterface CommertialOffer {\n Price: number\n [key: string]: any\n}\n\n```" } ]
code_actionpay_60d61d5b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of actionpay/react/typings/vtex.render-runtime.d.ts from the actionpay VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime' {\n export const canUseDOM: boolean\n}\n\n```" } ]
code_actionpay_7c4668a1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of actionpay/react/typings/global.d.ts from the actionpay VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Window extends Window {\n actionpayPartnerId: string\n actionpayDomain: string\n actionpayPostclick: number\n actionpayCampaignId: string\n APRT_DATA: any\n}\n\n```" } ]
code_actionpay_8fb1c604
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of actionpay/react/__tests__/helpers.ts from the actionpay VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n getQueryVariable,\n getProductPrice,\n setActionpayCookie,\n getCookieByName,\n} from '../helpers'\n\nimport { Product } from '../typings/events'\n\ndescribe('getQueryVariable', () => {\n test('it should return null if no url', () => {\n window.history.pushState({}, 'Test', '/test')\n expect(getQueryVariable('foo')).toBeNull()\n })\n test('it should return the query string value ', () => {\n window.history.pushState({}, 'Test', '/test?foo=bar')\n expect(getQueryVariable('foo')).toBe('bar')\n window.history.pushState({}, 'Test', '/test?foo=bar&baz=fizz')\n expect(getQueryVariable('baz')).toBe('fizz')\n })\n test('it will return null if not found value', () => {\n window.history.pushState(\n {},\n 'Test',\n '/checkout/orderPlaced/?og=957261794487'\n )\n expect(getQueryVariable('foo')).toBeNull()\n })\n})\n\ndescribe('getProductPrice', () => {\n test('it should return null if no price', () => {\n const product: Product = {\n productId: '',\n productName: '',\n brand: '',\n categories: [''],\n sku: {\n itemId: '',\n name: '',\n },\n items: [\n {\n itemId: '',\n name: '',\n sellers: [\n {\n commertialOffer: {},\n },\n ],\n },\n ],\n }\n expect(getProductPrice(product)).toBeNull()\n })\n test('it should return the product price', () => {\n const product: Product = {\n productId: '',\n productName: '',\n brand: '',\n categories: [''],\n sku: {\n itemId: '',\n name: '',\n },\n items: [\n {\n itemId: '',\n name: '',\n sellers: [\n {\n commertialOffer: {\n Price: 199,\n },\n },\n ],\n },\n ],\n }\n expect(getProductPrice(product)).toBe(199)\n })\n})\n\ndescribe('getCookieByName', () => {\n test('it returns null if no cookie found', () => {\n document.cookie = 'foo=bar'\n expect(getCookieByName('bar')).toBeNull()\n })\n test('it gets a cookie value that has a certain name', () => {\n document.cookie = 'foo=bar'\n expect(getCookieByName('foo')).toBe('bar')\n })\n})\n\ndescribe('setActionpayCookie', () => {\n test('it sets a cookie with a value', () => {\n setActionpayCookie('foo', 'bar')\n expect(getCookieByName('foo')).toBe('bar')\n })\n})\n\n```" } ]
code_actionpay_461903c4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of actionpay/react/helpers/index.tsx from the actionpay VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { Product } from '../typings/events'\n\nexport function getQueryVariable(key: string) {\n const {\n location: { search },\n } = window\n if (!search) return null\n const query = search.substring(1)\n const vars = query.split('&')\n const [{ value = null } = {}] = vars\n .map(item => {\n const [name, value] = item.split('=')\n return { name, value }\n })\n .filter(({ name }) => name === key)\n return value\n}\n\nexport function getProductPrice(product: Product) {\n const {\n items: [\n {\n sellers: [\n {\n commertialOffer: { Price: price = null },\n },\n ],\n },\n ],\n } = product\n return price\n}\n\nexport function getCookieByName(cookieName: string): string | null {\n const [{ value = null } = {}] = document.cookie\n .split('; ')\n .map(cookie => {\n const [name, value] = cookie.split('=')\n return { name, value }\n })\n .filter(cookie => cookie)\n .filter(({ name }) => cookieName === name)\n return value\n}\n\nexport function getUrls(transactionId: string, transactionSubtotal: number) {\n const { actionpayCampaignId: campaignId } = window\n const actionpayCookie = getCookieByName('Actionpay')\n return [\n `//apretailer.com.br/ok/${campaignId}.png?actionpay=${actionpayCookie}&apid=${transactionId}&price=${transactionSubtotal}`\n ]\n}\n\nexport function createImageTags(\n transactionId: string,\n transactionSubtotal: number\n): void {\n getUrls(transactionId, transactionSubtotal).map(url => {\n const img = document.createElement('img')\n img.setAttribute('src', url)\n img.setAttribute('height', '0')\n img.setAttribute('width', '0')\n document.body.appendChild(img)\n })\n}\n\nexport function setActionpayCookie(name: string, value: any): void {\n const {\n actionpayPostclick: daysExpire,\n location: { host: domain },\n } = window\n const date = new Date()\n date.setTime(date.getTime() + daysExpire * 24 * 60 * 60 * 1000)\n var expires = `expires=${date.toUTCString()}`\n document.cookie = `${name}=${value}; path=/;${expires}; domain=${domain}`\n}\n\n```" } ]
code_add-to-cart-validation_93ba2cec
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/messages/pt.json from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"editor.countdown.title\": \"Contagem regressiva\",\n \"editor.countdown.description\": \"Componente de contagem regressiva\"\n}\n\n```" } ]
code_add-to-cart-validation_55c2bcd2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/messages/en.json from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"editor.countdown.title\": \"Countdown\",\n \"editor.countdown.description\": \"Countdown component\"\n}\n```" } ]
code_add-to-cart-validation_4ace464a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/messages/context.json from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"editor.countdown.title\": \"Countdown\",\n \"editor.countdown.description\": \"Countdown component\"\n}\n```" } ]
code_add-to-cart-validation_39379def
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/messages/es.json from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"editor.countdown.title\": \"Cuenta regresiva\",\n \"editor.countdown.description\": \"Cuenta regresiva component\"\n}\n```" } ]
code_add-to-cart-validation_51b7a858
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/node/package.json from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"@vtex/api\": \"^3.0.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"8.x\",\n \"@vtex/api\": \"^3.0.0\",\n \"typescript\": \"3.9.4\"\n },\n \"resolutions\": {\n \"**/**/minimist\": \"^0.2.1\",\n \"**/**/lodash\": \"^4.17.17\"\n }\n}\n\n```" } ]
code_add-to-cart-validation_1179cca2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/node/index.ts from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ClientsConfig, LRUCache, Service, ServiceContext } from '@vtex/api'\n\nimport { Clients } from './clients'\n\nconst TIMEOUT_MS = 5000\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>\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service<Clients, {}>({\n clients,\n graphql: {\n resolvers: {\n Query: {},\n },\n },\n})\n\n```" } ]
code_add-to-cart-validation_820614e4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/react/package.json from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"@vtex/css-handles\": \"^1.0.0\",\n \"classnames\": \"^2.2.6\",\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/classnames\": \"^2.2.7\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.7.5\",\n \"@types/prop-types\": \"^15.7.0\",\n \"@types/ramda\": \"^0.26.5\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"apollo-client\": \"^2.5.1\",\n \"graphql\": \"^14.6.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.order-items\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-items@0.13.21/public/@types/vtex.order-items\",\n \"vtex.order-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.12.0/public/@types/vtex.order-manager\",\n \"vtex.product-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.10.0/public/@types/vtex.product-context\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.4/public/@types/vtex.render-runtime\",\n \"vtex.store-resources\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-resources@0.88.0/public/@types/vtex.store-resources\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.2/public/@types/vtex.styleguide\"\n }\n}\n\n```" } ]
code_add-to-cart-validation_b5771eb3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/react/AddToCartValidation.tsx from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable no-console */\n/* eslint-disable eqeqeq */\n/* eslint-disable no-var */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable prettier/prettier */\nimport React, { useState, useEffect } from 'react'\nimport type { FC } from 'react'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\nimport { useProduct } from 'vtex.product-context'\n\nconst ProductContext: FC = () => {\n const {\n orderForm: { items },\n } = useOrderForm()\n const [added, setAdded] = useState(false)\n const productContextValue = useProduct()\n var currentProductId: any\n var productAdded: any\n\n if (productContextValue?.product?.items.length == 1) {\n currentProductId = productContextValue?.product?.productId\n // Verifico si tengo el item agregado en el carrito\n productAdded = items?.filter(\n (item: any) => item.productId == currentProductId\n )\n useEffect(() => {\n if (productAdded.length > 0) {\n setAdded(true)\n } else {\n setAdded(false)\n }\n }, [productAdded])\n } else {\n currentProductId = productContextValue?.selectedItem?.itemId\n productAdded = items?.filter((item: any) => item.id == currentProductId)\n useEffect(() => {\n if (productAdded.length > 0) {\n setAdded(true)\n } else {\n setAdded(false)\n }\n }, [productAdded])\n }\n\n const AddToCart = ''\n const ProductAdded = '¡Producto agregado al cart!'\n\n return <div>{added ? ProductAdded : AddToCart}</div>\n}\n\nexport default ProductContext\n\n```" } ]
code_add-to-cart-validation_06c1af0c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/store/interfaces.json from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"add-to-cart-validation\": {\n \"component\": \"AddToCartValidation\"\n }\n}\n\n```" } ]
code_add-to-cart-validation_3420fe5b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/node/clients/index.ts from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nexport class Clients extends IOClients {}\n\n```" } ]
code_add-to-cart-validation_19440645
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/node/typings/global.d.ts from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare const metrics\n\ntype GenericObject = Record<string, any>\n\n```" } ]
code_add-to-cart-validation_39428cfd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/react/typings/storefront.d.ts from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = GenericObject>\n extends FunctionComponent<P> {\n getSchema?(props: P): GenericObject\n schema?: GenericObject\n }\n\n interface StorefrontComponent<P = GenericObject, S = GenericObject>\n extends Component<P, S> {\n getSchema?(props: P): GenericObject\n schema: GenericObject\n }\n}\n\n```" } ]
code_add-to-cart-validation_8ed880e1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/react/typings/vtex.render-runtime.d.ts from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import { Component, ComponentType, ReactElement, ReactType } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n interface ExtensionPointProps {\n id: string\n [key: string]: any\n }\n\n export const ExtensionPoint: ComponentType<ExtensionPointProps>\n\n interface ChildBlockProps {\n id: string\n }\n\n export const ChildBlock: ComponentType<ChildBlockProps>\n export const useChildBlock = ({ id: string }) => GenericObject\n\n export const Helmet: ReactElement\n export const Link: ReactType\n export const NoSSR: ReactElement\n export const RenderContextConsumer: ReactElement\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends GenericObject>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n}\n\n```" } ]
code_add-to-cart-validation_3d37f06a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/react/typings/global.d.ts from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface TimeSplit {\n hours: string\n minutes: string\n seconds: string\n}\n\ntype GenericObject = Record<string, any>\n\n```" } ]
code_add-to-cart-validation_99f2559d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/react/typings/css.d.ts from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: any\n export default css\n}\n\n```" } ]
code_add-to-cart-validation_92278594
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/react/typings/graphql.d.ts from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_add-to-cart-validation_006ffe9c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/react/typings/vtex.styleguide.d.ts from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n import { ComponentType } from 'react'\n\n export const Input: ComponentType<InputProps>\n\n interface InputProps {\n [key: string]: any\n }\n}\n\n```" } ]
code_add-to-cart-validation_42e53fa9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/react/utils/time.ts from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { TimeSplit } from '../typings/global'\n\nconst SECONDS_IN_MINUTE = 60\nconst SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE\n\nconst fillWithZero = (digits: number, number: number): string => {\n const filled = `${'0'.repeat(digits - 1)}${number}`\n\n return filled.slice(filled.length - digits)\n}\n\nexport const parseTimeRemaining = (totalSeconds: number): TimeSplit => {\n const hours = Math.floor(totalSeconds / SECONDS_IN_HOUR)\n const minutes = Math.floor(\n (totalSeconds % SECONDS_IN_HOUR) / SECONDS_IN_MINUTE\n )\n\n const seconds = Math.floor(\n (totalSeconds % SECONDS_IN_HOUR) % SECONDS_IN_MINUTE\n )\n\n return {\n hours: fillWithZero(2, hours),\n minutes: fillWithZero(2, minutes),\n seconds: fillWithZero(2, seconds),\n }\n}\n\n/**\n *\n * @param targetDate ISOString for the date that the countdown will expire\n * @param dispatchFn A function that updates the state of the component\n */\nexport const tick = (\n targetDate: string,\n dispatchFn: React.Dispatch<React.SetStateAction<TimeSplit>>\n) => {\n const ONE_SECOND_IN_MILLIS = 1000\n const finalDate = new Date(targetDate)\n const now = new Date()\n\n const secondsLeft =\n (finalDate.getTime() - now.getTime()) / ONE_SECOND_IN_MILLIS\n\n setTimeout(() => {\n dispatchFn(parseTimeRemaining(secondsLeft))\n }, ONE_SECOND_IN_MILLIS)\n}\n\nexport const getTwoDaysFromNow = () => {\n const today = new Date()\n\n today.setDate(today.getDate() + 2)\n\n return today.toISOString()\n}\n\n```" } ]
code_add-to-cart-validation_e5a4115a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of add-to-cart-validation/react/graphql/productReleaseDate.graphql from the add-to-cart-validation VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery productReleaseDate($slug: String){\n product(slug: $slug) {\n releaseDate\n }\n}\n\n```" } ]
code_product-highlights_e4d61c68
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/messages/de.json from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.product-highlights.filter\": \"Filter\",\n \"admin/editor.product-highlights.type\": \"Abfragetyp\",\n \"admin/editor.product-highlights.type.collection\": \"Kollektion\",\n \"admin/editor.product-highlights.type.promotion\": \"Beförderung\",\n \"admin/editor.product-highlights.type.teaser\": \"Teaser\",\n \"admin/editor.product-highlights.filter.type\": \"Art\",\n \"admin/editor.product-highlights.filter.type.hide\": \"Ausblenden\",\n \"admin/editor.product-highlights.filter.type.show\": \"Anzeigen\",\n \"admin/editor.product-highlights.filter.highlight-names\": \"Markieren Sie Namen\",\n \"admin/editor.product-highlights.filter.highlight-names.item\": \"Namen hervorheben\"\n}\n\n```" } ]
code_product-highlights_139ef5d7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/messages/en.json from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.product-highlights.filter\": \"Filter\",\n \"admin/editor.product-highlights.type\": \"Query Type\",\n \"admin/editor.product-highlights.type.collection\": \"Collection\",\n \"admin/editor.product-highlights.type.promotion\": \"Promotion\",\n \"admin/editor.product-highlights.type.teaser\": \"Teaser\",\n \"admin/editor.product-highlights.filter.type\": \"Type\",\n \"admin/editor.product-highlights.filter.type.hide\": \"Hide\",\n \"admin/editor.product-highlights.filter.type.show\": \"Show\",\n \"admin/editor.product-highlights.filter.highlight-names\": \"Highlight Names\",\n \"admin/editor.product-highlights.filter.highlight-names.item\": \"Highlight name\"\n}\n\n```" } ]
code_product-highlights_78ff46c9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/messages/context.json from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.product-highlights.filter\": \"Filter\",\n \"admin/editor.product-highlights.type\": \"Query Type\",\n \"admin/editor.product-highlights.type.collection\": \"Collection\",\n \"admin/editor.product-highlights.type.promotion\": \"Promotion\",\n \"admin/editor.product-highlights.type.teaser\": \"Teaser\",\n \"admin/editor.product-highlights.filter.type\": \"Type\",\n \"admin/editor.product-highlights.filter.type.hide\": \"Hide\",\n \"admin/editor.product-highlights.filter.type.show\": \"Show\",\n \"admin/editor.product-highlights.filter.highlight-names\": \"Highlight Names\",\n \"admin/editor.product-highlights.filter.highlight-names.item\": \"Highlight name\"\n}\n\n```" } ]
code_product-highlights_1171fd8e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/docs/README.md from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/product-highlights) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Product Highlights\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nThe Product Highlights app provides blocks to display highlight badges on products according to the collection or promotion they are linked to.\n\n![Product Highlights Example](https://cdn.jsdelivr.net/gh/vtexdocs/dev-portal-content@main/images/vtex-product-highlights-0.png)\n\n_In the image above, the product has a `Top Seller` highlight._\n\n## Configuration\n\n### Step 1 - Adding the Product Highlights app to your theme dependencies\n\nIn your theme `manifest.json` file, add the Product Highlights app as a dependency:\n\n```diff\n \"dependencies\": {\n+ \"vtex.product-highlights\": \"2.x\"\n}\n```\n\nNow, you can use all the blocks exported by the `product-highlights` app. See the full list below:\n\n| Block name | Description |\n| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `product-highlights` | Parent block for defining how the Product Highlights component will be displayed, based on its children blocks (`product-highlight-text` and `product-highlight-wrapper`) and props. |\n| `product-highlight-text` | Renders a `span` HTML tag with the highlight name. It also provides data attributes and CSS handles for style customizations. |\n| `product-highlight-wrapper` | You may use this block if you need to render other blocks alongside the highlight name. It renders a `div` HTML tag and its children blocks, if any. |\n\n### Step 2 - Adding the Product Highlights blocks to your theme templates\n\nCopy one of the examples stated below and paste it into your desired theme template, making the necessary changes. If needed, add the `product-highlights` block to the template block list.\n\n- Simple example:\n\n```json\n{\n \"vtex.product-highlights@2.x:product-highlights\": {\n \"children\": [\"product-highlight-text\"]\n },\n \"product-highlight-text\": {\n \"props\": {\n \"message\": \"{highlightName}\"\n }\n }\n}\n```\n\n- Example using the `link` prop:\n\n```json\n{\n \"vtex.product-highlights@2.x:product-highlights\": {\n \"children\": [\"product-highlight-text\"]\n },\n \"product-highlight-text\": {\n \"props\": {\n \"message\": \"{highlightName}\",\n \"link\": \"/collection/{highlightId}\"\n }\n }\n}\n```\n\n- Example using `product-highlight-wrapper`:\n\n```jsonc\n{\n \"vtex.product-highlights@2.x:product-highlights\": {\n \"children\": [\"product-highlight-wrapper\"]\n },\n \"product-highlight-wrapper\": {\n \"children\": [\n \"icon-star\", // You can add anything inside a product-highlight-wrapper\n \"product-highlight-text\"\n ]\n },\n \"product-highlight-text\": {\n \"props\": {\n \"message\": \"{highlightName}\"\n }\n }\n}\n```\n\n- Example using the prop `filter` and the prop `type`:\n\n```jsonc\n{\n \"vtex.product-highlights@2.x:product-highlights\": {\n \"props\": {\n \"type\": \"teaser\",\n \"filter\": {\n \"type\": \"show\",\n \"highlightNames\": [\"10% Boleto\"]\n }\n },\n \"children\": [\"product-highlight-text\"]\n },\n \"product-highlight-text\": {\n \"props\": {\n \"message\": \"{highlightName}\",\n \"blockClass\": \"boleto\"\n }\n }\n}\n```\n\n> ⚠️ warning\n>\n> Note that **the Product Highlights blocks require a Product context to work properly, as they handle product data**. Therefore, when declaring these blocks, ensure that they are in a theme template or block where this context is available, such as the `store.product` and `product-summary.shelf`.\n\n#### `product-highlights` props\n\n| Prop name | Type | Description | Default value |\n| --------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |\n| `type` | `enum` | The desired type of product highlight to be displayed. Possible values are: `collection`, `promotion`, and `teaser`. `collection` highlights the product's collection, so it must be used with the [Collection Highlight](https://help.vtex.com/en/tutorial/collection-highlight-control--1tGdb2ndjqy6yWsk2YwKMu?locale=en) feature. `promotion` and `teaser` should be used when the product is configured with a [promotion that includes highlights](https://help.vtex.com/en/tutorial/configuring-promotions-with-a-highlightflag--tutorials_2295?locale=en). It can be used even if the promotion does not have any restrictions. On the other hand, the `teaser` must only be used when the promotion has restrictions. ⚠️* Note that nominal promotions will only be displayed in the cart, not on the shelf or product page.* | `collection` |\n| `filter` | `object` | Defines which highlights should and should not be displayed by the block. | `undefined` |\n\n>⚠️ Technically, the `collection` highlight maps to the [`clusterHighlights`](https://github.com/vtex-apps/search-graphql/blob/ea1d7e244e6b00b58e5aa4272fbb16987c483468/graphql/types/Product.graphql#L29) property; the `promotion` highlight maps to the [`discountHighlights`](https://github.com/vtex-apps/search-graphql/blob/ea1d7e244e6b00b58e5aa4272fbb16987c483468/graphql/types/Product.graphql#L283) property; and the `teaser` highlight maps to the [`teasers`](https://github.com/vtex-apps/search-graphql/blob/ea1d7e244e6b00b58e5aa4272fbb16987c483468/graphql/types/Product.graphql#L284) property.\n\n- **`filter` object:**\n\n| Prop name | Type | Description | Default value |\n| ---------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |\n| `highlightNames` | `[string]` | An array of highlight names that determine which highlights should be hidden or shown based on the `type` property defined in the `product-highlights` block. | `undefined` |\n| `type` | `enum` | Determines whether the highlights for the `highlightNames` prop should be displayed or hidden on the UI. Possible values are: `hide` (hides highlights declared in the `highlightNames` prop) or `show` (only shows the highlights declared in the `highlightNames` prop). | `undefined` |\n\n#### `product-highlight-text` props\n\n| Prop name | Type | Description | Default value |\n| ------------ | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |\n| `blockClass` | `string` | The block ID you chose to be used for [CSS customization](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-css-handles-for-store-customization#using-the-blockclass-property). | `undefined` |\n| `message` | `string` | Defines the block default text message to be rendered in the UI. You can also use the Admin Site Editor and the `markers` prop to specify the text message that the block will render on the UI. | `undefined` |\n| `markers` | `[string]` | IDs you chose to identify the block's rendered text message and customize it using the Admin Site Editor. Learn how to use them in [Using the Markers prop to customize a block message](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-the-markers-prop-to-customize-a-blocks-message). Note that a block message can also be customized in the Store Theme source code using the `message` prop. | `[]` |\n| `link` | `string` | If this prop is set, it creates a link to the string passed. You can interpolate the variables `highlightText` and `highlightId`. Example: `/collection/{highlightId}`. | `undefined` |\n\n#### `product-highlight-wrapper` props\n\n| Prop name | Type | Description | Default value |\n| ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |\n| `blockClass` | `string` | The block ID you chose to be used in [CSS customization](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-css-handles-for-store-customization#using-the-blockclass-property). | `undefined` |\n\n### Step 3 - Editing the `product-highlight-text` messages\n\nThe `product-highlight-text` block uses the [ICU Message Format](https://format-message.github.io/icu-message-format-for-translators/), enabling comprehensive customization of the rendered text messages.\n\nWhen using the `message` prop, you will not need to create an advanced configuration: declare the prop directly in your Store Theme app and pass to it the desired text value to be rendered with the block.\n\nThe `markers` prop, in turn, requires you to add an extra configuration in the Site Editor of the Admin to properly work. When using this prop, do not forget to check out the block's message variables (shown in the table below) and the [Using the Markers prop to customize a block's message](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-the-markers-prop-to-customize-a-blocks-message) documentation.\n\n| Message variable | Type | Description |\n| ---------------- | -------- | -------------------- |\n| `highlightName` | `string` | Highlights the name. |\n\n## Customization\n\nTo apply CSS customizations to this and other blocks, follow the instructions in [Using CSS handles for store customizations](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-css-handles-for-store-customization).\n\n| CSS handles |\n| ------------------------- |\n| `productHighlightText` |\n| `productHighlightWrapper` |\n\n| Data attributes |\n| --------------------- |\n| `data-highlight-name` |\n| `data-highlight-id` |\n| `data-highlight-type` |\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n <tr>\n <td align=\"center\"><a href=\"https://www.linkedin.com/in/igor-becker-73b7901a3/\"><img src=\"https://avatars.githubusercontent.com/u/57180581?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>proudynyu</b></sub></a><br /><a href=\"https://github.com/vtex-apps/product-highlights/commits?author=proudynyu\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n\n<!-- markdownlint-restore -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```" } ]
code_product-highlights_4ae6b406
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/react/ProductHighlights.test.tsx from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport type { ProductContext } from 'vtex.product-context'\nimport { useProduct } from 'vtex.product-context'\n\nimport ProductHighlights from './ProductHighlights'\nimport ProductHighlightText from './ProductHighlightText'\nimport tankTop from './__fixtures__/tankTop'\n\nconst mockUseProduct = useProduct as jest.Mock<ProductContext>\n\nmockUseProduct.mockImplementation(() => ({ product: tankTop }))\n\ntest(\"render all collections' highlights\", () => {\n const { queryByText, rerender } = render(\n <ProductHighlights>\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n expect(queryByText('Top Sellers')).toBeInTheDocument()\n expect(queryByText('Summer')).toBeInTheDocument()\n\n rerender(\n <ProductHighlights type=\"collection\">\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n expect(queryByText('Top Sellers')).toBeInTheDocument()\n expect(queryByText('Summer')).toBeInTheDocument()\n})\n\ntest(\"render all promotions' highlights\", () => {\n const { queryByText } = render(\n <ProductHighlights type=\"promotion\">\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n expect(queryByText('Free Shipping')).toBeInTheDocument()\n expect(queryByText('10% Discount')).toBeInTheDocument()\n})\n\ntest(\"render all teasers' highlights\", () => {\n const { queryByText } = render(\n <ProductHighlights type=\"teaser\">\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n expect(queryByText('8% Boleto')).toBeInTheDocument()\n expect(queryByText('5% Visa')).toBeInTheDocument()\n})\n\ntest('render nothing if wrong type is passed', () => {\n const { container } = render(\n // eslint-disable-next-line @typescript-eslint/ban-ts-ignore\n // @ts-ignore\n <ProductHighlights type=\"\">\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n expect(container).toBeEmptyDOMElement()\n})\n\ntest(\"render nothing if there's no product context\", () => {\n mockUseProduct.mockImplementationOnce(() => ({ product: undefined }))\n\n const { container } = render(\n <ProductHighlights>\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n expect(container).toBeEmptyDOMElement()\n})\n\ntest('should filter highlights', () => {\n const { queryByText, rerender } = render(\n <ProductHighlights filter={{ type: 'hide', highlightNames: ['Summer'] }}>\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n expect(queryByText('Top Sellers')).toBeInTheDocument()\n expect(queryByText('Summer')).not.toBeInTheDocument()\n\n rerender(\n <ProductHighlights filter={{ type: 'show', highlightNames: ['Summer'] }}>\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n expect(queryByText('Top Sellers')).not.toBeInTheDocument()\n expect(queryByText('Summer')).toBeInTheDocument()\n\n rerender(\n <ProductHighlights\n filter={{\n type: 'hide',\n highlightNames: ['Summer', 'Top Sellers'],\n }}\n >\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n expect(queryByText('Top Sellers')).not.toBeInTheDocument()\n expect(queryByText('Summer')).not.toBeInTheDocument()\n\n rerender(\n <ProductHighlights\n filter={{\n type: 'show',\n highlightNames: ['Summer', 'Top Sellers'],\n }}\n >\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n expect(queryByText('Top Sellers')).toBeInTheDocument()\n expect(queryByText('Summer')).toBeInTheDocument()\n})\n\n```" } ]
code_product-highlights_28b36028
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/react/ProductHighlights.tsx from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC, ReactNode } from 'react'\nimport React, { useContext, useMemo } from 'react'\nimport { defineMessages } from 'react-intl'\nimport type { ProductTypes } from 'vtex.product-context'\nimport { useProduct } from 'vtex.product-context'\n\nimport { getSeller } from './modules/seller'\n\ntype HighlightType = 'collection' | 'promotion' | 'teaser'\n\ninterface Filter {\n type: 'hide' | 'show'\n highlightNames: string[]\n}\n\ninterface ProductHighlightsProps {\n filter?: Filter\n type?: HighlightType\n children: NonNullable<ReactNode>\n}\n\nconst defaultFilter: Filter = {\n type: 'hide',\n highlightNames: [],\n}\n\ninterface Highlight {\n id?: string\n name: string\n}\n\ninterface ProductHighlightContextProviderProps {\n highlight: Highlight\n type: HighlightType\n}\n\nfunction createFilterHighlight(filter: Filter) {\n return function filterHighlight(highlight: Highlight) {\n const hasHighlight = filter.highlightNames?.includes(highlight.name)\n\n if (\n (filter.type === 'hide' && hasHighlight) ||\n (filter.type === 'show' && !hasHighlight)\n ) {\n return false\n }\n\n return true\n }\n}\n\nconst ProductHighlightContext =\n React.createContext<ProductHighlightContextProviderProps | null>(null)\n\nconst ProductHighlightContextProvider: FC<ProductHighlightContextProviderProps> =\n ({ highlight, type, children }) => {\n const contextValue = useMemo(\n () => ({\n highlight,\n type,\n }),\n [highlight, type]\n )\n\n return (\n <ProductHighlightContext.Provider value={contextValue}>\n {children}\n </ProductHighlightContext.Provider>\n )\n }\n\nfunction ProductHighlights({\n filter = defaultFilter,\n type = 'collection',\n children,\n}: ProductHighlightsProps) {\n const { product, selectedItem } = useProduct() ?? {}\n const selectedSku = selectedItem ?? product?.items?.[0]\n const seller: ProductTypes.Seller | null = selectedSku\n ? getSeller(selectedSku)\n : null\n\n const highlights = useMemo(() => {\n const clusterHighlights = product?.clusterHighlights ?? []\n const discountHighlights = seller?.commertialOffer?.discountHighlights ?? []\n const teasers = seller?.commertialOffer?.teasers ?? []\n\n const filterHighlight = createFilterHighlight(filter)\n\n if (type === 'collection') {\n return clusterHighlights.filter(filterHighlight)\n }\n\n if (type === 'promotion') {\n return discountHighlights.filter(filterHighlight)\n }\n\n if (type === 'teaser') {\n return teasers.filter(filterHighlight)\n }\n\n return []\n }, [\n filter,\n product?.clusterHighlights,\n seller?.commertialOffer?.discountHighlights,\n seller?.commertialOffer?.teasers,\n type,\n ])\n\n if (!product) {\n return null\n }\n\n return (\n <>\n {highlights.map((highlight, index) => (\n <ProductHighlightContextProvider\n key={index}\n type={type}\n highlight={highlight}\n >\n {children}\n </ProductHighlightContextProvider>\n ))}\n </>\n )\n}\n\nconst messages = defineMessages({\n Filter: {\n defaultMessage: '',\n id: 'admin/editor.product-highlights.filter',\n },\n QueryType: {\n defaultMessage: '',\n id: 'admin/editor.product-highlights.type',\n },\n Collection: {\n defaultMessage: '',\n id: 'admin/editor.product-highlights.type.collection',\n },\n Promotion: {\n defaultMessage: '',\n id: 'admin/editor.product-highlights.type.promotion',\n },\n Teaser: {\n defaultMessage: '',\n id: 'admin/editor.product-highlights.type.teaser',\n },\n Type: {\n defaultMessage: '',\n id: 'admin/editor.product-highlights.filter.type',\n },\n Hide: {\n defaultMessage: '',\n id: 'admin/editor.product-highlights.filter.type.hide',\n },\n Show: {\n defaultMessage: '',\n id: 'admin/editor.product-highlights.filter.type.show',\n },\n HighlightNames: {\n defaultMessage: '',\n id: 'admin/editor.product-highlights.filter.highlight-names',\n },\n HighlightName: {\n defaultMessage: '',\n id: 'admin/editor.product-highlights.filter.highlight-names.item',\n },\n})\n\nProductHighlights.schema = {\n title: 'Product Highlights',\n type: 'object',\n properties: {\n filter: {\n title: messages.Filter.id,\n type: 'object',\n properties: {\n type: {\n title: messages.Type.id,\n type: 'string',\n enum: ['hide', 'show'],\n enumNames: [messages.Hide.id, messages.Show.id],\n },\n highlightNames: {\n title: messages.HighlightNames.id,\n type: 'array',\n minItems: 0,\n maxItems: 5,\n items: {\n title: messages.HighlightName.id,\n type: 'string',\n default: '',\n },\n },\n },\n },\n type: {\n title: 'admin/editor.product-highlights.type',\n type: 'string',\n enum: ['collection', 'promotion', 'teaser'],\n enumNames: [\n messages.Collection.id,\n messages.Promotion.id,\n messages.Teaser.id,\n ],\n },\n },\n}\n\nexport const useHighlight = () => {\n const group = useContext(ProductHighlightContext)\n\n return group\n}\n\nexport default ProductHighlights\n\n```" } ]
code_product-highlights_3f102b9b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/react/package.json from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"product-highlights\",\n \"version\": \"2.3.2\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.3.1\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.native-types\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.native-types@0.7.5/public/@types/vtex.native-types\",\n \"vtex.product-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.9.7/public/@types/vtex.product-context\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.126.11/public/@types/vtex.render-runtime\"\n }\n}\n\n```" } ]
code_product-highlights_7c72eb9e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/react/ProductHighlightText.test.tsx from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport { useProduct } from 'vtex.product-context'\n\nimport ProductHighlights from './ProductHighlights'\nimport ProductHighlightText from './ProductHighlightText'\nimport tankTop from './__fixtures__/tankTop'\n\nconst mockUseProduct = useProduct as jest.Mock\n\nmockUseProduct.mockImplementation(() => ({ product: tankTop }))\n\ntest('ProductHighlightText should render data-attributes and CSS handles', () => {\n const { getByText } = render(\n <ProductHighlights>\n <ProductHighlightText message=\"{highlightName}\" />\n </ProductHighlights>\n )\n\n const topSellers = getByText('Top Sellers')\n const summer = getByText('Summer')\n\n expect(topSellers).toHaveAttribute('data-highlight-id', '1182')\n expect(topSellers).toHaveAttribute('data-highlight-name', 'Top Sellers')\n expect(topSellers).toHaveAttribute('data-highlight-type', 'collection')\n expect(summer).toHaveClass('productHighlightText')\n\n expect(summer).toHaveAttribute('data-highlight-id', '1183')\n expect(summer).toHaveAttribute('data-highlight-name', 'Summer')\n expect(summer).toHaveAttribute('data-highlight-type', 'collection')\n expect(summer).toHaveClass('productHighlightText')\n})\n\ntest('ProductHighlightText should render link if prop is passed', () => {\n const { getByText } = render(\n <ProductHighlights>\n <ProductHighlightText\n message=\"{highlightName}\"\n link=\"/collection/{highlightName}/{highlightId}\"\n />\n </ProductHighlights>\n )\n\n const topSellers = getByText('Top Sellers')\n const summer = getByText('Summer')\n\n expect(topSellers).toHaveAttribute('href', '/collection/Top Sellers/1182')\n expect(summer).toHaveAttribute('href', '/collection/Summer/1183')\n})\n\ntest(\"ProductHighlightText should render nothing if there's no context\", () => {\n const { container } = render(\n <ProductHighlightText message=\"{highlightName}\" />\n )\n\n expect(container).toBeEmptyDOMElement()\n})\n\ntest(\"ProductHighlightText should render nothing if there's no message\", () => {\n const { container } = render(\n // eslint-disable-next-line @typescript-eslint/ban-ts-ignore\n // @ts-ignore\n <ProductHighlightText />\n )\n\n expect(container).toBeEmptyDOMElement()\n})\n\n```" } ]
code_product-highlights_47e54cbb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/react/ProductHighlightText.tsx from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC, ReactNode } from 'react'\nimport React, { useMemo } from 'react'\nimport { IOMessageWithMarkers, formatIOMessage } from 'vtex.native-types'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { useIntl } from 'react-intl'\n\nimport { useHighlight } from './ProductHighlights'\n\ninterface Props {\n message: string\n markers?: string[]\n blockClass?: string\n link?: string\n}\n\ninterface MessageValues {\n highlightName: ReactNode\n}\n\nconst CSS_HANDLES = ['productHighlightText'] as const\n\nconst ProductHighlightText: FC<Props> = ({\n message = '',\n markers = [],\n link = '',\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n const value = useHighlight()\n const intl = useIntl()\n\n const values = useMemo(() => {\n const result: MessageValues = {\n highlightName: '',\n }\n\n if (!value) {\n return result\n }\n\n if (link) {\n const href = formatIOMessage(\n {\n intl,\n id: link,\n },\n {\n highlightId: value.highlight.id ?? '',\n highlightName: value.highlight.name,\n }\n ) as string\n\n result.highlightName = (\n <a\n href={href}\n key=\"highlightLink\"\n data-highlight-name={value.highlight.name}\n data-highlight-id={value.highlight.id}\n data-highlight-type={value.type}\n className={handles.productHighlightText}\n >\n {value.highlight.name}\n </a>\n )\n } else {\n result.highlightName = (\n <span\n key=\"highlightName\"\n data-highlight-name={value.highlight.name}\n data-highlight-id={value.highlight.id}\n data-highlight-type={value.type}\n className={handles.productHighlightText}\n >\n {value.highlight.name}\n </span>\n )\n }\n\n return result\n }, [value, link, intl, handles.productHighlightText])\n\n if (!value || !message) {\n return null\n }\n\n return (\n <IOMessageWithMarkers\n handleBase=\"productHighlightText\"\n message={message}\n markers={markers}\n values={values}\n />\n )\n}\n\nexport default ProductHighlightText\n\n```" } ]
code_product-highlights_ae0f1c62
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/react/ProductHighlightWrapper.test.tsx from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport { useProduct } from 'vtex.product-context'\n\nimport ProductHighlights from './ProductHighlights'\nimport ProductHighlightWrapper from './ProductHighlightWrapper'\nimport tankTop from './__fixtures__/tankTop'\n\nconst mockUseProduct = useProduct as jest.Mock\n\nmockUseProduct.mockImplementation(() => ({ product: tankTop }))\n\ntest('ProductHighlight should render data-attributes and CSS handles', () => {\n const { getByText } = render(\n <ProductHighlights\n filter={{ type: 'show', highlightNames: ['Top Sellers'] }}\n >\n <ProductHighlightWrapper>Hello World</ProductHighlightWrapper>\n </ProductHighlights>\n )\n\n const topSellers = getByText('Hello World')\n\n expect(topSellers).toHaveAttribute('data-highlight-id', '1182')\n expect(topSellers).toHaveAttribute('data-highlight-name', 'Top Sellers')\n expect(topSellers).toHaveAttribute('data-highlight-type', 'collection')\n expect(topSellers).toHaveClass('productHighlightWrapper')\n})\n\ntest(\"ProductHighlight should render nothing if there's no context\", () => {\n const { container } = render(\n <ProductHighlightWrapper>Hello World</ProductHighlightWrapper>\n )\n\n expect(container).toBeEmptyDOMElement()\n})\n\n```" } ]
code_product-highlights_fdb261e1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/react/ProductHighlightWrapper.tsx from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC, ReactNode } from 'react'\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { useHighlight } from './ProductHighlights'\n\ninterface Props {\n blockClass?: string\n children: ReactNode\n}\n\nconst CSS_HANDLES = ['productHighlightWrapper'] as const\n\nconst ProductHighlightWrapper: FC<Props> = ({ children }) => {\n const handles = useCssHandles(CSS_HANDLES)\n const value = useHighlight()\n\n if (!value) {\n return null\n }\n\n return (\n <div\n data-highlight-name={value.highlight.name}\n data-highlight-id={value.highlight.id}\n data-highlight-type={value.type}\n className={handles.productHighlightWrapper}\n >\n {children}\n </div>\n )\n}\n\nexport default ProductHighlightWrapper\n\n```" } ]
code_product-highlights_9ae9d624
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/store/interfaces.json from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"product-highlights\": {\n \"component\": \"ProductHighlights\",\n \"composition\": \"children\"\n },\n \"product-highlight-wrapper\": {\n \"component\": \"ProductHighlightWrapper\",\n \"composition\": \"children\"\n },\n \"product-highlight-text\": {\n \"component\": \"ProductHighlightText\"\n }\n}\n\n```" } ]
code_product-highlights_5b57ea57
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/react/__fixtures__/tankTop.ts from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport default {\n cacheId: 'tank-top',\n productId: '3',\n description: 'Show your arms!',\n productName: 'Tank Top',\n productReference: 'xpto123',\n linkText: 'tank-top',\n brand: 'AOC',\n brandId: '2000012',\n link: 'https://portal.vtexcommercestable.com.br/tank-top/p',\n categories: [\n '/Apparel & Accessories/Clothing/Tops/',\n '/Apparel & Accessories/Clothing/',\n '/Apparel & Accessories/',\n ],\n priceRange: {\n sellingPrice: {\n highPrice: 600,\n lowPrice: 375.6,\n },\n listPrice: {\n highPrice: 1000,\n lowPrice: 600,\n },\n },\n specificationGroups: [\n {\n name: 'Specifications',\n originalName: 'Specifications',\n specifications: [\n {\n name: 'Sleeve type',\n originalName: 'Sleeve type',\n values: ['Sleeveless'],\n },\n ],\n },\n {\n name: 'allSpecifications',\n originalName: 'allSpecifications',\n specifications: [\n {\n name: 'Sleeve type',\n originalName: 'Sleeve type',\n values: ['Sleeveless'],\n },\n ],\n },\n ],\n items: [\n {\n itemId: '3',\n name: 'White',\n nameComplete: 'Tank Top White',\n complementName: '',\n ean: '613468247360',\n variations: [],\n referenceId: [\n {\n Key: 'RefId',\n Value: 'whitet',\n },\n ],\n measurementUnit: 'un',\n unitMultiplier: 1,\n images: [\n {\n cacheId: '155491',\n imageId: '155491',\n imageLabel: '',\n imageTag:\n '<img src=\"~/arquivos/ids/155491-#width#-#height#/Frame-1.jpg?v=636793841351870000\" width=\"#width#\" height=\"#height#\" alt=\"Frame-1\" id=\"\" />',\n imageUrl:\n 'https://storecomponents.vtexassets.com/arquivos/ids/155491/Frame-1.jpg?v=636793841351870000',\n imageText: 'Frame-1',\n },\n ],\n sellers: [\n {\n sellerId: '1',\n sellerName: 'VTEX',\n commertialOffer: {\n discountHighlights: [\n {\n name: 'Free Shipping',\n },\n {\n name: '10% Discount',\n },\n ],\n teasers: [\n {\n name: '8% Boleto',\n conditions: {\n minimumQuantity: 0,\n parameters: [\n {\n name: 'PaymentMethodId',\n value: '6',\n },\n ],\n },\n effects: {\n parameters: [\n {\n name: 'PercentualDiscount',\n value: '8.0',\n },\n ],\n },\n },\n {\n name: '5% Visa',\n conditions: {\n minimumQuantity: 0,\n parameters: [\n {\n name: 'PaymentMethodId',\n value: '3',\n },\n ],\n },\n effects: {\n parameters: [\n {\n name: 'PercentualDiscount',\n value: '5.0',\n },\n ],\n },\n },\n ],\n Installments: [\n {\n Value: 62.6,\n InterestRate: 0,\n TotalValuePlusInterestRate: 375.6,\n NumberOfInstallments: 6,\n Name: 'Visa 6 vezes sem juros',\n PaymentSystemName: 'Visa',\n },\n ],\n Price: 375.6,\n ListPrice: 600,\n Tax: 0,\n taxPercentage: 0,\n spotPrice: 345.5,\n PriceWithoutDiscount: 375.6,\n RewardValue: 0,\n PriceValidUntil: '2021-09-01T19:59:52.2582922Z',\n AvailableQuantity: 3000000,\n },\n },\n ],\n },\n {\n itemId: '4',\n name: 'Black',\n nameComplete: 'Tank Top Black',\n complementName: '',\n ean: 'code123',\n variations: [],\n referenceId: [\n {\n Key: 'RefId',\n Value: 'code1234',\n },\n ],\n measurementUnit: 'un',\n unitMultiplier: 1,\n images: [\n {\n cacheId: '155490',\n imageId: '155490',\n imageLabel: '',\n imageTag:\n '<img src=\"~/arquivos/ids/155490-#width#-#height#/Frame-2.jpg?v=636793841164270000\" width=\"#width#\" height=\"#height#\" alt=\"Frame-2\" id=\"\" />',\n imageUrl:\n 'https://storecomponents.vtexassets.com/arquivos/ids/155490/Frame-2.jpg?v=636793841164270000',\n imageText: 'Frame-2',\n },\n ],\n sellers: [\n {\n sellerId: '1',\n sellerName: 'VTEX',\n commertialOffer: {\n discountHighlights: [],\n teasers: [\n {\n name: '8% Boleto',\n conditions: {\n minimumQuantity: 0,\n parameters: [\n {\n name: 'PaymentMethodId',\n value: '6',\n },\n ],\n },\n effects: {\n parameters: [\n {\n name: 'PercentualDiscount',\n value: '8.0',\n },\n ],\n },\n },\n ],\n Installments: [\n {\n Value: 100,\n InterestRate: 0,\n TotalValuePlusInterestRate: 600,\n NumberOfInstallments: 6,\n Name: 'Visa 6 vezes sem juros',\n PaymentSystemName: 'Visa',\n },\n ],\n Price: 600,\n ListPrice: 1000,\n Tax: 0,\n taxPercentage: 0,\n spotPrice: 552,\n PriceWithoutDiscount: 600,\n RewardValue: 0,\n PriceValidUntil: '2021-09-01T19:59:52.2625928Z',\n AvailableQuantity: 3000000,\n },\n },\n ],\n },\n ],\n skuSpecifications: null,\n clusterHighlights: [\n {\n id: '1182',\n name: 'Top Sellers',\n },\n {\n id: '1183',\n name: 'Summer',\n },\n ],\n properties: [\n {\n name: 'Sleeve type',\n values: ['Sleeveless'],\n },\n ],\n selectedProperties: null,\n}\n\n```" } ]
code_product-highlights_6991c1af
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of product-highlights/react/modules/seller.ts from the product-highlights VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ProductTypes } from 'vtex.product-context'\n\nexport function getSeller(item: ProductTypes.Item) {\n const defaultSeller = item?.sellers?.find((seller) => seller.sellerDefault)\n\n if (!defaultSeller) {\n return item?.sellers?.[0]\n }\n\n return defaultSeller\n}\n\n```" } ]
code_cy-runner_d53faf7c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/deprecated.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst { get } = require('lodash')\n\nconst logger = require('./logger')\n\nmodule.exports.deprecated = async (config) => {\n // Let's try to warn deprecated features\n const FOUND = []\n const DEPRECATED = [\n 'base.vtex.deployCli',\n 'base.twilio',\n 'base.jira.testing',\n 'base.cypress.sorry',\n 'workspace.linkApp.logOutput',\n ]\n\n DEPRECATED.forEach((flag) => {\n if (get(config, flag)) FOUND.push(flag)\n })\n\n // eslint-disable-next-line vtex/prefer-early-return\n if (FOUND.length) {\n logger.msgSection('Deprecation report')\n logger.msgWarn('Deprecated configuration on your cy-runner.yml')\n FOUND.forEach((flag) => {\n logger.msgPad(flag)\n })\n logger.msgOk('You should remove it as soon as possible')\n }\n}\n\n```" } ]
code_cy-runner_e3aac93f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/logger.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst path = require('path')\n\nconst storage = require('./storage')\nconst system = require('./system')\n\nconst LOG_PATH = path.join(system.cyRunnerPath(), 'logs')\nconst LOG_FILE = path.join(LOG_PATH, '_cy-runner.log')\nconst PUL_FILE = path.join(LOG_PATH, '_cy-decorator.txt')\n\nfunction ico(type) {\n switch (type) {\n case 'section':\n return '####'\n\n case 'ok':\n return '[✓]'.padStart(8)\n\n case 'warn':\n return '[!]'.padStart(8)\n\n case 'error':\n return '[✗]'.padStart(8)\n\n case 'pipe':\n return ' ☍'.padStart(10)\n\n default:\n return '- '.padStart(8)\n }\n}\n\n// Init logs, clean before each run if local\nexports.init = () => {\n if (system.isCI()) return storage.makeDir(LOG_PATH)\n storage.delete(PUL_FILE)\n storage.delete(LOG_PATH)\n storage.makeDir(LOG_PATH)\n}\n\n// Return log path\nexports.logPath = () => {\n return LOG_PATH\n}\n\n// Return log file\nexports.logFile = () => {\n return LOG_FILE\n}\n\n// Write messages to log file and console\nexports.write = (msg, pr = false) => {\n process.stdout.write(msg)\n storage.append(msg, LOG_FILE)\n // Send pr messages to be printed in GitHub PR\n if (pr) {\n storage.append(\n storage.exists(PUL_FILE) ? msg : `#### Cy-Runner\\n\\n${msg}`,\n PUL_FILE\n )\n }\n}\n\nexports.msgOk = (msg, pr = false) => {\n this.write(`\\n${ico('ok')} ${msg}`, pr)\n}\n\nexports.msgWarn = (msg, pr = false) => {\n this.write(`\\n${ico('warn')} ${msg}`, pr)\n}\n\nexports.msgError = (msg, pr = false) => {\n this.write(`\\n${ico('error')} ${msg}`, pr)\n}\n\nexports.msgPipe = (msg) => {\n this.write(`\\n${ico('pipe')} ${msg}`)\n}\n\nexports.msgPad = (msg, pr = false) => {\n this.write(`\\n${ico()} ${msg}`, pr)\n}\n\nexports.msgSection = (msg, pr = false) => {\n if (system.isCI()) {\n // If first section, don't close group\n // eslint-disable-next-line no-console\n if (msg !== 'Cypress Runner') console.log(`::endgroup::`)\n\n // Open group for each new section\n // eslint-disable-next-line no-console\n console.log(`::group::${msg}`)\n }\n\n this.write(`\\n\\n${ico('section')} ${msg}\\n`, pr)\n}\n\nexports.msgEnd = (msg, pr = false) => {\n this.write(`\\n\\n${ico('section')} ${msg}\\n`, pr)\n}\n\nexports.newLine = (n = 1, pr = false) => {\n for (let i = 0; i < n; i++) {\n this.write('\\n', pr)\n }\n}\n\n```" } ]
code_cy-runner_8acffb9d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/test.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst path = require('path')\n\nconst { startCase, difference, intersection } = require('lodash')\n\nconst system = require('./system')\nconst logger = require('./logger')\nconst cypress = require('./cypress')\n\nlet specsFailed = []\nlet specsSkipped = []\nlet specsDisabled = []\nlet specsPassed = []\nlet runUrl = null\n\nexports.runTests = async (config) => {\n // Control time and load strategies\n const START = system.tick()\n const STRGS = config.strategy\n\n // Start Xvfb\n const xvfb = await this.startXvfb()\n\n // Loop strategies\n for (const strategy in STRGS) {\n const test = STRGS[strategy]\n const group = `${system.getId()}/${strategy}`\n\n test.name = startCase(strategy)\n\n // If test disabled, just flag and continue\n if (!test.enabled) {\n specsDisabled = specsDisabled.concat(test.specs)\n continue\n }\n\n // If it has dependencies, and they don't meet, flag and continue\n if (test.dependency?.length) {\n // Set to drop eventual user duplications by mistaken\n const deps = [...new Set(test.dependency)].sort()\n const pass = [...new Set(specsPassed)].sort()\n const miss = difference(deps, pass)\n\n // Dependencies don't meet\n if (miss?.length) {\n logger.msgSection(`[skip] Strategy ${test.name}`)\n const loopPass = intersection(deps, pass)\n const loopMiss = intersection(deps, miss)\n const loopSkip = intersection(deps, specsSkipped)\n\n // Show feedback to user\n loopPass.forEach((spec) => {\n logger.msgOk(cypress.specNameClean(spec))\n })\n loopSkip.forEach((spec) => {\n logger.msgWarn(cypress.specNameClean(spec))\n })\n loopMiss.forEach((spec) => {\n logger.msgError(cypress.specNameClean(spec))\n })\n\n // Feed skipped list\n specsSkipped = specsSkipped.concat(test.specs)\n\n continue\n }\n }\n\n // All set, let's run the test\n // eslint-disable-next-line no-await-in-loop\n await runTest(test, config, group)\n }\n\n // Stops Xvfb\n await this.stopXvfb(xvfb)\n\n return {\n time: system.tack(START),\n specsFailed,\n specsSkipped,\n specsDisabled,\n specsPassed,\n runUrl,\n }\n}\n\nexports.startXvfb = async () => {\n // Xvfb only run if running on CI\n if (system.isCI()) {\n const displayLog = path.join(logger.logPath(), '_display.log')\n\n return system.spawn(\n 'Xvfb',\n ['-screen', '0', '1024x768x24', ':99'],\n displayLog\n )\n }\n}\n\nexports.stopXvfb = async (xvfb) => {\n if (system.isCI()) xvfb.kill()\n}\n\nasync function runTest(test, config, group) {\n const cypressOptions = { parallel: test.parallel }\n const tries = test.hardTries + 1\n let testTry = 1\n\n test.specs = [...new Set(test.specs)] // Sanitize\n while (testTry <= tries && test.specs.length) {\n logger.msgSection(`[try ${testTry}/${tries}] Strategy ${test.name}`)\n if (runUrl) {\n logger.msgOk('Dashboard URL')\n logger.msgPad(runUrl)\n }\n\n logger.msgOk('Specs to run on this try')\n test.specs.forEach((spec) => {\n logger.msgPad(cypress.specNameClean(spec))\n })\n cypressOptions.group = `${group}/${testTry}`\n // eslint-disable-next-line no-await-in-loop\n const results = await cypress.run(test, config, cypressOptions)\n\n // eslint-disable-next-line no-loop-func\n results.forEach((result) => {\n if (!runUrl) runUrl = result.runUrl\n if (result.success) {\n test.specs = difference(test.specs, result.specsPassed)\n specsPassed = specsPassed.concat(result.specsPassed)\n }\n })\n testTry++\n }\n\n if (!test.specs.length) {\n logger.msgOk(`Strategy ${test.name} ran successfully`)\n specsPassed = [...new Set(specsPassed)].sort() // Sanitization\n specsPassed.forEach((spec) => {\n logger.msgPad(`Passed: ${cypress.specNameClean(spec)}`)\n })\n } else {\n logger.msgError(`Strategy ${test.name} failed`)\n specsFailed = specsFailed.concat(test.specs)\n specsFailed = [...new Set(specsFailed)].sort() // Sanitization\n specsFailed.forEach((spec) => {\n logger.msgPad(`Failed: ${cypress.specNameClean(spec)}`)\n })\n if (test.stopOnFail) {\n await cypress.stopOnFail(\n config,\n { strategy: test.name, specsPassed, specsFailed },\n runUrl\n )\n }\n }\n}\n\n```" } ]
code_cy-runner_60fa9ffb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/system.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst { execSync, spawn } = require('child_process')\nconst fs = require('fs')\nconst path = require('path')\n\nconst logger = require('./logger')\nconst storage = require('./storage')\nconst workspace = require('./workspace')\n\nconst BASE_PATH = path.join(__dirname, '..', '..')\n\n// Return base path\nexports.basePath = () => {\n return BASE_PATH\n}\n\n// Return root path\nexports.rootPath = () => {\n return path.join(BASE_PATH, '..')\n}\n\n// Return cy-runner path\nexports.cyRunnerPath = () => {\n return path.join(BASE_PATH, 'cy-runner')\n}\n\n// Return toolbelt to be used\nexports.vtexBin = async (crash = false) => {\n const VTEX_BIN = path.join(\n this.cyRunnerPath(),\n 'node_modules',\n 'vtex',\n 'bin',\n 'run'\n )\n\n // Return the installed as cy-runner package, for sure it is on the right version\n if (storage.exists(VTEX_BIN)) return VTEX_BIN\n\n // Let's avoid check version every time\n if (crash) {\n const VTEX_VERSION = this.exec('vtex version', 'pipe')\n const check = /beta-ci/.test(VTEX_VERSION)\n\n return check\n ? 'vtex'\n : this.crash(\"Run 'yarn install' inside cy-runner folder\", VTEX_VERSION)\n }\n\n // It passed on crash test already, just return\n return 'vtex'\n}\n\n// Detect CI\nexports.isCI = () => {\n return !!process.env.CI\n}\n\n// Debug file\nexports.debugFile = () => {\n return path.join(process.env.HOME, '.vtex', 'logs', 'debug.json')\n}\n\n// Delay\nexports.delay = (ms) => new Promise((res) => setTimeout(res, ms))\n\n// Crash and exit\nexports.crash = (msg, err, options = { pr: true, dump: true }) => {\n logger.msgEnd('Error', options.pr)\n logger.msgError(msg, 'Crash', options.pr)\n if (typeof err !== 'undefined') logger.msgPad(err, options.pr)\n\n // kill any subprocesses created by cy-runner\n const PID_FILE = path.join(logger.logPath(), '_pid')\n\n if (storage.exists(PID_FILE)) {\n const PID = storage.read(PID_FILE)\n\n logger.msgPad(`Killing pid ${PID} [vtex link]`)\n try {\n process.kill(Number(PID.toString()), 9)\n } catch (e) {\n logger.msgPad(`Failed to kill ${PID}`)\n }\n }\n\n // Dump env\n if (options.dump) workspace.dumpEnvironment().then((r) => r)\n\n logger.newLine(2)\n\n // Give GitHub information to print about the error\n // eslint-disable-next-line no-console\n if (options.pr) console.log(`::error title=${msg}::${err}`)\n process.exit(99)\n}\n\n// Success and exit\nexports.success = (msg) => {\n logger.msgEnd('Success', true)\n logger.msgOk(msg, true)\n logger.newLine()\n process.exit(0)\n}\n\n// Fail and exit\nexports.fail = (msg) => {\n logger.msgEnd('Fail', true)\n logger.msgError(msg, true)\n logger.newLine()\n process.exit(17)\n}\n\n// Run sync process\nexports.exec = (cmd, output = 'ignore', cwd = process.cwd()) => {\n const timeout = 5 * 60 * 1000 // 5 minutes\n let result\n\n try {\n result = execSync(cmd, { stdio: output, timeout, cwd })\n } catch (e) {\n logger.msgError(`Failed to run ${cmd}`)\n logger.msgPad(e)\n result = 'error'\n\n // If timeout, exit\n if (/ETIMEDOUT/.test(e)) this.crash(`Timeout running ${cmd}`, e)\n }\n\n return result.toString()\n}\n\n// Start a background process\n// eslint-disable-next-line max-params\nexports.spawn = (bin, cmd, logFile, cwd = process.cwd()) => {\n const out = fs.openSync(logFile, 'a')\n const err = fs.openSync(logFile, 'a')\n\n try {\n const subprocess = spawn(bin, cmd, {\n cwd,\n detached: true,\n stdio: ['ignore', out, err],\n })\n\n subprocess.unref()\n\n return subprocess\n } catch (e) {\n logger.msgError(`Failed to spawn ${cmd}`)\n logger.msgPad(e)\n }\n}\n\n// Start timer\nexports.tick = () => {\n return Date.now()\n}\n\n// Finish time\nexports.tack = (start) => {\n const stop = (Date.now() - start) / 1000\n const convert = (x) => (x < 10 ? `0${Math.floor(x)}` : Math.floor(x))\n const h = convert(stop / (60 * 60))\n const m = convert((stop / 60) % 60)\n const s = convert(stop % 60)\n\n return `${h}:${m}:${s}`\n}\n\n// Init ID\nexports.initId = () => {\n const ID = this.tick().toString().substring(6, 13)\n const FILE_ID = path.join(logger.logPath(), '_id')\n\n storage.delete(FILE_ID)\n storage.write(ID, FILE_ID)\n}\n\n// Get ID\nexports.getId = () => {\n const FILE_ID = path.join(logger.logPath(), '_id')\n\n if (storage.exists(FILE_ID)) return storage.read(FILE_ID)\n\n this.initId()\n\n return storage.read(FILE_ID)\n}\n\n// Traverse YAML or JSON\nexports.traverse = (result, obj, previousKey) => {\n if (typeof obj === 'object') {\n for (const key in obj) {\n this.traverse(\n result,\n obj[key],\n (previousKey || '') + (previousKey ? `.${key}` : key)\n )\n }\n } else {\n result.push({\n key: previousKey || '',\n type: obj,\n })\n }\n\n return result\n}\n\n// Check mixed paths\nexports.checkSpecHealth = async (config) => {\n for (const strategy in config.strategy) {\n const test = config.strategy[strategy]\n\n if (test.enabled) {\n const PATH = path.parse(test.specs[0]).dir\n\n // eslint-disable-next-line no-loop-func\n test.specs.forEach((spec) => {\n if (path.parse(spec).dir !== PATH) {\n this.crash('Paths mixed on the same strategy', spec, {\n dump: false,\n })\n }\n\n if (!storage.exists(path.join(this.cyRunnerPath(), spec))) {\n this.crash('Spec does not exist', spec, {\n dump: false,\n })\n }\n })\n }\n }\n\n if (config.workspace.wipe.enabled) {\n const { specs } = config.workspace.wipe\n\n specs.forEach((spec) => {\n if (!storage.exists(path.join(this.cyRunnerPath(), spec))) {\n this.crash('Wipe spec does not exist', spec, {\n dump: false,\n })\n }\n })\n }\n}\n\n```" } ]
code_cy-runner_144cefc9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/credentials.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst path = require('path')\n\nconst { merge } = require('lodash')\nconst jsYaml = require('js-yaml')\n\nconst http = require('./http')\nconst logger = require('./logger')\nconst schema = require('./schema')\nconst system = require('./system')\nconst toolbelt = require('./toolbelt')\nconst storage = require('./storage')\n\nexports.getCookies = async (config) => {\n // eslint-disable-next-line vtex/prefer-early-return\n if (config.base.cypress.getCookies) {\n // Admin cookie\n logger.msgOk('Getting admin cookie')\n const axiosConfig = {\n url: config.base.vtex.vtexIdUrl,\n method: 'get',\n params: {\n user: config.base.vtex.apiKey,\n pass: config.base.vtex.apiToken,\n },\n }\n\n const response = await http.request(axiosConfig)\n\n if (response?.data?.authStatus !== 'Success') {\n system.crash(\n 'Failed to get admin credentials',\n 'Check your apiToken and apiKey on your secrets and enable it'\n )\n }\n\n config.base.vtex.authCookieName = response?.data?.authCookie?.Name\n config.base.vtex.adminAuthCookieValue = response?.data?.authCookie?.Value\n\n // User cookie\n logger.msgOk('Getting user cookie')\n const userOrRobot = await toolbelt.getLocalToken()\n\n config.base.vtex.userAuthCookieValue = userOrRobot.token\n logger.msgPad(userOrRobot.mailOrKey)\n\n return config\n }\n}\n\nexports.readSecrets = (config) => {\n if (!config.base.secrets.enabled) {\n logger.msgWarn('Secrets disabled')\n\n return {}\n }\n\n logger.msgOk('Loading secrets')\n const SECRET_NAME = config.base.secrets.name\n const SECRET_FILE = path.join(system.cyRunnerPath(), `.${SECRET_NAME}.json`)\n let secrets = process.env[SECRET_NAME]\n let loadedFrom = null\n\n if (storage.exists(SECRET_FILE)) {\n secrets = storage.readYaml(SECRET_FILE)\n loadedFrom = `file ${SECRET_FILE}`\n } else {\n if (!secrets) {\n system.crash(\n 'Secrets missing',\n `You should disable secrets, create a '.${SECRET_NAME}.json' or set a '${SECRET_NAME}' env`\n )\n }\n\n try {\n secrets = jsYaml.load(secrets, 'utf-8')\n loadedFrom = `env variable ${SECRET_NAME}`\n } catch (e) {\n this.crash(`Check if your env variable ${SECRET_NAME} is well formatted`)\n }\n }\n\n schema.validateSecrets(secrets, config)\n logger.msgPad(`from ${loadedFrom.replace(system.basePath(), '.')}`)\n\n return secrets\n}\n\nexports.mergeSecrets = (config, secrets) => {\n merge(config.base, secrets)\n\n return config\n}\n\n```" } ]
code_cy-runner_89fbacba
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/config.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst path = require('path')\n\nconst { get } = require('lodash')\n\nconst logger = require('./logger')\nconst storage = require('./storage')\nconst credentials = require('./credentials')\nconst lock = require('./lock')\nconst system = require('./system')\nconst cypress = require('./cypress')\nconst http = require('./http')\n\nexports.getConfig = async (configFile) => {\n // Load and parse cy-runner.yml file\n logger.msgOk('Loading cy-runner configuration')\n let config = storage.loadConfig(configFile)\n\n // Make link if base has Cypress folder\n const lnk = path.join(__dirname, '..', 'cypress')\n const src = path.join(__dirname, '..', 'cypress-shared', 'support', 'common')\n const cyp = path.join(__dirname, '..', '..', 'cypress')\n const dst = path.join(__dirname, '..', '..', 'cypress', 'support')\n\n if (storage.exists(dst)) {\n logger.msgOk('Linking local Cypress code on Cy-Runner')\n\n // Create common links inside cypress\n const common = path.join(dst, 'common')\n const clean = path.join(__dirname, '..', '..')\n\n logger.msgPad(`${src.replace(clean, '.')} -> ${common.replace(clean, '.')}`)\n if (storage.exists(common)) storage.unLink(common)\n storage.link(src, common)\n\n // Create cypress link inside cy-runner\n logger.msgPad(`${cyp.replace(clean, '.')} -> ${lnk.replace(clean, '.')}`)\n if (storage.exists(lnk)) storage.unLink(lnk)\n storage.link(cyp, lnk)\n }\n\n // Check mixed paths and missing specs\n logger.msgOk('Checking for mixed paths and missing specs')\n await system.checkSpecHealth(config)\n\n // Check toolbelt version\n logger.msgOk('Checking toolbelt version')\n await system.vtexBin(true)\n\n // Fill URLs\n const VTEX_AUTH_PATH = '.myvtex.com/api/vtexid/pub/authentication'\n const VTEX_ACCOUNT = config.base.vtex.account\n const WORKSPACE = await this.getWorkspaceName(config)\n const ACCOUNT = config.base.vtex.account\n const DOMAIN = config.base.vtex.domain\n const RESERVE = config.workspace?.reserveAccount?.enabled\n\n config.base.vtex.authUrl = `https://${VTEX_ACCOUNT}${VTEX_AUTH_PATH}`\n config.base.vtex.baseUrl = `https://${WORKSPACE}--${ACCOUNT}.${DOMAIN}`\n\n // Load and parse secrets\n const secrets = credentials.readSecrets(config)\n\n // Lock the orderForm, in CI the lock is done by a step on GH Actions\n if (RESERVE) await lock.reserveAccount(config, secrets)\n\n // Seed envs if not present\n if (!config.envs) config.envs = []\n\n // TODO: Migrate this to its own yaml file\n config.base.stateFiles.push('_orderFormDebug.json')\n config.base.keepStateFiles = true\n\n // Run in different mode if on GitHub (CI)\n if (system.isCI()) {\n logger.msgWarn('Running in CI mode')\n // Enforce config to avoid misconfiguration\n config.base.vtex.isCI = true\n config.base.cypress.devMode = false\n config.base.cypress.runHeaded = false\n config.base.cypress.quiet = true\n config.base.cypress.videoUploadOnPasses = false\n config.base.cypress.trashAssetsBeforeRuns = false\n config.base.cypress.watchForFileChanges = false\n config.base.cypress.browser = 'chrome'\n // Inject envs\n config.envs.push(\n 'ELECTRON_EXTRA_LAUNCH_ARGS: --disable-gpu --disable-software-rasterizer'\n )\n config.envs.push('LIBVA_DRIVER_NAME: --disable-software-rasterizer')\n config.envs.push('DISPLAY: :99')\n config.envs.push('NODE_NO_WARNINGS: 1')\n } else {\n config.base.vtex.isCI = false\n // Clean debug\n logger.msgOk('Cleaning debug file')\n storage.delete(system.debugFile())\n logger.msgPad(`${system.debugFile()} cleaned successfully`)\n\n // If local and not on dev mode\n if (!config.base.cypress.devMode) {\n // Disable parallelism if Sorry Cypress is not running\n const sorryRunning = await http.runningSorryCypress()\n\n if (!sorryRunning) {\n logger.msgError('Sorry Cypress not detected')\n logger.msgPad('disabling dashboard')\n logger.msgPad('disabling parallelization')\n logger.msgPad('waiting 7 seconds, so you can cancel and try again')\n await system.delay(7000)\n config.base.cypress.maxJobs = 0\n }\n }\n }\n\n // Merge secrets on config\n config = credentials.mergeSecrets(config, secrets)\n\n // Report configuration to help understand that'll run\n await this.sectionsToRun(config)\n\n // Set up Cypress environment\n logger.msgSection('Cypress set up')\n config = await credentials.getCookies(config)\n logger.msgOk('Creating Cypress environment')\n cypress.saveCypressEnvJson(config)\n cypress.saveCypressJson(config)\n\n // Create state files\n storage.createStateFiles(config)\n\n // Export envs to make debug easier inside GitHub\n if (config.envs.length) logger.msgOk('Exporting envs variables')\n config.envs.forEach((env) => {\n const [envName, envValue] = env.split(': ')\n\n logger.msgPad(`${envName} = ${envValue}`)\n process.env[envName] = envValue\n })\n\n return config\n}\n\nexports.getWorkspaceName = async (config) => {\n const { workspace } = config\n\n if (workspace.name === 'random') {\n const id = system.getId()\n const { prefix } = workspace\n\n workspace.name = `${prefix}${id}`\n } else {\n workspace.name = workspace.name.toLowerCase()\n }\n\n logger.msgOk('Defining workspace')\n logger.msgPad(workspace.name)\n\n return workspace.name\n}\n\nexports.sectionsToRun = async (config) => {\n logger.msgSection('Sections to run')\n const getList = (item, property) => {\n const list = get(config, `${item}.${property}`)\n\n return list !== undefined ? list : []\n }\n\n system.traverse([], config).forEach((item) => {\n // eslint-disable-next-line vtex/prefer-early-return\n if (/enabled/.test(item.key) && /true/.test(item.type)) {\n const [itemEnabled] = item.key.split('.enabled')\n\n logger.msgOk(itemEnabled)\n getList(itemEnabled, 'specs').forEach((spec) => {\n logger.msgPad(cypress.specNameClean(spec))\n })\n getList(itemEnabled, 'dependency').forEach((dep) => {\n logger.msgPipe(cypress.specNameClean(dep))\n })\n }\n })\n\n const NUM_APPS_INSTALL = config.workspace.installApps.length\n const NUM_APPS_REMOVE = config.workspace.removeApps.length\n\n if (NUM_APPS_INSTALL) {\n logger.msgOk('Apps to be installed')\n getList('workspace', 'installApps').forEach((app) => {\n logger.msgPad(app)\n })\n }\n\n if (NUM_APPS_REMOVE) {\n logger.msgOk('Apps to be removed')\n getList('workspace', 'removeApps').forEach((app) => {\n logger.msgPad(app)\n })\n }\n}\n\n```" } ]
code_cy-runner_b5324be8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/workspace.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst path = require('path')\n\nconst lock = require('./lock')\nconst system = require('./system')\nconst logger = require('./logger')\nconst toolbelt = require('./toolbelt')\nconst storage = require('./storage')\nconst http = require('./http')\nconst { wipe } = require('./wipe')\n\nconst MAX_RETRIES = 3\n\nexports.init = async (config) => {\n const START = system.tick()\n const NAME = config.workspace.name\n\n logger.msgSection('Workspace set up')\n logger.msgOk('Changing workspace')\n logger.msgPad(NAME)\n\n // Create namespace\n const check = await toolbelt.changeWorkspace(NAME)\n\n if (!check) system.crash('Failed to change workspace')\n\n return system.tack(START)\n}\n\nexports.installApps = async (config) => {\n const START = system.tick()\n const APPS = config.workspace.installApps\n\n if (APPS?.length) {\n let check = { success: false, log: null }\n let thisTry = 1\n\n while (thisTry <= MAX_RETRIES && !check.success) {\n logger.msgOk(`[try ${thisTry}/${MAX_RETRIES}] Installing apps`)\n // eslint-disable-next-line no-await-in-loop\n check = await toolbelt.install(APPS)\n thisTry++\n }\n\n if (!check.success) system.crash('Failed to install some app', check.log)\n }\n\n return system.tack(START)\n}\n\nexports.uninstallApps = async (config) => {\n const START = system.tick()\n const APPS = config.workspace.removeApps\n\n if (APPS?.length) {\n let check = { success: false, log: null }\n let thisTry = 1\n\n while (thisTry <= MAX_RETRIES && !check.success) {\n logger.msgOk(`[try ${thisTry}/${MAX_RETRIES}] Uninstalling apps`)\n // eslint-disable-next-line no-await-in-loop\n check = await toolbelt.uninstall(APPS)\n thisTry++\n }\n\n if (!check.success) system.crash('Failed to uninstall some app', check.log)\n }\n\n return system.tack(START)\n}\n\nexports.updateVtexIgnore = async () => {\n const IGNORE_FILE = path.join(system.basePath(), '.vtexignore')\n const SHORT_NAME = IGNORE_FILE.replace(system.rootPath(), '.')\n\n logger.msgOk(`Updating ${SHORT_NAME}`)\n if (!storage.exists(IGNORE_FILE)) storage.write('# cy-r\\n', IGNORE_FILE)\n const EXCLUSIONS = ['cypress', 'cy-runner', 'cypress-shared']\n\n EXCLUSIONS.forEach((exclusion) => {\n storage.append(`${exclusion}\\n`, IGNORE_FILE)\n })\n}\n\nexports.linkApp = async (config) => {\n const START = system.tick()\n\n // eslint-disable-next-line vtex/prefer-early-return\n if (config.workspace.linkApp.enabled) {\n const MANIFEST_FILE = path.join(system.basePath(), 'manifest.json')\n const SHORT_NAME = MANIFEST_FILE.replace(system.rootPath(), '.')\n\n // Update vtex ignore\n await this.updateVtexIgnore()\n\n // Read name of app to be linked\n logger.msgOk(`Reading ${SHORT_NAME}`)\n const MANIFEST = storage.readYaml(MANIFEST_FILE)\n const APP = `${MANIFEST.vendor}.${MANIFEST.name}@${MANIFEST.version}`\n\n // Link app\n logger.msgOk(`Linking ${APP}`)\n let APP_LOG = path.join(logger.logPath(), `_link_${APP}.log`)\n const APP_PID = path.join(logger.logPath(), `_pid`)\n const STOP = 13\n const link = await toolbelt.link(APP_LOG)\n let check = false\n let loop = 0\n\n while (!check) {\n // To not wait forever\n loop++\n if (loop === STOP) break\n if (link.killed) system.crash('Link failed', JSON.stringify(link))\n\n logger.msgPad(`waiting ${130 - loop * 10} seconds until link gets ready`)\n // eslint-disable-next-line no-await-in-loop\n await system.delay(10000)\n\n const log = storage.read(APP_LOG)\n\n check = /App running | App linked successfully/.test(log.toString())\n }\n\n if (check) {\n logger.msgOk('App linked successfully')\n } else {\n APP_LOG = APP_LOG.replace(system.cyRunnerPath(), '.')\n logger.msgError('Failed to link app, you should', true)\n logger.msgPad(`1. Read the log ${APP_LOG}`, true)\n logger.msgPad('2. Fix your code if get some error on log', true)\n logger.msgPad('3. Try the E2E test again', true)\n logger.msgWarn('The link fail due an error or timeout (120 s)', true)\n }\n\n if (link.pid) storage.write(link.pid.toString(), APP_PID)\n\n // Test login page after app link\n this.checkLoginPage(config.workspace.name)\n\n return { success: check, time: system.tack(START), subprocess: link }\n }\n\n return { success: true, time: system.tack(START), subprocess: null }\n}\n\nexports.checkLoginPage = async (workspace) => {\n const LOGIN_PATH = '/_v/segment/admin-login/v1/login'\n const AXIOS_CFG = {\n url: `https://${workspace}--productusqa.myvtex.com${LOGIN_PATH}`,\n method: 'get',\n }\n\n let thisTry = 1\n let check = false\n\n while (thisTry <= MAX_RETRIES && !check) {\n logger.msgOk(`[try ${thisTry}/${MAX_RETRIES}] Checking login page`)\n\n // eslint-disable-next-line no-await-in-loop\n const response = await http.request(AXIOS_CFG)\n\n if (/2../.test(response?.status)) check = true\n thisTry++\n }\n\n if (!check) system.crash('Access to login page failed')\n}\n\nexports.teardown = async (config, linkSucceed = true) => {\n const START = system.tick()\n const { workspace } = config\n const RESERVE = config.workspace?.reserveAccount?.enabled\n\n if (RESERVE) await lock.releaseAccount(config)\n\n logger.msgSection('Workspace teardown')\n await this.dumpEnvironment()\n if (config.base.keepStateFiles) storage.keepStateFiles(config)\n // Run wipe only if link succeeds\n if (linkSucceed) await wipe(config)\n await this.cleanSensitiveData()\n if (workspace.teardown.enabled) await toolbelt.deleteWorkspace(workspace.name)\n\n return system.tack(START)\n}\n\n// Save apps list\nexports.dumpEnvironment = async () => {\n const APPS_INSTALLED = path.join(logger.logPath(), '_apps_installed.txt')\n const APPS_DEPENDENCY = path.join(logger.logPath(), '_apps_dependency.json')\n\n logger.msgOk('Dumping environment')\n logger.msgPad(APPS_INSTALLED.replace(system.basePath(), '.'))\n storage.write((await toolbelt.ls()).toString(), APPS_INSTALLED)\n logger.msgPad(APPS_DEPENDENCY.replace(system.basePath(), '.'))\n storage.write((await toolbelt.dependency()).toString(), APPS_DEPENDENCY)\n\n const SRC = system.debugFile()\n let DST = path.join(logger.logPath(), '_debug.json')\n\n logger.msgPad(`${SRC} -> ${DST.replace(system.basePath(), '.')}`)\n storage.copy(SRC, DST)\n\n DST = path.join(logger.logPath(), '_node_versions.json')\n logger.msgPad(`Node versions -> ${DST.replace(system.basePath(), '.')}`)\n storage.append(JSON.stringify(process.versions), DST)\n\n DST = path.join(logger.logPath(), '_env.txt')\n logger.msgPad(`Env variables -> ${DST.replace(system.basePath(), '.')}`)\n delete process.env.VTEX_QE\n storage.append(JSON.stringify(process.env), DST)\n}\n\n// Clean sensitive data\nexports.cleanSensitiveData = async () => {\n const SENSITIVE_FILES = ['cypress.env.json', 'cypress.json']\n\n logger.msgOk('Cleaning sensitive data')\n SENSITIVE_FILES.forEach((file) => {\n logger.msgPad(file)\n storage.delete(file)\n })\n}\n\n```" } ]
code_cy-runner_fae2796c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/schema.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/** ********************************************\n Validate schema on cy-runner.yml\n Test only mandatory fields cy-runner works\n 0 = String not null\n 1 = Integer not null\n 2 = Boolean not null\n 3 = String\n 4 = Integer\n 5 = Boolean\n 6 = Not null\n 7 = array\n ********************************************* */\n\nconst { get } = require('lodash')\n\nconst system = require('./system')\n\nfunction schemaValidator(schema, config, strategy = '') {\n const skip = []\n const schemaTraversed = system.traverse([], schema)\n const ignore = (key, value) => {\n let byPass = null\n\n key = strategy + key\n if (/\\.enabled/.test(key) && typeof value === 'boolean' && !value) {\n skip.push(key.split('.enabled')[0])\n }\n\n skip.forEach((disabled) => {\n byPass = !!key.includes(disabled)\n })\n\n return byPass\n }\n\n schemaTraversed.forEach((item) => {\n const value = get(config, item.key)\n let crash = false\n let msg = 'not null'\n\n if (ignore(item.key, value)) return\n if (/[0126]/.test(item.type) && value == null) crash = true\n switch (item.type) {\n // String\n case 0:\n /* falls through */\n\n case 3:\n msg = 'string'\n crash = typeof value !== msg\n break\n\n // Integer\n case 1:\n /* falls through */\n\n case 4:\n msg = 'number'\n crash = typeof value !== msg\n break\n\n // Boolean\n case 2:\n /* falls through */\n\n case 5:\n msg = 'boolean'\n crash = typeof value !== msg\n break\n\n // Array\n case 7:\n msg = 'array'\n try {\n // If not array, it'll fail\n // noinspection JSObjectNullOrUndefined\n value.push('isThisArray?')\n value.pop()\n } catch (e) {\n crash = true\n }\n\n break\n\n default:\n break\n }\n\n if (crash) {\n system.crash(\n 'Parse of cy-runner.yml failed',\n `${strategy}${item.key} must be ${msg}`\n )\n }\n })\n}\n\nexports.validateConfig = (config) => {\n const BASE_SCHEMA = {\n base: {\n secrets: {\n enabled: 2,\n name: 0,\n },\n vtex: {\n account: 0,\n id: 4,\n domain: 0,\n },\n cypress: {\n devMode: 2,\n runHeaded: 2,\n getCookies: 2,\n maxJobs: 1,\n quiet: 2,\n projectId: 0,\n video: 2,\n videoCompression: 6,\n videoUploadOnPasses: 2,\n screenshotOnRunFailure: 2,\n trashAssetsBeforeRuns: 2,\n viewportWidth: 1,\n viewportHeight: 1,\n defaultCommandTimeout: 1,\n requestTimeout: 1,\n watchForFileChanges: 2,\n pageLoadTimeout: 1,\n browser: 0,\n chromeWebSecurity: 2,\n },\n jira: { enabled: 2, account: 0, board: 0, issueType: 0 },\n slack: { enabled: 2, channel: 3 },\n stateFiles: 7,\n },\n workspace: {\n name: 3,\n prefix: 0,\n linkApp: {\n enabled: 2,\n },\n installApps: 7,\n removeApps: 7,\n wipe: { enabled: 2, stopOnFail: 2, specs: 7 },\n teardown: { enabled: 2 },\n },\n }\n\n const STRATEGY_SCHEMA = {\n enabled: 2,\n sendDashboard: 2,\n stopOnFail: 2,\n parallel: 2,\n hardTries: 1,\n specs: 7,\n }\n\n // Validate base\n schemaValidator(BASE_SCHEMA, config)\n\n // Validate test strategies\n const configSchema = {}\n\n Object.entries(config.strategy).forEach((entry) => {\n configSchema[entry[0]] = entry[1]\n })\n Object.keys(configSchema).forEach((strategy) => {\n schemaValidator(STRATEGY_SCHEMA, configSchema[strategy], `${strategy}.`)\n })\n\n // Validate dependencies\n checkDependency(config)\n\n // All set, show the user a positive feedback\n return true\n}\n\nexports.validateSecrets = (secrets, config) => {\n try {\n if (config.base.secrets.enabled) {\n const VTEX_ATTRIBUTES = [\n 'apiKey',\n 'apiToken',\n 'authCookieName',\n 'robotMail',\n 'robotPassword',\n ]\n\n VTEX_ATTRIBUTES.forEach((att) => {\n checkSecret(`secrets.vtex.${att}`, secrets.vtex[att])\n })\n }\n } catch (e) {\n system.crash('This property is missing on your secrets', e)\n }\n}\n\n// Check secrets\nfunction checkSecret(key, value) {\n key = key.split('secrets.')[1]\n if (typeof value !== 'string') system.crash('This secret must be string', key)\n if (value.length <= 0) system.crash(\"This secret can't be null\", key)\n}\n\n// Check dependencies\nfunction checkDependency(config) {\n const dependencies = []\n const specs = []\n const missing = []\n\n // Get dependencies and all specs\n system.traverse([], config.strategy).forEach((item) => {\n if (/.dependency./.test(item.key)) dependencies.push(item.type)\n else if (/.spec.js/.test(item.type)) specs.push(item.type)\n })\n\n // Check if dependency is also a spec\n dependencies.forEach((item) => {\n if (!specs.includes(item)) missing.push(item)\n })\n\n if (missing.length) {\n const text = missing.length > 1 ? 'Dependencies' : 'Dependency'\n\n system.crash(`${text} missing on strategies`, JSON.stringify(missing))\n }\n}\n\n```" } ]
code_cy-runner_9510c066
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/report.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst logger = require('./logger')\nconst system = require('./system')\nconst cypress = require('./cypress')\n\nmodule.exports.report = async (control, config) => {\n logger.msgSection('Execution report')\n\n logger.msgOk('Execution time', true)\n\n for (const section in control.timing) {\n logger.msgPad(`${section.padEnd(30, '.')} ${control.timing[section]}`, true)\n }\n\n logger.newLine(1)\n\n if (config.base.cypress.devMode) {\n system.success('Hope your tests went well. See you soon!')\n } else {\n this.printSpecs(control)\n\n if (control.runUrl != null) cypress.showDashboard(control.runUrl)\n\n // Final result\n if (\n control.specsFailed?.length < 1 &&\n control.specsSkipped?.length < 1 &&\n control.specsPassed?.length > 0\n ) {\n system.success('The test ran successfully, well done!')\n } else {\n const url =\n 'https://www.notion.so/vtexhandbook/My-PR-got-failed-what-s-next'\n\n logger.msgSection(`[Notion documentation](${url})`, true)\n logger.msgOk(url, true)\n system.fail('The test failed! Please, check the artifacts.')\n }\n }\n}\n\nmodule.exports.printSpecs = (control) => {\n const items = [\n ['specsDisabled', 'Disabled', 'ok'],\n ['specsPassed', 'Successful', 'ok'],\n ['specsSkipped', 'Skipped', 'warn'],\n ['specsFailed', 'Failed', 'error'],\n ]\n\n items.forEach((item) => {\n const tests = control[item[0]]\n\n // eslint-disable-next-line vtex/prefer-early-return\n if (tests?.length > 0) {\n const str = tests.length > 1 ? 'specs' : 'spec'\n\n if (item[2] === 'ok') logger.msgOk(`${item[1]} ${str}`)\n if (item[2] === 'warn') logger.msgWarn(`${item[1]} ${str}`)\n if (item[2] === 'error') logger.msgError(`${item[1]} ${str}`)\n tests.sort()\n tests.forEach((test) => {\n logger.msgPad(cypress.specNameClean(test))\n })\n\n logger.newLine(1)\n }\n })\n}\n\n```" } ]
code_cy-runner_103e7d31
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/toolbelt.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst system = require('./system')\nconst logger = require('./logger')\n\nconst MAX_RETRIES = 3\n\n// Get user, email and workspace name\nexports.whoami = async () => {\n const VTEX = await system.vtexBin()\n let stdout = null\n let check = false\n let thisTry = 1\n\n while (thisTry <= MAX_RETRIES && !check) {\n stdout = system.exec(`${VTEX} whoami`, 'pipe').toString()\n check = /Logged/.test(stdout)\n thisTry++\n }\n\n const mailOrKey = check ? stdout.split(' ')[7] : null\n const workspace = check ? stdout.split(' ')[11] : null\n\n return { isLogged: check, mailOrKey, workspace, stdout }\n}\n\n// Get local user token\nexports.getLocalToken = async () => {\n const VTEX = await system.vtexBin()\n const userOrRobot = await this.whoami()\n let result = null\n let token = null\n\n if (userOrRobot.isLogged) {\n let check = false\n let thisTry = 1\n\n while (thisTry <= MAX_RETRIES && !check) {\n result = system.exec(`${VTEX} local token`, 'pipe')\n token = result.slice(0, -1)\n check = /ey/.test(token)\n thisTry++\n }\n\n userOrRobot.token = token\n\n if (check) return userOrRobot\n }\n\n system.crash(\n 'Failed to get local user token',\n 'Are you logged on VTEX Toolbelt?'\n )\n}\n\n// Crash app if on master\nexports.crashIfMaster = async (msg) => {\n const check = await this.whoami()\n\n if (check.workspace === 'master') {\n system.crash(`Failed to ${msg}`, `You can't ${msg} master workspace`)\n }\n}\n\nexports.deleteWorkspace = async (workspace) => {\n await this.crashIfMaster('delete')\n const VTEX = await system.vtexBin()\n\n const result = system.exec(`${VTEX} workspace delete -f ${workspace}`, 'pipe')\n const check = /successfully/.test(result)\n\n check\n ? logger.msgOk(`Workspace ${workspace} deleted`)\n : logger.msgPad(`Failed to delete workspace ${workspace}`)\n}\n\nexports.changeWorkspace = async (workspace) => {\n const VTEX = await system.vtexBin()\n let check = false\n let thisTry = 1\n\n while (thisTry <= MAX_RETRIES && !check) {\n system.exec(`${VTEX} workspace use ${workspace}`, 'pipe')\n // eslint-disable-next-line no-await-in-loop\n const result = await this.whoami()\n\n check = RegExp(result.workspace).test(workspace)\n thisTry++\n }\n\n return check\n}\n\nexports.ls = async () => {\n const VTEX = await system.vtexBin()\n\n return system.exec(`${VTEX} ls`, 'pipe').toString()\n}\n\nexports.dependency = async () => {\n const VTEX = await system.vtexBin()\n\n return system.exec(`${VTEX} deps ls`, 'pipe').toString()\n}\n\nexports.install = async (app) => {\n // Show list of apps to be installed\n app.forEach((a) => {\n logger.msgPad(a)\n })\n // Crash if on master\n await this.crashIfMaster('install apps')\n const VTEX = await system.vtexBin()\n\n // Install apps and count successfully ones\n const result = system.exec(`${VTEX} install ${app.join(' ')}`, 'pipe')\n const count = (result.match(/successfully/g) || []).length\n\n // Feedback\n count === app.length\n ? logger.msgOk(`${count} of ${app.length} apps installed`)\n : logger.msgError(`${count} of ${app.length} apps installed`)\n\n // Return success if the count matches apps requested to install\n return { success: count === app.length, log: result }\n}\n\nexports.uninstall = async (app) => {\n // Show list of apps to be installed\n app.forEach((a) => {\n logger.msgPad(a)\n })\n // Crash if on master\n await this.crashIfMaster('uninstall apps')\n const VTEX = await system.vtexBin()\n\n // Install apps and count successfully ones\n const result = system.exec(`${VTEX} uninstall ${app.join(' ')}`, 'pipe')\n const count = (result.match(/successfully/g) || []).length\n\n // Feedback\n count === app.length\n ? logger.msgOk(`${count} of ${app.length} apps uninstalled`)\n : logger.msgError(`${count} of ${app.length} apps uninstalled`)\n\n // Return success if the count matches apps requested to uninstall\n return { success: count === app.length, log: result }\n}\n\nexports.link = async (logFile) => {\n const VTEX = await system.vtexBin()\n\n return system.spawn(VTEX, ['link', '--verbose'], logFile, system.basePath())\n}\n\n```" } ]
code_cy-runner_09bc7388
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/cypress.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst path = require('path')\n\nconst cypress = require('cypress')\nconst { merge } = require('lodash')\nconst jsYaml = require('js-yaml')\n\nconst storage = require(`./storage`)\nconst system = require('./system')\nconst logger = require('./logger')\nconst workspace = require('./workspace')\n\n// Get Cypress Folder [cypress or cypress-shared]\nexports.getCypressFolder = () => {\n return storage.exists(path.join(system.basePath(), 'cypress', 'integration'))\n ? 'cypress'\n : 'cypress-shared'\n}\n\n// Save Env for Cypress\nexports.saveCypressEnvJson = (config) => {\n storage.writeJson(\n config,\n path.join(system.cyRunnerPath(), 'cypress.env.json')\n )\n}\n\n// Save config for Cypress\nexports.saveCypressJson = (config) => {\n storage.writeJson(\n {\n baseUrl: config.base.vtex.baseUrl,\n chromeWebSecurity: config.base.cypress.chromeWebSecurity,\n video: config.base.cypress.video,\n videoCompression: config.base.cypress.videoCompression,\n videoUploadOnPasses: config.base.cypress.videoUploadOnPasses,\n screenshotOnRunFailure: config.base.cypress.screenshotOnRunFailure,\n trashAssetsBeforeRuns: config.base.cypress.trashAssetsBeforeRuns,\n viewportWidth: config.base.cypress.viewportWidth,\n viewportHeight: config.base.cypress.viewportHeight,\n defaultCommandTimeout: config.base.cypress.defaultCommandTimeout,\n requestTimeout: config.base.cypress.defaultCommandTimeout,\n watchForFileChanges: config.base.cypress.watchForFileChanges,\n pageLoadTimeout: config.base.cypress.pageLoadTimeout,\n browser: config.base.cypress.browser,\n projectId: config.base.cypress.projectId,\n retries: 0,\n screenshotsFolder: 'logs/screenshots',\n videosFolder: 'logs/videos',\n },\n path.join(system.cyRunnerPath(), 'cypress.json')\n )\n}\n\n// Deal with stop on fail\nexports.stopOnFail = async (config, step, runUrl) => {\n logger.msgSection(`Stop on fail triggered by strategy ${step.strategy}`)\n\n step.specsPassed.sort()\n step.specsPassed.forEach((spec) => {\n logger.msgOk(this.specNameClean(spec))\n })\n\n logger.newLine()\n\n step.specsFailed.sort()\n step.specsFailed.forEach((spec) => {\n logger.msgError(this.specNameClean(spec))\n })\n\n await workspace.teardown(config)\n if (runUrl != null) this.showDashboard(runUrl)\n system.crash('Triggered stop on fail', step.strategy)\n}\n\n// Show URL for Cypress Dashboard or Sorry Cypress\nexports.showDashboard = (url) => {\n logger.msgSection(`[Cypress Dashboard](${url})`, true)\n logger.msgOk(url, true)\n}\n\n// Beauty spec name to show on logs\nexports.specNameClean = (spec) => {\n const clean = spec.replace('cypress/integration/', '')\n\n return clean.replace('cypress-shared/integration/', '')\n}\n\n// Open Cypress\nexports.open = async () => {\n logger.msgSection('Running in dev mode')\n\n const CY_FOLDER = this.getCypressFolder()\n const options = {\n config: {\n integrationFolder: `${CY_FOLDER}/integration`,\n supportFile: `${CY_FOLDER}/support`,\n fixturesFolder: `${CY_FOLDER}/fixtures`,\n pluginsFile: `${CY_FOLDER}/plugins/index.js`,\n downloadsFolder: `${CY_FOLDER}/downloads`,\n },\n }\n\n logger.msgWarn('Verity if the workspace has the Apps you need already')\n\n try {\n await cypress.open(options)\n } catch (e) {\n system.crash('Failed to open Cypress', e.message)\n }\n}\n\n// Run Cypress\nexports.run = async (test, config, addOptions = {}) => {\n // Mix Cypress base folder isn't allowed\n const SPEC_PATH = path.parse(test.specs[0]).dir\n const CY_FOLDER = this.getCypressFolder()\n\n // Build options\n let options = {\n config: {\n integrationFolder: SPEC_PATH,\n supportFile: `${SPEC_PATH.split(path.sep)[0]}/support`,\n fixturesFolder: `${CY_FOLDER}/fixtures`,\n pluginsFile: `${CY_FOLDER}/plugins/index.js`,\n downloadsFolder: `${CY_FOLDER}/downloads`,\n },\n spec: test.specs,\n headed: config.base.cypress.runHeaded,\n browser: config.base.cypress.browser,\n quiet: config.base.cypress.quiet,\n }\n\n const testToRun = []\n let maxJobs = 1\n\n // maxJobs = 0 --> running local without Sorry Cypress\n if (config.base.cypress.maxJobs) {\n options = tuneOptions(options, config)\n merge(options, addOptions)\n maxJobs = getMaxJobs(test, config)\n }\n\n // Mount parallel jobs\n for (let i = 0; i < maxJobs; i++) {\n testToRun.push(\n // eslint-disable-next-line no-loop-func\n cypress.run(options).then((result) => {\n const specsPassed = []\n const specsFailed = []\n\n // If Cypress fails, roll back the spec\n if (result.failures) {\n logger.msgError('Got error from Cypress')\n logger.msgPad(JSON.stringify(result))\n\n return { success: false, specsPassed, specsFailed, runUrl: null }\n }\n\n // Remove sensitive data and get runUrl\n delete result.config\n const { runUrl } = result\n\n // Return specs passed and failed\n result.runs.forEach((run) => {\n const logName = run.spec.name.replace('.js', '-result.yaml')\n const logFile = path.join(logger.logPath(), logName)\n const logFlow = {}\n\n logFlow[`epoc-${system.tick()}`] = result\n storage.append(jsYaml.dump(logFlow), logFile)\n\n if (run.stats.failures) specsFailed.push(run.spec.relative)\n else specsPassed.push(run.spec.relative)\n })\n\n return { success: true, specsPassed, specsFailed, runUrl }\n })\n )\n }\n\n try {\n return await Promise.all(testToRun)\n } catch (e) {\n await workspace.teardown(config)\n system.crash('Failed to run Cypress', e)\n }\n}\n\n// Tune options\nfunction tuneOptions(options, config) {\n const RUN_ID = process.env.GITHUB_RUN_ID ?? system.getId()\n const RUN_ATTEMPT = process.env.GITHUB_RUN_ATTEMPT ?? 1\n\n options.key = config.base.cypress.dashboardKey\n options.record = true\n options.ciBuildId = `${RUN_ID}-${RUN_ATTEMPT}`\n\n // Configure Cypress to use Sorry Cypress if not in CI\n if (!system.isCI()) process.env.CYPRESS_INTERNAL_ENV = 'development'\n\n return options\n}\n\n// Calculate max jobs\nfunction getMaxJobs(test, config) {\n let maxJobs = 1\n\n if (test.parallel) {\n maxJobs =\n test.specs.length < config.base.cypress.maxJobs\n ? test.specs.length\n : config.base.cypress.maxJobs\n }\n\n return maxJobs\n}\n\n```" } ]
code_cy-runner_4eecc523
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/wipe.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst logger = require('./logger')\nconst cypress = require('./cypress')\nconst test = require('./test')\n\nmodule.exports.wipe = async (config) => {\n const { wipe } = config.workspace\n\n // eslint-disable-next-line vtex/prefer-early-return\n if (wipe.enabled) {\n logger.msgOk('Wiping data')\n\n // Disable parallelism for wipe and increase verbosity\n logger.msgPad('Disabling parallelism')\n config.base.cypress.maxJobs = 0\n\n // Remove data\n logger.msgPad('Running wipe')\n const xvfb = await test.startXvfb()\n const results = await cypress.run(wipe, config)\n\n await test.stopXvfb(xvfb)\n let success = false\n\n results.forEach((result) => {\n if (result.success) if (!result.specsFailed?.length) success = true\n })\n\n success\n ? logger.msgOk('Data wiped successfully')\n : logger.msgError('Failed to wipe data')\n }\n}\n\n```" } ]
code_cy-runner_b7b4d200
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/jira.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst axios = require('axios')\n\nconst logger = require('./logger')\nconst system = require('./system')\n\nmodule.exports.issue = async (config, specsFailed, runUrl) => {\n logger.msgSection('Jira ticket automation', true)\n\n // If LOCAL, avoid any ticket creation\n if (!system.isCI()) {\n logger.msgWarn('Not on CI, skipping ticket creation')\n\n return\n }\n\n const {\n GITHUB_REPOSITORY,\n GITHUB_REF,\n GITHUB_RUN_ID,\n GITHUB_SERVER_URL,\n GITHUB_ACTOR,\n } = process.env\n\n const JIRA = config.base.jira\n const [, , GH_REF] = GITHUB_REF.split('/')\n const PR_URL = `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/${GH_REF}`\n const CY_URL = `https://dashboard.cypress.io/projects/${config.base.cypress.projectId}/runs`\n const RUN_URL = `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}`\n const IS_SCH = process.env.GITHUB_EVENT_NAME === 'schedule' ?? false\n const IS_DIS = process.env.GITHUB_EVENT_NAME === 'workflow_dispatch' ?? false\n const IS_PRN = /^-?\\d+$/.test(`${GH_REF}`)\n\n // If DISPATCH, avoid any ticket creation\n if (IS_DIS) {\n logger.msgWarn('It was triggered by dispatch, skipping ticket creation')\n\n return\n }\n\n // Jira - You can set config.base.jira.testing as true for tests\n // JIRA.board = JIRA.testing || IS_SCH ? 'ENGINEERS' : JIRA.board\n JIRA.board = 'ENGINEERS'\n const PR = IS_PRN ? `PR #${GH_REF}` : 'FORK'\n const SUMMARY = IS_SCH ? `SCHEDULE ${GITHUB_REPOSITORY}:` : `${PR}:`\n const JQL = `summary ~ '${SUMMARY}' AND project = '${JIRA.board}' AND statusCategory IN ('undefined', 'In Progress', 'To Do')`\n const PRIORITY = JIRA.priority ?? 'High'\n const JIRA_KEY = await searchIssue(JIRA.account, JIRA.authorization, JQL)\n\n // Prepare failures with links\n const FAILURES = []\n let MARKS = []\n\n if (typeof runUrl !== 'undefined') {\n MARKS = [\n {\n type: 'link',\n attrs: {\n href: `${runUrl}/test-results?statuses=[{\"value\":\"FAILED\",\"label\":\"FAILED\"}]`,\n },\n },\n ]\n }\n\n specsFailed.forEach((fail) => {\n FAILURES.push({\n type: 'text',\n text: `\\n==> ${fail}`,\n marks: MARKS,\n })\n })\n\n // Payload for ticket creation\n const ADD_ISSUE = JSON.stringify({\n fields: {\n project: {\n key: JIRA.board,\n },\n summary: `${SUMMARY} E2E test failed for ${GITHUB_REPOSITORY}`,\n description: {\n type: 'doc',\n version: 1,\n content: [\n {\n type: 'paragraph',\n content: [\n {\n type: 'text',\n text: 'E2E test ',\n },\n {\n type: 'text',\n text: `${SUMMARY}`,\n marks: [\n {\n type: 'link',\n attrs: {\n href: PR_URL,\n },\n },\n ],\n },\n {\n type: 'text',\n text: ` ${\n IS_PRN ? 'created' : 'authorized'\n } by ${GITHUB_ACTOR}; failed on\\n`,\n },\n ...FAILURES,\n ],\n },\n {\n type: 'paragraph',\n content: [\n {\n type: 'text',\n text: '\\nTo get more information about the errors, please take a look at ',\n },\n {\n type: 'text',\n text: `artifacts on GitHub Action`,\n marks: [\n {\n type: 'link',\n attrs: {\n href: RUN_URL,\n },\n },\n ],\n },\n {\n type: 'text',\n text: ' or ',\n },\n {\n type: 'text',\n text: `Cypress Dashboard`,\n marks: [\n {\n type: 'link',\n attrs: {\n href: CY_URL,\n },\n },\n ],\n },\n {\n type: 'text',\n text: '.',\n },\n ],\n },\n ],\n },\n issuetype: {\n name: JIRA.issueType,\n },\n // Priority - Lowest, Low, Medium, High, Highest\n priority: {\n name: PRIORITY,\n },\n // Bug priority - Must Fix, Should Fix, Unbreak Now\n customfield_10115: {\n value: 'Should Fix',\n },\n },\n update: {},\n })\n\n const CFG_ADD_ISSUE = {\n method: 'post',\n url: `https://${JIRA.account}.atlassian.net/rest/api/3/issue`,\n headers: {\n Authorization: `Basic ${JIRA.authorization}`,\n 'Content-Type': 'application/json',\n },\n params: {\n updateHistory: true,\n applyDefaultValues: false,\n },\n data: ADD_ISSUE,\n }\n\n // Payload for ticket update\n const UPDATE_ISSUE = JSON.stringify({\n body: {\n version: 1,\n type: 'doc',\n content: [\n {\n type: 'paragraph',\n content: [\n {\n type: 'text',\n text: 'E2E test for ',\n },\n {\n type: 'text',\n text: `${SUMMARY} ${GH_REF}`,\n marks: [\n {\n type: 'link',\n attrs: {\n href: PR_URL,\n },\n },\n ],\n },\n {\n type: 'text',\n text: ` failed again on:`,\n },\n ...FAILURES,\n ],\n },\n ],\n },\n visibility: null,\n })\n\n const CFG_UPDATE_ISSUE = {\n method: 'post',\n url: `https://${JIRA.account}.atlassian.net/rest/api/3/issue/${JIRA_KEY}/comment`,\n headers: {\n Authorization: `Basic ${JIRA.authorization}`,\n 'Content-Type': 'application/json',\n },\n data: UPDATE_ISSUE,\n }\n\n // Update or create the issue\n let CFG = null\n let MSG = null\n let KEY = null\n\n switch (JIRA_KEY) {\n case 'abort':\n logger.msgError('Error on the JQL')\n logger.msgPad(JQL)\n\n return\n\n case 'create':\n CFG = CFG_ADD_ISSUE\n MSG = 'create'\n break\n\n default:\n CFG = CFG_UPDATE_ISSUE\n MSG = 'update'\n }\n\n await axios(CFG)\n .then((response) => {\n const { key: ISSUE_KEY } = response.data\n\n KEY = typeof ISSUE_KEY === 'undefined' ? JIRA_KEY : ISSUE_KEY\n const URL = `https://${JIRA.account}.atlassian.net/browse/${KEY}`\n\n logger.msgOk(`Issue ${KEY} ${MSG}d`, true)\n logger.msgPad(URL, true)\n })\n .catch((e) => {\n logger.msgError(`Failed to ${MSG} issue`, true)\n logger.msgPad(e, true)\n })\n}\n\n// Search issues on Jira\nasync function searchIssue(account, authorization, jiraJQL) {\n let key = null\n\n // Configuration\n const CFG = {\n method: 'get',\n url: `https://${account}.atlassian.net/rest/api/3/search`,\n headers: {\n Authorization: `Basic ${authorization}`,\n 'Content-Type': 'application/json',\n },\n params: {\n jql: jiraJQL,\n startAt: 0,\n maxResults: 2,\n },\n }\n\n await axios(CFG)\n .then((response) => {\n if (response.data.total === 1) {\n key = response.data.issues[0].key\n logger.msgOk(`Opened issue ${key} found`)\n } else if (response.data.total > 1) {\n key = 'abort'\n logger.msgError('More than one issue found')\n logger.msgPad(jiraJQL)\n } else {\n key = 'create'\n logger.msgWarn('A new issue will be created')\n }\n })\n .catch((e) => {\n logger.msgError('Querying Jira API')\n logger.msgPad(e)\n })\n\n return key\n}\n\n```" } ]
code_cy-runner_08ba57bf
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/http.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst axios = require('axios')\n\nconst system = require('./system')\n\nexports.request = async (axiosConfig) => {\n let response\n\n await axios(axiosConfig)\n .then((result) => {\n response = result\n })\n .catch((e) => {\n system.crash('Request failed', JSON.stringify(e.response.data))\n })\n\n return response\n}\n\nexports.runningSorryCypress = async () => {\n let response\n const axiosConfig = {\n url: 'http://localhost:1234',\n method: 'get',\n }\n\n await axios(axiosConfig)\n .then((result) => {\n response = result\n })\n .catch((_e) => {\n return false\n })\n\n return response?.status === 200\n}\n\n```" } ]
code_cy-runner_6d74999c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/lock.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst cfg = require('./config')\nconst logger = require('./logger')\nconst system = require('./system')\nconst storage = require('./storage')\nconst credentials = require('./credentials')\nconst toolbelt = require('./toolbelt')\nconst http = require('./http')\n\nconst [, , action] = process.argv\nconst MAX_TIME = 40 // Forced releasing time for stuck workspace (minutes)\n\nasync function checkAccount() {\n logger.init()\n logger.msgSection('Cypress Runner - Handle account level resources')\n const config = storage.readYaml('cy-runner.yml')\n const secrets = credentials.readSecrets(config)\n // eslint-disable-next-line global-require,import/no-self-import\n const lock = require('./lock')\n\n if (action === 'reserve') return lock.reserveAccount(config, secrets)\n if (action === 'release') return lock.releaseAccount(config, secrets)\n\n system.crash(\n `You must call me with 'reserve' or 'release' action`,\n `./cy-runner/node/lock ( reserve | release )`\n )\n}\n\nexports.reserveAccount = async (config, secrets = null) => {\n // If from action, show next section\n if (action) logger.msgSection('Reserve account level resources')\n\n logger.msgOk(`Checking current configuration`)\n // Check current configuration\n const orderFormCfg = await getOrderFormConfig(config, secrets)\n\n // Save results to be used later\n config.data = orderFormCfg.data\n\n // Check\n if (orderFormCfg.startTime) {\n // Yes, get the time running in seconds\n const ranTime = (Date.now() - orderFormCfg.startTime) / 1000 / 60\n\n if (ranTime < MAX_TIME) {\n // Test running less than 40 minutes, try again later\n logger.msgError('Another test is running', true)\n system.crash(\n `Account ${config.base.vtex.account} was reserved to ${orderFormCfg.workspace}`,\n `Please, try again in ${Math.floor(MAX_TIME - ranTime)} minutes`,\n { pr: true, dump: false }\n )\n } else {\n // Test running more than 40 minutes or appId miss configured\n logger.msgPad(\n `Workspace ${orderFormCfg.workspace} stuck [${Math.floor(\n ranTime\n )} minutes], releasing`\n )\n await this.releaseAccount(config, secrets)\n }\n }\n\n // Set up base info\n config.workspace.name = await cfg.getWorkspaceName(config)\n const { account } = config.base.vtex\n\n // Reserve app\n logger.msgOk(`Reserving ${account} to ${config.workspace.name}`)\n config.data.apps.push({\n fields: [config.workspace.name, Date.now()],\n id: 'e2e',\n major: 1,\n })\n await setOrderFormConfig(config, secrets)\n\n // Set up other reservations\n await setAppConfig(config, secrets)\n\n // If we reach here, everything is good\n logger.msgOk('Requested successfully')\n}\n\nexports.releaseAccount = async (config, secrets = null) => {\n // If from action, show start section\n if (action) logger.msgSection('Release account level resources')\n\n logger.msgOk('Releasing account level resources')\n const orderFormCfg = await getOrderFormConfig(config, secrets)\n\n config.data = orderFormCfg.data\n config.data.apps.splice(orderFormCfg.appId, 1)\n config.data.taxConfiguration = {}\n await setOrderFormConfig(config, secrets)\n logger.msgOk('Released successfully')\n}\n\nasync function getOrderFormConfig(config, secrets = null) {\n logger.msgPad('getting orderForm configuration')\n if (!secrets) secrets = config.base\n const { account } = config.base.vtex\n const axiosConfig = {\n url: `https://${account}.vtexcommercestable.com.br/api/checkout/pvt/configuration/orderForm`,\n method: 'get',\n headers: {\n 'X-VTEX-API-AppKey': secrets.vtex.apiKey,\n 'X-VTEX-API-AppToken': secrets.vtex.apiToken,\n },\n }\n\n const result = await http.request(axiosConfig)\n const appId = result?.data?.apps?.findIndex((app) => app.id === 'e2e')\n const workspace = appId >= 0 ? result?.data?.apps[appId]?.fields[0] : null\n const startTime = appId >= 0 ? result?.data?.apps[appId]?.fields[1] : null\n\n return { startTime, workspace, appId, data: result?.data }\n}\n\nasync function setOrderFormConfig(config, secrets) {\n logger.msgPad('setting orderForm configuration')\n if (!secrets) secrets = config.base\n const { account } = config.base.vtex\n const url = `https://${account}.vtexcommercestable.com.br/api/checkout/pvt/configuration/orderForm`\n const headers = {\n 'X-VTEX-API-AppKey': secrets.vtex.apiKey,\n 'X-VTEX-API-AppToken': secrets.vtex.apiToken,\n }\n\n const axiosConfig = { url, method: 'post', headers, data: config.data }\n const result = await http.request(axiosConfig)\n\n if (!/20./.test(result?.status)) {\n system.crash(\n 'Failed to set up orderForm configuration',\n `HTTP status: ${result?.status}`\n )\n }\n}\n\nasync function setAppConfig(config, secrets) {\n logger.msgOk('Configuring apps')\n if (!secrets) secrets = config.base\n const { account } = config.base.vtex\n const { prefix } = config.workspace\n const workspace = config.workspace.name\n const orderFormCfg = await getOrderFormConfig(config, secrets)\n const apps = config.workspace.reserveAccount.setup\n\n config.data = orderFormCfg.data\n for (const id in apps) {\n if (apps[id].toLowerCase() === 'orderform') {\n config.data.taxConfiguration = {\n url: `https://${workspace}--${account}.myvtex.com/${prefix}/checkout/order-tax`,\n authorizationHeader: secrets.vtex.authorizationHeader,\n allowExecutionAfterErrors: false,\n integratedAuthentication: false,\n appId: Date.now(),\n }\n // eslint-disable-next-line no-await-in-loop\n await setOrderFormConfig(config, secrets)\n } else if (apps[id].includes('@')) {\n logger.msgPad(`configuring ${apps[id]}`)\n const [app, version] = apps[id].split('@')\n const graphQLApp = 'vtex.apps-graphql@3.x'\n const url = `https://${account}.myvtex.com/_v/private/admin-graphql-ide/v0/${graphQLApp}`\n // eslint-disable-next-line no-await-in-loop\n const user = await toolbelt.getLocalToken()\n const headers = { Cookie: `${secrets.vtex.authCookieName}=${user.token}` }\n let check = null\n\n const query =\n 'mutation' +\n '($app:String, $version:String, $settings:String)' +\n '{saveAppSettings(app:$app, version:$version, settings:$settings){message}}'\n\n const variables = {\n app,\n version,\n settings: `{\"targetWorkspace\": \"${workspace}\"}`,\n }\n\n const axiosConfig = {\n url,\n method: 'post',\n headers,\n data: { query, variables },\n }\n\n try {\n // eslint-disable-next-line no-await-in-loop\n const result = await http.request(axiosConfig)\n\n check = RegExp(workspace).test(\n result?.data?.data?.saveAppSettings?.message\n )\n } catch (_e) {\n check = false\n }\n\n if (!check) {\n logger.msgError(`Failed to configure ${apps[id]}`, true)\n logger.msgPad('Releasing account level resources')\n // eslint-disable-next-line no-await-in-loop\n await this.releaseAccount(config, secrets)\n system.crash('Failed to configure app', apps[id])\n }\n }\n }\n}\n\n// If called outside cy-runner, let's deal with it\nif (action) checkAccount().then((r) => r)\n\n```" } ]
code_cy-runner_b3521015
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/node/storage.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst fs = require('fs')\nconst path = require('path')\n\nconst jsYaml = require('js-yaml')\n\nconst system = require('./system')\nconst logger = require('./logger')\nconst schema = require('./schema')\n\nexports.read = (file) => {\n try {\n return fs.readFileSync(file, { encoding: 'utf-8' })\n } catch (e) {\n system.crash(`Failed to read the ${file}`, e)\n }\n}\n\nexports.size = (file) => {\n try {\n return fs.statSync(file).size\n } catch (e) {\n system.crash(`Failed to get size of ${file}`, e)\n }\n}\n\nexports.copy = (source, destination) => {\n try {\n return fs.copyFileSync(source, destination)\n } catch (e) {\n system.crash(`Failed to copy ${source} to ${destination}`, e)\n }\n}\n\nexports.link = (source, destination) => {\n try {\n return fs.symlinkSync(source, destination)\n } catch (e) {\n system.crash(`Failed to link ${source} to ${destination}`, e)\n }\n}\n\nexports.unLink = (source) => {\n try {\n return fs.unlinkSync(source)\n } catch (e) {\n system.crash(`Failed to unlink ${source}`, e)\n }\n}\n\nexports.exists = (fileOrDirectory) => {\n try {\n return fs.existsSync(fileOrDirectory)\n } catch (e) {\n system.crash(`Failed to check ${fileOrDirectory}`, e)\n }\n}\n\nexports.append = (msg, file) => {\n try {\n return fs.appendFileSync(file, msg)\n } catch (e) {\n system.crash(`Failed to append ${msg} to ${file}`, e)\n }\n}\n\nexports.write = (msg, file) => {\n try {\n return fs.writeFileSync(file, msg)\n } catch (e) {\n system.crash(`Failed to create ${file}`, e)\n }\n}\n\nexports.delete = (file) => {\n try {\n if (this.exists(file)) return fs.rmSync(file, { recursive: true })\n } catch (e) {\n system.crash(`Failed to delete ${file}`, e)\n }\n}\n\nexports.makeDir = (directory) => {\n try {\n if (!this.exists(directory)) return fs.mkdirSync(directory)\n } catch (e) {\n // TODO: Fix the error when got error creating logs folder\n // If the dir to be create = logs, the error will be in loop\n system.crash(`Failed to create ${directory}`, e)\n }\n}\n\nexports.readYaml = (jsonFile) => {\n try {\n return jsYaml.load(this.read(jsonFile, 'utf-8'))\n } catch (e) {\n system.crash(`Invalid JSON/YAML file: ${jsonFile}`, e)\n }\n}\n\nexports.loadConfig = (yamlFile) => {\n // Check if you are inside cy-runner\n logger.msgOk('Checking base path')\n if (this.exists('cy-runner')) {\n system.crash('Wrong start path', 'You must be inside cy-runner folder', {\n dump: false,\n })\n }\n\n // Fill full path for yaml config\n yamlFile = path.join(system.basePath(), yamlFile)\n const parentYamlFile = path.join(system.rootPath(), yamlFile)\n\n if (this.exists(parentYamlFile)) yamlFile = parentYamlFile\n if (!this.exists(yamlFile)) system.crash(`${yamlFile} not found`)\n\n try {\n const data = this.read(yamlFile)\n const config = jsYaml.load(data)\n\n schema.validateConfig(config)\n ? logger.msgPad(yamlFile.replace(system.rootPath(), '.'))\n : system.crash(`Unknown error loading ${yamlFile}`)\n\n return config\n } catch (e) {\n system.crash(`Invalid ${yamlFile.replace(system.rootPath(), '.')}`, e)\n }\n}\n\nexports.writeJson = (config, jsonFile) => {\n try {\n this.write(JSON.stringify(config), jsonFile)\n logger.msgPad(jsonFile.replace(system.basePath(), '.'))\n } catch (e) {\n system.crash(`Failed to create ${jsonFile}`, e)\n }\n}\n\nexports.createStateFiles = (config) => {\n try {\n const { stateFiles } = config.base\n const SIZE = stateFiles.length\n const PLURAL = SIZE > 1 ? 'files' : 'file'\n\n if (SIZE) {\n logger.msgOk(`Creating state ${PLURAL}`)\n stateFiles.forEach((stateFile) => {\n logger.msgPad(stateFile)\n this.write('{}', path.join(system.cyRunnerPath(), stateFile))\n })\n }\n } catch (e) {\n system.crash('Failed to create a state file', e)\n }\n}\n\n// ENGINEERS-465\nexports.keepStateFiles = (config) => {\n try {\n const { stateFiles } = config.base\n\n logger.msgWarn('Moving state files')\n stateFiles.forEach((stateFile) => {\n const SRC = path.join(system.cyRunnerPath(), stateFile)\n const DST = path.join(logger.logPath(), stateFile)\n\n logger.msgPad(`${stateFile} -> ${DST.replace(system.basePath(), '.')}`)\n\n this.copy(SRC, DST)\n })\n logger.msgOk('State files moved successfully')\n } catch (e) {\n system.crash('Failed to keep state files', e)\n }\n}\n\n```" } ]
code_cy-runner_62b71ac5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/test/cypress/plugins/index.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n// / <reference types=\"cypress\" />\n// ***********************************************************\n// This example plugins/index.js can be used to load plugins\n//\n// You can change the location of this file or turn off loading\n// the plugins file with the 'pluginsFile' configuration option.\n//\n// You can read more here:\n// https://on.cypress.io/plugins-guide\n// ***********************************************************\n\n// This function is called when a project is opened or re-opened (e.g. due to\n// the project's config changing)\n\n/**\n * @type {Cypress.PluginConfig}\n */\n// eslint-disable-next-line no-unused-vars\nmodule.exports = (on, config) => {\n // `on` is used to hook into various events Cypress emits\n // `config` is the resolved Cypress config\n}\n\n```" } ]
code_cy-runner_adc52645
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/test/cypress/integration/todo.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n// / <reference types=\"cypress\" />\n\n// Welcome to Cypress!\n//\n// This spec file contains a variety of sample tests\n// for a tod o list app that are designed to demonstrate\n// the power of writing tests in Cypress.\n//\n// To learn more about how Cypress works and\n// what makes it such an awesome testing tool,\n// please read our getting started guide:\n// https://on.cypress.io/introduction-to-cypress\n\ndescribe('example to-do app', () => {\n beforeEach(() => {\n // Cypress starts out with a blank slate for each test\n // so we must tell it to visit our website with the `cy.visit()` command.\n // Since we want to visit the same URL at the start of all our tests,\n // we include it in our beforeEach function so that it runs before each test\n cy.visit('https://example.cypress.io/todo')\n })\n\n it('displays two todo items by default', () => {\n // We use the `cy.get()` command to get all elements that match the selector.\n // Then, we use `should` to assert that there are two matched items,\n // which are the two default items.\n cy.get('.todo-list li').should('have.length', 2)\n\n // We can go even further and check that the default todos each contain\n // the correct text. We use the `first` and `last` functions\n // to get just the first and last matched elements individually,\n // and then perform an assertion with `should`.\n cy.get('.todo-list li').first().should('have.text', 'Pay electric bill')\n cy.get('.todo-list li').last().should('have.text', 'Walk the dog')\n })\n\n it('can add new todo items', () => {\n // We'll store our item text in a variable so we can reuse it\n const newItem = 'Feed the cat'\n\n // Let's get the input element and use the `type` command to\n // input our new list item. After typing the content of our item,\n // we need to type the enter key as well in order to submit the input.\n // This input has a data-test attribute so we'll use that to select the\n // element in accordance with best practices:\n // https://on.cypress.io/selecting-elements\n cy.get('[data-test=new-todo]').type(`${newItem}{enter}`)\n\n // Now that we've typed our new item, let's check that it actually was added to the list.\n // Since it's the newest item, it should exist as the last element in the list.\n // In addition, with the two default items, we should have a total of 3 elements in the list.\n // Since assertions yield the element that was asserted on,\n // we can chain both of these assertions together into a single statement.\n cy.get('.todo-list li')\n .should('have.length', 3)\n .last()\n .should('have.text', newItem)\n })\n\n it('can check off an item as completed', () => {\n // In addition to using the `get` command to get an element by selector,\n // we can also use the `contains` command to get an element by its contents.\n // However, this will yield the <label>, which is lowest-level element that contains the text.\n // In order to check the item, we'll find the <input> element for this <label>\n // by traversing up the dom to the parent element. From there, we can `find`\n // the child checkbox <input> element and use the `check` command to check it.\n cy.contains('Pay electric bill')\n .parent()\n .find('input[type=checkbox]')\n .check()\n\n // Now that we've checked the button, we can go ahead and make sure\n // that the list element is now marked as completed.\n // Again we'll use `contains` to find the <label> element and then use the `parents` command\n // to traverse multiple levels up the dom until we find the corresponding <li> element.\n // Once we get that element, we can assert that it has the completed class.\n cy.contains('Pay electric bill')\n .parents('li')\n .should('have.class', 'completed')\n })\n\n context('with a checked task', () => {\n beforeEach(() => {\n // We'll take the command we used above to check off an element\n // Since we want to perform multiple tests that start with checking\n // one element, we put it in the beforeEach hook\n // so that it runs at the start of every test.\n cy.contains('Pay electric bill')\n .parent()\n .find('input[type=checkbox]')\n .check()\n })\n\n it('can filter for uncompleted tasks', () => {\n // We'll click on the \"active\" button in order to\n // display only incomplete items\n cy.contains('Active').click()\n\n // After filtering, we can assert that there is only the one\n // incomplete item in the list.\n cy.get('.todo-list li')\n .should('have.length', 1)\n .first()\n .should('have.text', 'Walk the dog')\n\n // For good measure, let's also assert that the task we checked off\n // does not exist on the page.\n cy.contains('Pay electric bill').should('not.exist')\n })\n\n it('can filter for completed tasks', () => {\n // We can perform similar steps as the test above to ensure\n // that only completed tasks are shown\n cy.contains('Completed').click()\n\n cy.get('.todo-list li')\n .should('have.length', 1)\n .first()\n .should('have.text', 'Pay electric bill')\n\n cy.contains('Walk the dog').should('not.exist')\n })\n\n it('can delete all completed tasks', () => {\n // First, let's click the \"Clear completed\" button\n // `contains` is actually serving two purposes here.\n // First, it's ensuring that the button exists within the dom.\n // This button only appears when at least one task is checked\n // so this command is implicitly verifying that it does exist.\n // Second, it selects the button so we can click it.\n cy.contains('Clear completed').click()\n\n // Then we can make sure that there is only one element\n // in the list and our element does not exist\n cy.get('.todo-list li')\n .should('have.length', 1)\n .should('not.have.text', 'Pay electric bill')\n\n // Finally, make sure that the clear button no longer exists.\n cy.contains('Clear completed').should('not.exist')\n })\n })\n})\n\n```" } ]
code_cy-runner_973acd3a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/test/cypress/support/index.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n// ***********************************************************\n// This example support/index.js is processed and\n// loaded automatically before your test files.\n//\n// This is a great place to put global configuration and\n// behavior that modifies Cypress.\n//\n// You can change the location of this file or turn off\n// automatically serving support files with the\n// 'supportFile' configuration option.\n//\n// You can read more here:\n// https://on.cypress.io/configuration\n// ***********************************************************\n\n// Import commands.js using ES2015 syntax:\nimport './commands'\n\n// Alternatively you can use CommonJS syntax:\n// require('./commands')\n\n```" } ]
code_cy-runner_46c1b19f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/test/cypress/support/commands.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n// ***********************************************\n// This example commands.js shows you how to\n// create various custom commands and overwrite\n// existing commands.\n//\n// For more comprehensive examples of custom\n// commands please read more here:\n// https://on.cypress.io/custom-commands\n// ***********************************************\n//\n//\n// -- This is a parent command --\n// Cypress.Commands.add('login', (email, password) => { ... })\n//\n//\n// -- This is a child command --\n// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })\n//\n//\n// -- This is a dual command --\n// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })\n//\n//\n// -- This will overwrite an existing command --\n// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })\n\n```" } ]
code_cy-runner_55c4ba27
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/test/cypress/fixtures/example.json from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Using fixtures to represent data\",\n \"email\": \"hello@cypress.io\",\n \"body\": \"Fixtures are a great way to mock data for responses to routes\"\n}\n\n```" } ]
code_cy-runner_f1cfec5d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/plugins/index.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst readXlsx = require('./read-xlsx.js')\n\nmodule.exports = (on) => {\n on('task', {\n readXlsx: readXlsx.read,\n })\n}\n\n```" } ]
code_cy-runner_69730cfc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/plugins/read-xlsx.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst fs = require('fs')\n\nconst XLSX = require('xlsx')\n\nconst read = ({ file, sheet }) => {\n const buf = fs.readFileSync(file)\n const workbook = XLSX.read(buf, { type: 'buffer' })\n\n return XLSX.utils.sheet_to_json(workbook.Sheets[sheet])\n}\n\nmodule.exports = {\n read,\n}\n\n```" } ]
code_cy-runner_b4256989
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/support/graphql_operations.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport const GRAPHL_OPERATIONS = {\n CreateOrganizationRequest: 'CreateOrganizationRequest',\n GetUsers: 'GetUsers',\n GetCostCentersByOrganizationIdStorefront:\n 'GetCostCentersByOrganizationIdStorefront',\n GetCostCenterStorefront: 'GetCostCenterStorefront',\n addToCart: 'addToCart',\n CreateQuote: 'CreateQuote',\n UpdateQuote: 'UpdateQuote',\n GetQuotes: 'GetQuotes',\n ImpersonateUser: 'ImpersonateUser',\n Session: 'Session',\n GetOrderForm: 'GetOrderForm',\n CheckImpersonation: 'ViewLists',\n Autocomplete: 'Autocomplete',\n}\n\n```" } ]
code_cy-runner_6f382993
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/support/validation_text.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport const TOAST_MSG = {\n added: /added/i,\n updated: /updated/i,\n deleted: /deleted/i,\n addedToTheCart: /added to the cart/i,\n initializing: /initializing/i,\n impersonatePermissionError: /do not have permission to impersonate/i,\n userAlreadyRegisteredInThisOrganization: /this organization/,\n}\n\nexport const BUTTON_LABEL = {\n create: /create/i,\n remove: /Remove/i,\n cancel: /cancel/i,\n save: /save/i,\n delete: /delete/i,\n back: /back/i,\n completeOrder: /Complete Order/i,\n AddToCart: /Add to Cart/i,\n QuickOrder: /Quick Order/i,\n QuoteDetails: 'Quote Details',\n}\n\n```" } ]
code_cy-runner_f06edd02
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/support/index.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport './common/commands'\nimport './b2b/env_organization'\nimport './b2b/env_quotes'\nimport './commands'\nimport './common/api_commands'\nimport './common/env_orders'\n\n// Configure it to preserve cookies\nCypress.Cookies.defaults({\n preserve: /VtexIdclientAutCookie$|JSESSIONID/,\n})\n\nCypress.on('uncaught:exception', (_, __) => {\n return false\n})\n\n// Reference:https://stackoverflow.com/questions/48661153/cypress-seems-to-have-stalled\n// We are using below code in affirm payment\nCypress.on('window:before:load', (win) => {\n if (win.location.href.includes('sandbox')) {\n Object.defineProperty(win, 'self', {\n get: () => {\n return window.top\n },\n })\n }\n})\n\n```" } ]
code_cy-runner_e1351d42
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/support/extract.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst GmailAPI = require('./common/gmail')\n\nconst delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n\nfunction extractAccessCode(message) {\n if (message) {\n const regex = /<strong>(\\d.*)<\\/strong>/\n\n return message.includes('access code') ? message.match(regex)[1] : '0'\n }\n\n return '0'\n}\n\nexport async function getAccessToken(email, gmailCreds, accessToken = null) {\n const gmail = new GmailAPI(gmailCreds)\n const ToEmail = email.replace('+', '%2B')\n let currentAccessToken\n const totalRetry = 8\n\n await gmail.getAcceToken(gmailCreds)\n\n /* eslint-disable no-await-in-loop */\n for (let currentRetry = 0; currentRetry <= totalRetry; currentRetry++) {\n currentAccessToken = extractAccessCode(\n await gmail.readInboxContent(\n new URLSearchParams(\n `from:noreply@vtexcommerce.com.br+to:${ToEmail}`\n ).toString(),\n gmailCreds\n )\n )\n if (accessToken === null || currentAccessToken !== accessToken) {\n return currentAccessToken\n }\n\n await delay(5500)\n }\n}\n\n```" } ]
code_cy-runner_a48ea489
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/support/commands.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport selectors from './common/selectors.js'\nimport {\n searchInMasterData,\n deleteDocumentInMasterData,\n} from './common/wipe.js'\nimport { performImpersonation } from './b2b/common.js'\nimport 'cypress-file-upload'\nimport { fillContactInfo, scroll } from './common/support.js'\n\nfunction closeModalIfOpened() {\n cy.get('body').then(($body) => {\n if ($body.find('div[class*=vtex-modal__close]').length) {\n cy.qe(`Some modal been opened in the page. Let's close it`)\n cy.get('div[class*=vtex-modal__close]').click()\n }\n })\n}\n\nCypress.Commands.add('closeMenuIfOpened', () => {\n cy.addDelayBetweenRetries(5000)\n cy.get('button[class*=closeIconButton]').then(($el) => {\n if (Cypress.dom.isVisible($el)) {\n cy.get('button[class*=closeIconButton]').first().click()\n }\n })\n})\n\nCypress.Commands.add('searchInMasterData', searchInMasterData)\nCypress.Commands.add('deleteDocumentInMasterData', deleteDocumentInMasterData)\nCypress.Commands.add('performImpersonation', performImpersonation)\n\nCypress.Commands.add('waitForSession', (selector = null) => {\n cy.qe('Wait for the Session to be called in the page')\n cy.getVtexItems().then((vtex) => {\n cy.intercept('POST', `${vtex.baseUrl}/**`, (req) => {\n if (req.body.operationName === 'Session') {\n req.continue()\n }\n }).as('Session')\n\n if (selector) {\n cy.qe(`Click this ${selector}`)\n cy.get(selector).last().click()\n }\n\n cy.wait('@Session', { timeout: 20000 })\n })\n})\n\nCypress.Commands.add(\n 'waitForGraphql',\n (operationName, selector = null, contains = null, timeout = 30000) => {\n cy.getVtexItems().then((vtex) => {\n cy.intercept('POST', `${vtex.baseUrl}/**`, (req) => {\n if (req.body.operationName === operationName) {\n req.continue()\n }\n }).as(operationName)\n\n if (selector && contains) {\n cy.scrollTo('top')\n cy.qe(`Click the button which has content ${selector} in it`)\n cy.contains(selector).should('be.visible').click()\n } else if (selector) {\n cy.qe(`Click the button which has selector ${selector} in it`)\n cy.get(selector).should('be.visible').last().click()\n } else if (contains) {\n cy.qe(`Click the button which has content ${contains} in it`)\n cy.contains(contains).should('be.visible').click()\n }\n\n cy.qe(\n `Wait for this graphql operation ${operationName} to be called in the page`\n )\n cy.wait(`@${operationName}`, { timeout })\n })\n }\n)\n\nCypress.Commands.add('fillAddressInCostCenter', (costCenter) => {\n const { country, postalCode, street, receiverName } = costCenter\n\n cy.qe(`For country dropdown, select ${country}`)\n cy.get(selectors.Country).should('not.be.disabled').select(country)\n cy.intercept('GET', `**/${postalCode}`).as('POSTALCODE')\n cy.qe(`For postalCode field, type ${postalCode}`)\n cy.get(selectors.PostalCode)\n .clear()\n .type(postalCode, { delay: 30 })\n .should('have.value', postalCode)\n cy.wait('@POSTALCODE')\n cy.qe(`For street field, type ${street}`)\n cy.get(selectors.Street)\n .clear()\n .type(street, { delay: 20 })\n .should('have.value', street)\n cy.qe(`Check state field is autofilled and not empty`)\n cy.get(selectors.State).invoke('val').should('not.be.empty')\n cy.qe(`Check city field is autofilled and not empty`)\n cy.get(selectors.City).invoke('val').should('not.be.empty')\n cy.qe(`For receiverName field, clear and type ${receiverName}`)\n cy.get(selectors.ReceiverNameinB2B)\n .clear()\n .type(receiverName)\n .should('have.value', receiverName)\n})\n\nCypress.Commands.add(\n 'gotoMyOrganization',\n (waitforSession = true, salesRepOrManager = false) => {\n cy.qe('ProfileLabel should be visible')\n cy.get(selectors.ProfileLabel).should('be.visible')\n\n cy.url().then((url) => {\n if (!url.includes('account')) {\n cy.qe('We are not in account page')\n cy.qe('Click SignInBtn')\n cy.get(selectors.SignInBtn).click()\n cy.qe('Click MyAccount')\n cy.get(selectors.MyAccount).click()\n if (waitforSession) cy.waitForSession()\n }\n\n closeModalIfOpened()\n cy.qe('Click MyOrganization link')\n cy.get(selectors.MyOrganization, { timeout: 40000 })\n .should('be.visible')\n .click()\n const noOfdivision = salesRepOrManager ? 2 : 4\n\n cy.qe(\n `This selector ${selectors.MyOrganizationCostCenterUserDiv} should have length ${noOfdivision} in current page`\n )\n\n cy.get(selectors.MyOrganizationCostCenterUserDiv).should(\n 'have.length',\n noOfdivision\n )\n })\n }\n)\nCypress.Commands.add('gotoCostCenter', (costCenter) => {\n cy.get('body').then(($body) => {\n if ($body.find('div[class*=pageHeader__title]').length) {\n cy.get('div[class*=pageHeader__title]')\n .invoke('text')\n .then((text) => {\n if (!text.includes('Cost Center')) {\n cy.qe('Cost Center text is not found in the page')\n cy.qe(\"So, let's open the costCenter\")\n cy.contains(costCenter).click()\n } else {\n cy.qe('Already in costcenter page')\n }\n })\n }\n })\n})\n\nCypress.Commands.add('gotoMyQuotes', () => {\n cy.get(selectors.ProfileLabel, { timeout: 20000 }).should('be.visible')\n cy.scrollTo('top')\n cy.get('body').then(($body) => {\n if (!$body.find(selectors.ToggleFields).length) {\n cy.get(selectors.MyQuotes, { timeout: 10000 })\n .should('be.visible')\n .click()\n }\n })\n cy.get(selectors.QuotesToolBar, { timeout: 20000 }).should('be.visible')\n})\n\nCypress.Commands.add('gotoQuickOrder', (b2b = false) => {\n cy.location().then((loc) => {\n let closeMenu = false\n\n if (loc.pathname.includes('quickorder')) closeMenu = true\n if (b2b) {\n closeMenu && cy.closeMenuIfOpened()\n cy.get(selectors.Menu).should('be.visible').click()\n cy.get(selectors.QuickOrder).should('be.visible').click()\n } else {\n cy.qe(\n 'Visit the QuickOrder home page: if the profile label is visible, then the profile label should contain Hello'\n )\n cy.visit('/quickorder')\n cy.get(selectors.ProfileLabel, { timeout: 20000 })\n .should('be.visible')\n .should('have.contain', `Hello,`)\n }\n\n cy.qe(`The Url should contain quickorder`)\n cy.url().should('include', 'quickorder')\n })\n})\n\nCypress.Commands.add('searchProductinB2B', (product, available = true) => {\n cy.url().then((url) => {\n if (url.includes('checkout')) {\n cy.visit('/')\n }\n\n cy.get(selectors.ProfileLabel).should('be.visible')\n // Search product in search bar\n cy.get(selectors.Search)\n .first()\n .should('be.visible')\n .should('be.enabled')\n .clear()\n .type(product, { force: true })\n .type('{enter}', { force: true })\n if (available) {\n cy.get(selectors.searchResult).should('be.visible')\n cy.get('article div[class*=storefront-permissions-ui]')\n .should('be.visible')\n .first()\n .scrollIntoView()\n }\n })\n})\n\nCypress.Commands.add('checkStatusAndReject', (expectedStatus) => {\n cy.get(selectors.QuoteStatus)\n .first()\n .invoke('text')\n .then((currentStatus) => {\n if (currentStatus === expectedStatus) return cy.wrap(false)\n\n return cy.wrap(true)\n })\n})\n\nCypress.Commands.add(\n 'checkAndFillData',\n (selector, expectedText, position = 0) => {\n cy.get(selector)\n .eq(position)\n .invoke('val')\n .then((text) => {\n if (text !== expectedText) {\n cy.get(selector).eq(position).clear().type(expectedText)\n\n return cy.wrap(true)\n }\n\n return cy.wrap(false)\n })\n }\n)\n\nCypress.Commands.add('orderProduct', () => {\n cy.qe('Fill contact information in checkout page')\n cy.get(selectors.FirstName).then(($el) => {\n if (Cypress.dom.isVisible($el)) {\n fillContactInfo()\n }\n })\n cy.qe('To make payment select Promissory payment')\n cy.get(selectors.PromissoryPayment).should('be.visible').click()\n cy.get(selectors.BuyNowBtn).last().should('be.visible').click()\n cy.get(selectors.Search, { timeout: 30000 }).should('be.visible')\n})\n\nCypress.Commands.add('openStoreFront', (login = false) => {\n cy.intercept('**/event-api/v1/*/event').as('events')\n cy.qe('Visit store front')\n cy.visit('/')\n cy.wait('@events')\n if (login === true) {\n cy.get(selectors.ProfileLabel, { timeout: 20000 })\n .should('be.visible')\n .should('have.contain', `Hello,`)\n }\n\n scroll()\n})\n\nCypress.Commands.add(\n 'addNewLocation',\n (country, postalCode, street, city, retypePostalCode = false) => {\n cy.openStoreFront()\n cy.qe(\n 'Address container should be visible in the top left of the home page'\n )\n cy.get(selectors.addressContainer, { timeout: 30000 })\n .should('be.visible')\n .click()\n cy.qe('Select a country')\n cy.get(selectors.countryDropdown).select(country)\n cy.qe('Type a postalcode')\n cy.get(selectors.addressInputContainer)\n .first()\n .clear()\n .should('be.visible')\n .type(postalCode, { delay: 10 })\n cy.get(selectors.SaveButtonInChangeLocationPopUp).should('be.visible')\n cy.qe('Type street address in address input')\n cy.get(selectors.Address)\n .contains('Address Line 1')\n .parent()\n .within(() => {\n cy.get(selectors.InputText).should('be.visible').clear().type(street)\n })\n cy.qe('Type a city')\n cy.get(selectors.Address)\n .contains('City')\n .parent()\n .within(() => {\n cy.get(selectors.InputText).should('be.visible').clear().type(city)\n })\n\n if (retypePostalCode) {\n cy.get(selectors.addressInputContainer)\n .first()\n .clear()\n .should('be.visible')\n .type(postalCode, { delay: 10 })\n }\n\n cy.waitForGraphql('setRegionId', selectors.SaveButtonInChangeLocationPopUp)\n cy.once('uncaught:exception', () => false)\n }\n)\n\nCypress.Commands.add(\n 'openProduct',\n (product, detailPage = false, searchPage = false) => {\n // Search product in search bar\n cy.get(selectors.Search).should('be.not.disabled').should('be.visible')\n cy.qe('Search product in search bar')\n cy.get(selectors.Search)\n .should('be.visible')\n .should('be.enabled')\n .clear()\n .type(product)\n .type('{enter}')\n // Page should load successfully now Filter should be visible\n cy.qe('Search result page should load successfully')\n cy.get(selectors.searchResult).should('have.text', product.toLowerCase())\n cy.get(selectors.FilterHeading, { timeout: 30000 }).should('be.visible')\n if (searchPage) {\n cy.qe(\n \"If the search page is true, then it should show the message 'Shipping: Unavailable for'\"\n )\n cy.get(selectors.locationUnavailable)\n .should('be.visible')\n .contains('Shipping: Unavailable for')\n }\n\n if (detailPage) {\n cy.qe('If detailPage is true,then it should go to product detail page')\n cy.gotoProductDetailPage()\n } else {\n cy.log('Visiting detail page is disabled')\n }\n }\n)\n\nfunction visitOrganizationPage() {\n cy.url().then((url) => {\n if (!url.includes('account')) {\n cy.get(selectors.ProfileLabel).should('be.visible')\n cy.get(selectors.SignInBtn).click()\n cy.get(selectors.MyAccount).click()\n cy.waitForSession()\n }\n\n closeModalIfOpened()\n cy.get('a[href*=\"profile\"]').should('be.visible')\n cy.get('a[href*=\"wishlist\"]').should('be.visible')\n cy.contains(selectors.QuotesAndSavedCarts).should('be.visible')\n })\n}\n\nCypress.Commands.add('organizationShouldNotShowInProfile', () => {\n visitOrganizationPage()\n cy.get(selectors.MyOrganization, { timeout: 20000 }).should('not.exist')\n})\n\nCypress.Commands.add('organizationShouldShowInProfile', () => {\n visitOrganizationPage()\n cy.get(selectors.MyOrganization, { timeout: 25000 }).should('be.visible')\n})\n\nconst fedexJson = 'fedexPayload.json'\n\nCypress.Commands.add('setAppSettingstoJSON', (key, value) => {\n cy.readFile(fedexJson).then((items) => {\n items[key] = value\n cy.writeFile(fedexJson, items)\n })\n})\n\nCypress.Commands.add('getAppSettingstoJSON', () => {\n cy.readFile(fedexJson).then((items) => {\n return items\n })\n})\n\nCypress.Commands.add('hideSla', (hide) => {\n cy.readFile(fedexJson).then((items) => {\n const { slaSettings } = items.config.data.getAppSettings\n\n for (const ship in slaSettings) {\n slaSettings[ship].hidden = hide\n }\n\n return slaSettings\n })\n})\n\nCypress.Commands.add('readSlaSettings', () => {\n cy.readFile(fedexJson).then((items) => {\n const { slaSettings } = items.config.data.getAppSettings\n\n return slaSettings\n })\n})\n\n```" } ]
code_cy-runner_b8e55f4b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/fixtures/pack.json from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"packed\": {\n \"ItemsToPack\": [\n {\n \"ID\": 1,\n \"Dim1\": 1,\n \"Dim2\": 1,\n \"Dim3\": 1,\n \"Quantity\": 1\n },\n {\n \"ID\": 2,\n \"Dim1\": 1,\n \"Dim2\": 2,\n \"Dim3\": 2,\n \"Quantity\": 1\n }\n ]\n }\n}\n\n```" } ]
code_cy-runner_5c5dbbdd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.4-discountProduct.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport {\n loginViaCookies,\n preserveCookie,\n} from '../../support/common/support.js'\nimport { discountProduct } from '../../support/adyen/outputvalidation'\nimport {\n getTestVariables,\n checkoutProduct,\n} from '../../support/common/testcase.js'\nimport { completePaymentWithDinersCard } from '../../support/adyen/testcase.js'\nimport selectors from '../../support/common/selectors.js'\n\nconst { prefix, total } = discountProduct\n\ndescribe(`${prefix} Scenarios`, () => {\n loginViaCookies()\n\n const { orderIdEnv } = getTestVariables(prefix)\n\n checkoutProduct(discountProduct)\n\n it(`In ${prefix} - Verifying total amounts and discount for a discounted product`, () => {\n // Verify Total\n cy.verifyTotal(total)\n // Verify Discounts\n cy.qe('Discounts should be visible')\n cy.get(selectors.Discounts).last().should('be.visible')\n })\n\n completePaymentWithDinersCard(prefix, orderIdEnv)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_a29c33e4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/wipe.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport {\n deleteAdyenWebhook,\n deleteAccountHoldersFromMasterData,\n} from '../../support/adyen/adyen_apis.js'\nimport { loginViaCookies } from '../../support/common/support.js'\nimport { setWorkspaceAndGatewayAffiliations } from '../../support/common/testcase.js'\n\ndescribe('Wipe Adyen in dynamic environment', () => {\n loginViaCookies()\n\n setWorkspaceAndGatewayAffiliations({ wipe: true })\n deleteAdyenWebhook()\n deleteAccountHoldersFromMasterData()\n})\n\n```" } ]
code_cy-runner_a7c18a1d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.7-promotionalProduct.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport {\n loginViaCookies,\n preserveCookie,\n updateRetry,\n} from '../../support/common/support.js'\nimport { promotionProduct } from '../../support/adyen/outputvalidation'\nimport {\n getTestVariables,\n checkoutProduct,\n} from '../../support/common/testcase'\nimport { completePaymentWithDinersCard } from '../../support/adyen/testcase.js'\n\ndescribe('Promotional Product scenarios', () => {\n loginViaCookies()\n\n const { prefix } = promotionProduct\n\n const { orderIdEnv } = getTestVariables(prefix)\n\n checkoutProduct(promotionProduct)\n\n it(`In ${prefix} - Verify free product is added`, updateRetry(3), () => {\n cy.qe('Verify free product is added')\n cy.get('span[class=\"new-product-price\"]')\n .first()\n .should('have.text', 'Free')\n })\n\n completePaymentWithDinersCard(prefix, orderIdEnv)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_a18e3ab1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.2-singleProduct.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport { completePaymentWithDinersCard } from '../../support/adyen/testcase'\nimport { singleProduct } from '../../support/adyen/outputvalidation'\nimport {\n loginViaCookies,\n preserveCookie,\n updateRetry,\n} from '../../support/common/support'\nimport { getTestVariables } from '../../support/common/testcase'\n\nconst { prefix, postalCode, productName, productQuantity } = singleProduct\n\nconst singleProductEnvs = getTestVariables(prefix)\nconst { orderIdEnv } = singleProductEnvs\n\ndescribe(`${prefix} scenarios`, () => {\n loginViaCookies()\n\n it(`In ${prefix} - Adding Product to Cart`, updateRetry(3), () => {\n // Search the product\n cy.searchProduct(productName)\n // Add product to cart\n cy.addProduct(productName)\n })\n\n it(\n `In ${prefix} - Updating product quantity to ${productQuantity}`,\n updateRetry(4),\n () => {\n cy.updateProductQuantity(productName, {\n quantity: productQuantity,\n verifySubTotal: false,\n })\n }\n )\n\n it(`In ${prefix} - Updating Shipping Information`, updateRetry(4), () => {\n // Update Shipping Section\n cy.updateShippingInformation({\n postalCode,\n })\n })\n\n completePaymentWithDinersCard(prefix, orderIdEnv)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_e65c3c86
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/post-setup.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { createAdyenWebhook } from '../../support/adyen/adyen_apis.js'\nimport {\n updateAdyenConnectorSettings,\n updateAdyenPlatformSettings,\n} from '../../support/adyen/graphql.js'\nimport {\n verifyAdyenConnectorSettings,\n verifyAdyenPlatformSettings,\n createOnBoardingLink,\n} from '../../support/adyen/testcase.js'\nimport {\n loginViaCookies,\n preserveCookie,\n} from '../../support/common/support.js'\nimport { setWorkspaceAndGatewayAffiliations } from '../../support/common/testcase.js'\n\ndescribe('Setting up adyen payments in dynamic environment', () => {\n loginViaCookies()\n\n updateAdyenConnectorSettings()\n verifyAdyenConnectorSettings()\n updateAdyenPlatformSettings()\n verifyAdyenPlatformSettings()\n createAdyenWebhook()\n setWorkspaceAndGatewayAffiliations({ afterAuthorization: true })\n createOnBoardingLink(true)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_f8a8ee50
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.10-partialRefund.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport { multiProduct } from '../../support/adyen/outputvalidation.js'\nimport { refund } from '../../support/common/refund_apis.js'\nimport { getTestVariables } from '../../support/common/testcase.js'\nimport {\n loginViaCookies,\n preserveCookie,\n} from '../../support/common/support.js'\nimport { getRefundPayload } from '../../support/common/refund.js'\nimport { verifyOrderInAdyen } from '../../support/adyen/adyen_apis.js'\nimport { loginToAdyen } from '../../support/adyen/testcase.js'\n\ndescribe('Testing Adyen transaction API for partial refund', () => {\n const multiProductEnvs = getTestVariables(multiProduct.prefix)\n const { orderIdEnv } = multiProductEnvs\n\n loginViaCookies()\n\n loginToAdyen()\n\n it('Verify whether we have an order to request for partial refund', () => {\n cy.getOrderItems().then((order) => {\n if (!order[orderIdEnv]) {\n throw new Error('Order id is missing')\n }\n })\n })\n\n // Request partial refund for the ordered product added in 2.3-multiProduct.spec.js\n refund(\n {\n total: multiProduct.getPartialRefundTotal, // Amount\n title: 'partial', // Refund Type for test case title\n env: orderIdEnv, // variable name where we stored the orderid in node environment\n },\n getRefundPayload,\n { startHandling: false }\n )\n\n verifyOrderInAdyen(multiProduct, multiProductEnvs, true)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_95bb49b4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.1-graphql_testcases.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable padding-line-between-statements */\n/* eslint-disable jest/expect-expect */\nimport {\n createAccountHolder,\n validateCreateAccountHolderResponse,\n refreshOnboarding,\n validateRefreshOnboardingResponse,\n closeAccountHolder,\n validateCloseAccountHolderResponse,\n sellers,\n validateSellersResponse,\n validateonboardingComplete,\n onboardingComplete,\n validateGetAdyenAccountResponse,\n getAdyenAccount,\n adyenAccountHolder,\n updateAccount,\n validateAdyenAccountHolderResponse,\n validateUpdateAccount,\n} from '../../support/adyen/graphql_testcase'\nimport { graphql } from '../../support/common/graphql_utils'\nimport { updateRetry, loginViaCookies } from '../../support/common/support'\nimport { createAccount, schedule } from '../../support/adyen/outputvalidation'\nimport { getAllAccount, getOnBoarding } from '../../support/adyen/api_testcase'\nimport { createOnBoardingLink } from '../../support/adyen/testcase'\nimport { deleteAccountHoldersFromMasterData } from '../../support/adyen/adyen_apis.js'\n\nconst accountJson = '.account.json'\nconst accountHolderJson = '.accountholder.json'\nconst accountTokenJson = '.accounttoken.json'\nconst accountHolderCodeJson = '.accountholderCode.json'\n\nconst APP = 'vtex.adyen-platforms'\nconst { sellerId } = createAccount\nconst prefix = 'Graphql testcase'\n\n// Don't change the order,it has dependency.\ndescribe('Adyen GraphQL Validation', () => {\n loginViaCookies()\n\n deleteAccountHoldersFromMasterData()\n\n it(`${prefix} - Create Account Holder`, updateRetry(2), () => {\n graphql(APP, createAccountHolder(createAccount), (response) => {\n validateCreateAccountHolderResponse(response)\n cy.qe('Write accountHolder information in accountJSON')\n cy.writeFile(accountJson, {\n newAccount: response.body.data.createAccountHolder.adyenAccountHolder,\n })\n })\n })\n\n it(`${prefix} - Get Sellers`, updateRetry(2), () => {\n graphql(APP, sellers(), validateSellersResponse)\n })\n\n it(`${prefix} - Get Adyen Account`, updateRetry(2), () => {\n graphql(APP, getAdyenAccount(), validateGetAdyenAccountResponse)\n })\n\n it(`${prefix} - Adyen Account Holder`, updateRetry(2), () => {\n graphql(\n APP,\n adyenAccountHolder(sellerId),\n validateAdyenAccountHolderResponse\n )\n })\n\n it(`${prefix} - Refresh On Boarding`, updateRetry(2), () => {\n cy.readFile(accountJson).then((items) => {\n graphql(\n APP,\n refreshOnboarding(items.newAccount.accountHolderCode),\n (response) => {\n validateRefreshOnboardingResponse(response)\n cy.qe(\n 'Get accountToken from response.body.data.refreshOnboarding and write to accountTokenJson'\n )\n cy.writeFile(accountTokenJson, {\n accountToken: response.body.data.refreshOnboarding,\n })\n }\n )\n })\n })\n\n getAllAccount(sellerId)\n\n it(`${prefix} - updateAccount`, updateRetry(2), () => {\n cy.readFile(accountHolderJson).then((items) => {\n const accountCode = items.accountList\n for (const account in accountCode) {\n if (\n accountCode[account].accountHolderCode === items.accountHolderCode\n ) {\n cy.qe('Make items.accountHolderCode as Active')\n accountCode[account].status = 'Active'\n }\n }\n graphql(\n APP,\n updateAccount(accountCode[0].accountCode, schedule),\n validateUpdateAccount\n )\n })\n })\n\n it(`${prefix} - onboardingComplete`, updateRetry(2), () => {\n cy.readFile(accountHolderCodeJson).then((items) => {\n const { accountHolderCode } = items\n graphql(\n APP,\n onboardingComplete(accountHolderCode),\n validateonboardingComplete\n )\n })\n })\n\n createOnBoardingLink(false)\n\n getOnBoarding()\n\n it(`${prefix} - Close Account Holder`, updateRetry(2), () => {\n cy.readFile(accountJson).then((items) => {\n graphql(\n APP,\n closeAccountHolder(items.newAccount.accountHolderCode),\n validateCloseAccountHolderResponse\n )\n })\n })\n})\n\n```" } ]
code_cy-runner_0a5db76b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.6-discountShipping.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport {\n loginViaCookies,\n preserveCookie,\n} from '../../support/common/support.js'\nimport { discountShipping } from '../../support/adyen/outputvalidation'\nimport { completePaymentWithDinersCard } from '../../support/adyen/testcase.js'\nimport {\n getTestVariables,\n checkoutProduct,\n} from '../../support/common/testcase.js'\n\nconst { prefix } = discountShipping\n\ndescribe(`${prefix} Scenarios`, () => {\n loginViaCookies()\n\n const { orderIdEnv } = getTestVariables(prefix)\n\n checkoutProduct(discountShipping)\n\n completePaymentWithDinersCard(prefix, orderIdEnv)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_4e0a844e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.5-externalSeller.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport {\n loginViaCookies,\n preserveCookie,\n updateRetry,\n} from '../../support/common/support.js'\nimport { externalSeller } from '../../support/adyen/outputvalidation'\nimport { getTestVariables } from '../../support/common/testcase.js'\nimport { completePaymentWithDinersCard } from '../../support/adyen/testcase.js'\n\ndescribe('External Seller Testcase', () => {\n loginViaCookies()\n\n const { prefix, product1Name, product2Name, postalCode, productQuantity } =\n externalSeller\n\n const { orderIdEnv } = getTestVariables(prefix)\n\n it(`In ${prefix} - Adding Product to Cart`, updateRetry(3), () => {\n // Search the product\n cy.searchProduct(product1Name)\n // Add product to cart\n cy.addProduct(product1Name, { proceedtoCheckout: false })\n // Search the product\n cy.searchProduct(product2Name)\n // Add product to cart\n cy.addProduct(product2Name, { proceedtoCheckout: true })\n })\n\n it(\n `In ${prefix} - Updating product quantity to ${productQuantity}`,\n updateRetry(4),\n () => {\n cy.updateProductQuantity(product1Name, {\n quantity: productQuantity,\n verifySubTotal: false,\n })\n }\n )\n\n it(`In ${prefix} - Updating Shipping Information`, updateRetry(4), () => {\n // Update Shipping Section\n cy.updateShippingInformation({ postalCode })\n })\n\n completePaymentWithDinersCard(prefix, orderIdEnv, externalSeller)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_7d3c16c3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.8-transactions.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport { loginViaCookies } from '../../support/common/support.js'\nimport {\n singleProduct,\n multiProduct,\n discountShipping,\n discountProduct,\n // externalSeller,\n promotionProduct,\n} from '../../support/adyen/outputvalidation'\nimport { getTestVariables } from '../../support/common/testcase.js'\nimport {\n loginToAdyen,\n verifyProductInvoiceTestcase,\n} from '../../support/adyen/testcase.js'\n\ndescribe(`Transaction Scenarios`, () => {\n loginViaCookies()\n\n loginToAdyen()\n\n const singleProductEnvs = getTestVariables(singleProduct.prefix)\n const multiProductEnvs = getTestVariables(multiProduct.prefix)\n const discountShippingEnvs = getTestVariables(discountShipping.prefix)\n const discountProductEnvs = getTestVariables(discountProduct.prefix)\n // const externalSellerEnvs = getTestVariables(externalSeller.prefix)\n const promotionalProductEnvs = getTestVariables(promotionProduct.prefix)\n\n // single product\n verifyProductInvoiceTestcase(singleProduct, singleProductEnvs)\n\n // multi product\n verifyProductInvoiceTestcase(multiProduct, multiProductEnvs)\n\n // discount product\n verifyProductInvoiceTestcase(discountProduct, discountProductEnvs)\n\n // discount shipping product\n verifyProductInvoiceTestcase(discountShipping, discountShippingEnvs)\n\n // promotional product\n verifyProductInvoiceTestcase(promotionProduct, promotionalProductEnvs)\n\n // external sellet product\n // TODO - Enable this after verifying it is working fine\n // verifyProductInvoiceTestcase(externalSeller, externalSellerEnvs, true)\n})\n\n```" } ]
code_cy-runner_33c970ca
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.3-multiProduct.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport {\n loginViaCookies,\n updateRetry,\n preserveCookie,\n} from '../../support/common/support.js'\nimport { multiProduct } from '../../support/adyen/outputvalidation'\nimport { completePaymentWithDinersCard } from '../../support/adyen/testcase'\nimport { getTestVariables } from '../../support/common/testcase'\n\nconst { prefix, product1Name, product2Name, postalCode, productQuantity } =\n multiProduct\n\nconst { orderIdEnv } = getTestVariables(prefix)\n\ndescribe('Multi Product Testcase', () => {\n loginViaCookies()\n\n it(`In ${prefix} - Adding Product to Cart`, updateRetry(3), () => {\n // Search the product\n cy.searchProduct(product1Name)\n // Add product to cart\n cy.addProduct(product1Name, { proceedtoCheckout: false })\n // Search the product\n cy.searchProduct(product2Name)\n // Add product to cart\n cy.addProduct(product2Name, {\n proceedtoCheckout: true,\n })\n })\n\n it(\n `In ${prefix} - Updating product quantity to ${productQuantity}`,\n updateRetry(3),\n () => {\n // Update Product quantity to 2\n cy.updateProductQuantity(product1Name, {\n quantity: productQuantity,\n verifySubTotal: false,\n })\n }\n )\n\n it(`In ${prefix} - Updating Shipping Information`, updateRetry(4), () => {\n // Update Shipping Section\n cy.updateShippingInformation({ postalCode })\n })\n\n completePaymentWithDinersCard(prefix, orderIdEnv)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_9a45fd8d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.11-rest-apis.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport {\n loginViaCookies,\n preserveCookie,\n} from '../../support/common/support.js'\nimport { getAllAccount, Adyenhook } from '../../support/adyen/api_testcase'\nimport { hook, sellerAccount } from '../../support/adyen/outputvalidation'\n\ndescribe('Rest-api-testcases', () => {\n loginViaCookies()\n\n getAllAccount(sellerAccount)\n\n Adyenhook(hook)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_125bccd0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/adyen/2.9-fullRefund-transaction.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport { singleProduct } from '../../support/adyen/outputvalidation.js'\nimport { refund } from '../../support/common/refund_apis.js'\nimport { getRefundPayload } from '../../support/common/refund.js'\nimport { getTestVariables } from '../../support/common/testcase.js'\nimport {\n loginViaCookies,\n preserveCookie,\n} from '../../support/common/support.js'\nimport { verifyOrderInAdyen } from '../../support/adyen/adyen_apis.js'\nimport { loginToAdyen } from '../../support/adyen/testcase.js'\n\ndescribe('Testing Adyen transaction API for full refund', () => {\n const singleProductEnvs = getTestVariables(singleProduct.prefix)\n const { orderIdEnv } = singleProductEnvs\n\n loginViaCookies()\n\n loginToAdyen()\n\n it('Verify whether we have an order to request for full refund', () => {\n cy.getOrderItems().then((order) => {\n if (!order[orderIdEnv]) {\n cy.qe('Order id missing in orders json')\n throw new Error('Order id is missing')\n } else {\n cy.qe('Order id found in orders json')\n }\n })\n })\n\n // Request full refund for the ordered product added in 2.2-singleProduct.spec.js\n refund(\n {\n total: singleProduct.getFullRefundTotal, // Amount\n title: 'full', // Refund Type for test case title\n env: orderIdEnv, // variable name where we stored the orderid in node environment\n },\n getRefundPayload,\n { startHandling: false }\n )\n\n verifyOrderInAdyen(singleProduct, singleProductEnvs, true)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_b37c5157
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/shopper-location/2.2-test-locale-with-autoredirect.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { loginViaAPI, preserveCookie } from '../../support/common/support'\nimport { updateSettings } from '../../support/shopper-location/settings'\nimport {\n poland,\n location,\n} from '../../support/shopper-location/outputvalidation'\nimport { addAddress } from '../../support/shopper-location/common'\n\nconst { country, url } = poland\nconst { lat, long } = location\nconst prefix = 'auto redirect configuration'\n\ndescribe('Test Locale with Auto redirect', () => {\n loginViaAPI()\n\n updateSettings(country, url, { automaticRedirect: true })\n\n addAddress(prefix, { address: poland, lat, long })\n\n // eslint-disable-next-line jest/expect-expect\n it(`${prefix} - Now site should force redirect to google`, () => {\n cy.qe(\n 'Without any popup the site will be automatically redirected to Google'\n )\n cy.url().should('eq', 'https://www.google.com/')\n })\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_f1b43eec
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/shopper-location/wipe.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/valid-expect */\nimport { deleteAddresses } from '../../support/common/testcase.js'\nimport {\n loginViaCookies,\n preserveCookie,\n} from '../../support/common/support.js'\n\ndescribe('Wipe the pickup points', () => {\n loginViaCookies()\n\n deleteAddresses()\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_b33f842d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/shopper-location/2.6-negative-scenarios-disable-location.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport {\n loginViaAPI,\n preserveCookie,\n updateRetry,\n} from '../../support/common/support'\nimport { verifyLocation } from '../../support/shopper-location/common'\nimport shopperLocationConstants from '../../support/shopper-location/constants'\nimport selectors from '../../support/common/selectors'\n\nconst prefix = 'Disable location'\n\ndescribe('Location validation', () => {\n loginViaAPI()\n\n // eslint-disable-next-line jest/expect-expect\n it(`${prefix} - Test negative scenarios`, updateRetry(2), () => {\n verifyLocation()\n cy.qe(\n `Now we should see message as (${shopperLocationConstants.faildFindLocation}) in popup`\n )\n cy.get(selectors.AddressErrorContainer).should(\n 'have.text',\n shopperLocationConstants.faildFindLocation\n )\n })\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_eadfd88e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/shopper-location/2.5-negative-scenarios-with-location.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { verifyLocation } from '../../support/shopper-location/common'\nimport {\n loginViaAPI,\n preserveCookie,\n updateRetry,\n} from '../../support/common/support'\nimport shopperLocationConstants from '../../support/shopper-location/constants'\nimport selectors from '../../support/common/selectors'\nimport { location } from '../../support/shopper-location/outputvalidation'\n\nconst prefix = 'Enable location'\n\ndescribe('Location validation', () => {\n loginViaAPI()\n\n // eslint-disable-next-line jest/expect-expect\n it(`${prefix} - Test negative scenarios`, updateRetry(2), () => {\n verifyLocation(location.lat, location.long)\n cy.qe(\n `Now we should see message as (${shopperLocationConstants.locationNotAvailable}) in popup`\n )\n cy.get(selectors.AddressErrorContainer).contains(\n shopperLocationConstants.locationNotAvailable\n )\n cy.get(selectors.countryDropdown).select('CAN')\n cy.qe('Type invalid postal code')\n cy.get(selectors.addressInputContainer).eq(0).type('000000')\n cy.qe(\n `Now user should see the ${shopperLocationConstants.invalidPostalCode} in popup\"`\n )\n cy.get(selectors.ChangeLocationError).should(\n 'have.text',\n shopperLocationConstants.invalidPostalCode\n )\n })\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_b318289d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/shopper-location/2.1-test-locale-redirect-configuration.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport {\n loginViaAPI,\n preserveCookie,\n scroll,\n updateRetry,\n} from '../../support/common/support'\nimport { updateSettings } from '../../support/shopper-location/settings'\nimport {\n poland,\n location,\n} from '../../support/shopper-location/outputvalidation'\nimport selectors from '../../support/common/selectors.js'\nimport { addAddress } from '../../support/shopper-location/common'\nimport { syncCheckoutUICustom } from '../../support/common/testcase.js'\n\nconst { country, url } = poland\nconst { lat, long } = location\n\nconst prefix = 'Manual redirect configuration'\n\ndescribe('Testing local redirect configuration', () => {\n loginViaAPI()\n\n syncCheckoutUICustom()\n\n updateSettings(country, url)\n\n addAddress(prefix, { address: poland, lat, long })\n\n // eslint-disable-next-line jest/expect-expect\n it(`${prefix} - Verify address`, updateRetry(2), () => {\n cy.qe(\n 'After adding address, verifying it on Homepage address container whether the given address is showing'\n )\n scroll()\n cy.get(selectors.addressUpdation)\n .should('be.visible')\n .contains('Warsaw, mazowieckie, 00-014')\n })\n\n // eslint-disable-next-line jest/expect-expect\n it(`${prefix} - Get popup with switch button`, updateRetry(2), () => {\n cy.qe(\n 'Once the address is verified, we will get an popup with visible of switch button. We should be able to click on the button.'\n )\n cy.get(selectors.ToastMsgInB2B).should('be.visible', { timeout: 10000 })\n cy.get(selectors.switchButton).should('be.visible').click()\n })\n\n // eslint-disable-next-line jest/expect-expect\n it(`${prefix} - Page will be redirected to google page`, () => {\n cy.qe(\n 'Once manually switch popup link is clicked, it should redirect us to Google'\n )\n cy.url().should('eq', 'https://www.google.com/')\n })\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_53f1a4fe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/shopper-location/2.3-disable-location-via-browser-popup-order-product.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { loginViaAPI, preserveCookie } from '../../support/common/support'\nimport { orderProductTestCase } from '../../support/shopper-location/common'\nimport { UsDetails } from '../../support/shopper-location/outputvalidation'\n\nconst prefix = 'Disable location'\n\ndescribe(`${prefix}- via browser popup - Order the Product`, () => {\n loginViaAPI()\n\n orderProductTestCase(prefix, UsDetails)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_3185b178
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/shopper-location/2.4-enable-Location-via-browser-popup-order-product.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { loginViaAPI, preserveCookie } from '../../support/common/support'\nimport { orderProductTestCase } from '../../support/shopper-location/common'\nimport { UsDetails } from '../../support/shopper-location/outputvalidation'\n\nconst prefix = 'Enable location'\n\ndescribe(`${prefix}- via browser popup - Order the Product`, () => {\n loginViaAPI()\n\n orderProductTestCase(prefix, UsDetails)\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_5b852dbb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/fedex-shipping/2.10-validate-surcharge-flat-rate.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/valid-expect */\n/* eslint-disable jest/valid-expect-in-promise */\n/* eslint-disable jest/expect-expect */\nimport { updateRetry, loginViaCookies } from '../../support/common/support'\nimport { appSetting } from '../../support/fedex-shipping/outputvalidation'\nimport { data } from '../../fixtures/fedex-shipping-fixtures/shippingRatePayload.json'\nimport { updateSLASettings } from '../../support/fedex-shipping/common.js'\nimport {\n loadCalculateShippingAPI,\n validateCalculateShipping,\n} from '../../support/fedex-shipping/api_testcase'\n\nconst prefix = 'Shipping Optimize'\nlet shippingMethods = []\nconst surchargeFlatRate = 20\nconst surchargePercent = 0\n\ndescribe('Modify SLA - Validate Surcharge Flat Rate in checkout', () => {\n loginViaCookies()\n\n it(`${prefix} - Update Surcharge Flat Rate`, updateRetry(3), () => {\n updateSLASettings(appSetting)\n })\n\n it(`${prefix} - Verify shipping price`, updateRetry(3), () => {\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n shippingMethods = response.body\n })\n })\n\n it(` ${prefix} - Update Surcharge Flat Rate`, updateRetry(3), () => {\n updateSLASettings(appSetting, surchargeFlatRate, surchargePercent)\n })\n\n it(`${prefix} - Validate Surcharge Flat Rate Changes`, updateRetry(3), () => {\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n\n shippingMethods.forEach((shippingMethod) => {\n response.body.forEach((res) => {\n // eslint-disable-next-line vtex/prefer-early-return\n if (res.shippingMethod === shippingMethod.shippingMethod) {\n const calculateFlatRate = shippingMethod.price + surchargeFlatRate\n\n // eslint-disable-next-line jest/no-conditional-expect\n expect(parseFloat(res.price.toFixed(2))).to.equal(calculateFlatRate)\n }\n })\n })\n })\n })\n})\n\n```" } ]
code_cy-runner_98cb2ded
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/fedex-shipping/2.3-single-product-scenarios.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/no-conditional-expect */\n/* eslint-disable jest/expect-expect */\n/* eslint-disable jest/valid-expect */\n/* eslint-disable jest/valid-expect-in-promise */\nimport { loginViaCookies, updateRetry } from '../../support/common/support.js'\nimport {\n singleProduct,\n warehouseId,\n} from '../../support/fedex-shipping/outputvalidation.js'\nimport { data } from '../../fixtures/fedex-shipping-fixtures/shippingRatePayload.json'\nimport {\n loadCalculateShippingAPI,\n validateCalculateShipping,\n} from '../../support/fedex-shipping/api_testcase.js'\nimport {\n verifyInventoryIsUnlimitedForFedexWareHouse,\n validateInventory,\n} from '../../support/fedex-shipping/graphql_testcase.js'\nimport { INVENTORY_GRAPHQL_APP } from '../../support/fedex-shipping/graphql_apps.js'\nimport { graphql } from '../../support/common/graphql_utils'\n\nconst { prefix } = singleProduct\nlet shippingMethods = []\n\ndescribe(`${prefix} Scenarios`, () => {\n loginViaCookies()\n\n it(`${prefix} - For fedex docks, verify inventory is set to infinite`, () => {\n graphql(\n INVENTORY_GRAPHQL_APP,\n verifyInventoryIsUnlimitedForFedexWareHouse(\n warehouseId,\n data.items[0].id\n ),\n validateInventory\n )\n })\n\n it(`${prefix} - Verify single product shipping price`, updateRetry(3), () => {\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n shippingMethods = response.body\n })\n })\n\n it(\n `${prefix} - Set product quantity to 2 and verify shipping price via API`,\n updateRetry(3),\n () => {\n data.items[0].quantity = 2\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n shippingMethods.forEach((shippingMethod) => {\n response.body.forEach((res) => {\n if (res.shippingMethod === shippingMethod.shippingMethod) {\n expect(shippingMethod.shippingMethod).to.equal(res.shippingMethod)\n\n expect(parseFloat(res.price.toFixed(2))).to.equal(\n shippingMethod.price * 2\n )\n }\n })\n })\n })\n }\n )\n})\n\n```" } ]
code_cy-runner_977afe20
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/fedex-shipping/2.5-hide-sla-scenarios.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/valid-expect */\n/* eslint-disable jest/valid-expect-in-promise */\n/* eslint-disable jest/expect-expect */\nimport { updateRetry, loginViaCookies } from '../../support/common/support'\nimport { appSetting } from '../../support/fedex-shipping/outputvalidation'\nimport { FEDEX_SHIPPING_APP } from '../../support/fedex-shipping/graphql_apps.js'\nimport {\n saveAppSetting,\n validateSaveAppSettingResponse,\n} from '../../support/fedex-shipping/graphql_testcase.js'\nimport { data } from '../../fixtures/fedex-shipping-fixtures/shippingRatePayload.json'\nimport { loadCalculateShippingAPI } from '../../support/fedex-shipping/api_testcase.js'\nimport { graphql } from '../../support/common/graphql_utils'\n\nconst prefix = 'Hide Sla'\n\ndescribe('FedEx Hide sla scenarios', () => {\n loginViaCookies()\n\n it(`${prefix} - Hide all Sla's`, updateRetry(3), () => {\n cy.qe('Update sla to hide using saveAppSetting graphql')\n cy.hideSla(true).then((sla) => {\n graphql(\n FEDEX_SHIPPING_APP,\n saveAppSetting(appSetting, sla),\n validateSaveAppSettingResponse\n )\n })\n })\n\n it(`${prefix} - Verify all sla's are not displaying`, updateRetry(2), () => {\n loadCalculateShippingAPI(data).then((response) => {\n expect(response.status).to.have.equal(200)\n expect(response.body).to.be.an('array').and.to.have.lengthOf(0)\n })\n })\n})\n\n```" } ]
code_cy-runner_1c133553
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/fedex-shipping/2.7-enable-disable-ship-to-residential-toggle.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/valid-expect */\n/* eslint-disable jest/valid-expect-in-promise */\nimport { loginViaCookies, updateRetry } from '../../support/common/support.js'\nimport {\n saveAppSetting,\n validateSaveAppSettingResponse,\n} from '../../support/fedex-shipping/graphql_testcase.js'\nimport { graphql } from '../../support/common/graphql_utils'\nimport { appSetting } from '../../support/fedex-shipping/outputvalidation.js'\nimport { data } from '../../fixtures/fedex-shipping-fixtures/shippingRatePayload.json'\nimport {\n loadCalculateShippingAPI,\n validateCalculateShipping,\n} from '../../support/fedex-shipping/api_testcase.js'\nimport { FEDEX_SHIPPING_APP } from '../../support/fedex-shipping/graphql_apps.js'\nimport sla from '../../support/fedex-shipping/sla.js'\n\nconst prefix = 'Ship To Residential'\n\ndescribe(`${prefix} Scenarios`, () => {\n loginViaCookies()\n\n it(`${prefix} - Disable Ship to Residential`, updateRetry(3), () => {\n appSetting.residential = false\n cy.readSlaSettings().then((sl) => {\n graphql(\n FEDEX_SHIPPING_APP,\n saveAppSetting(appSetting, sl),\n validateSaveAppSettingResponse\n )\n })\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n const filtershippingMethod = response.body.filter(\n (b) => b.shippingMethod === sla.FedexGroundDelivery\n )\n\n expect(filtershippingMethod)\n .to.be.an('array')\n .and.to.have.lengthOf.above(0)\n })\n })\n\n it(`${prefix} - Enable Ship to Residential`, updateRetry(3), () => {\n appSetting.residential = true\n cy.readSlaSettings().then((s) => {\n graphql(\n FEDEX_SHIPPING_APP,\n saveAppSetting(appSetting, s),\n validateSaveAppSettingResponse\n )\n })\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n const filtershippingMethod = response.body.filter(\n (b) => b.shippingMethod === sla.FedexHomeDelivery\n )\n\n expect(filtershippingMethod)\n .to.be.an('array')\n .and.to.have.lengthOf.above(0)\n })\n })\n})\n\n```" } ]
code_cy-runner_0f4d3bd1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/fedex-shipping/2.2-rest-apis.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport {\n loginViaCookies,\n preserveCookie,\n updateRetry,\n} from '../../support/common/support.js'\nimport {\n loadDocks,\n loadCalculateShippingAPI,\n validateCalculateShipping,\n} from '../../support/fedex-shipping/api_testcase.js'\nimport { data } from '../../fixtures/fedex-shipping-fixtures/shippingRatePayload.json'\n\nconst prefix = 'Rest API'\n\ndescribe('Rest-api-testcases', () => {\n loginViaCookies()\n\n loadDocks()\n\n it(`${prefix} - Calculate shipping price`, updateRetry(2), () => {\n loadCalculateShippingAPI(data, validateCalculateShipping)\n })\n\n preserveCookie()\n})\n\n```" } ]
code_cy-runner_758d5bda
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/fedex-shipping/2.8-shipping-optimize-scenarios.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/valid-expect */\n/* eslint-disable jest/valid-expect-in-promise */\n/* eslint-disable jest/expect-expect */\nimport { loginViaCookies, updateRetry } from '../../support/common/support.js'\nimport {\n saveAppSetting,\n savePackingOptimizationAppSetting,\n validateSaveAppSettingResponse,\n} from '../../support/fedex-shipping/graphql_testcase.js'\nimport {\n appSetting,\n smartPackingAccessKey,\n packingOptimizationSettings,\n} from '../../support/fedex-shipping/outputvalidation.js'\nimport { data } from '../../fixtures/fedex-shipping-fixtures/shippingOptimizePayload.json'\nimport {\n loadCalculateShippingAPI,\n validateCalculateShipping,\n} from '../../support/fedex-shipping/api_testcase.js'\nimport {\n FEDEX_SHIPPING_APP,\n PACKING_OPTIMIZATION,\n} from '../../support/fedex-shipping/graphql_apps.js'\nimport sla from '../../support/fedex-shipping/sla.js'\nimport { graphql } from '../../support/common/graphql_utils.js'\n\nconst prefix = 'Shipping Optimize'\nlet NonePackingShippingPrice = ''\nlet PackAllInOneShippingPrice = ''\nlet SmartPackingShippingPrice = ''\n\ndescribe(`${prefix} Scenarios`, () => {\n loginViaCookies()\n\n it(`${prefix} - Generate access key`, updateRetry(2), () => {\n graphql(\n PACKING_OPTIMIZATION,\n savePackingOptimizationAppSetting(packingOptimizationSettings),\n validateSaveAppSettingResponse\n )\n })\n\n it(\n `${prefix} - Select shipping optimize type None and validate`,\n updateRetry(3),\n () => {\n appSetting.optimizeShippingType = 0 // Update shipping type to None\n\n cy.readSlaSettings().then((sl) => {\n graphql(\n FEDEX_SHIPPING_APP,\n saveAppSetting(appSetting, sl),\n validateSaveAppSettingResponse\n )\n })\n cy.addDelayBetweenRetries(10000)\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n const filtershippingMethod = response.body.filter(\n (b) =>\n b.shippingMethod === sla.FirstOvernight ||\n b.shippingMethod === sla.StandardOvernight\n )\n\n expect(filtershippingMethod)\n .to.be.an('array')\n .and.to.have.lengthOf.above(0)\n NonePackingShippingPrice = filtershippingMethod[0].price\n })\n }\n )\n\n it(\n `${prefix} - Select shipping optiomize type Pack All In One and validate`,\n updateRetry(3),\n () => {\n appSetting.optimizeShippingType = 1 // Update shipping type to Pack all in one\n\n cy.readSlaSettings().then((getSla) => {\n graphql(\n FEDEX_SHIPPING_APP,\n saveAppSetting(appSetting, getSla),\n validateSaveAppSettingResponse\n )\n })\n cy.addDelayBetweenRetries(10000)\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n const filtershippingMethod = response.body.filter(\n (b) =>\n b.shippingMethod === sla.FirstOvernight ||\n b.shippingMethod === sla.StandardOvernight\n )\n\n expect(filtershippingMethod)\n .to.be.an('array')\n .and.to.have.lengthOf.above(0)\n PackAllInOneShippingPrice = filtershippingMethod[0].price\n })\n }\n )\n\n it(\n `${prefix} - Select shipping optiomize type Smart Packing and validate`,\n updateRetry(3),\n () => {\n appSetting.optimizeShippingType = 2 // Update shipping type to Smart Packing\n appSetting.packingAccessKey = smartPackingAccessKey // Add Smart Packing Access Key\n\n cy.readSlaSettings().then((s) => {\n // update settings\n graphql(\n FEDEX_SHIPPING_APP,\n saveAppSetting(appSetting, s),\n validateSaveAppSettingResponse\n )\n })\n cy.addDelayBetweenRetries(10000)\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n const filtershippingMethod = response.body.filter(\n (b) =>\n b.shippingMethod === sla.FirstOvernight ||\n b.shippingMethod === sla.StandardOvernight\n )\n\n expect(filtershippingMethod)\n .to.be.an('array')\n .and.to.have.lengthOf.above(0)\n SmartPackingShippingPrice = filtershippingMethod[0].price\n })\n }\n )\n\n it(\n `${prefix} - Verify None shipping price is higher than Pack all in one box and Smart packing`,\n updateRetry(1),\n () => {\n expect(NonePackingShippingPrice).to.be.gt(PackAllInOneShippingPrice)\n expect(NonePackingShippingPrice).to.be.gt(SmartPackingShippingPrice)\n }\n )\n\n it(\n `${prefix} - Verify Pack all in one box shipping price is higher than None`,\n updateRetry(1),\n () => {\n expect(PackAllInOneShippingPrice).to.be.lt(NonePackingShippingPrice)\n }\n )\n\n it(\n `${prefix} - Verify Smart Packig shipping price is higher than None`,\n updateRetry(1),\n () => {\n expect(SmartPackingShippingPrice).to.be.lt(NonePackingShippingPrice)\n expect(SmartPackingShippingPrice).to.be.lte(PackAllInOneShippingPrice)\n }\n )\n})\n\n```" } ]
code_cy-runner_658fe7f6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/fedex-shipping/2.6-show-sla-scenarios.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\n/* eslint-disable jest/valid-expect */\nimport { updateRetry, loginViaCookies } from '../../support/common/support.js'\nimport { appSetting } from '../../support/fedex-shipping/outputvalidation.js'\nimport { FEDEX_SHIPPING_APP } from '../../support/fedex-shipping/graphql_apps.js'\nimport {\n saveAppSetting,\n validateSaveAppSettingResponse,\n} from '../../support/fedex-shipping/graphql_testcase.js'\nimport { graphql } from '../../support/common/graphql_utils'\nimport { data } from '../../fixtures/fedex-shipping-fixtures/shippingRatePayload.json'\nimport {\n loadCalculateShippingAPI,\n validateCalculateShipping,\n} from '../../support/fedex-shipping/api_testcase.js'\n\nconst prefix = `UnHide sla`\n\ndescribe('FedEx UnHide sla scenarios', () => {\n loginViaCookies()\n\n it(`${prefix} - Unhide all sla's`, updateRetry(3), () => {\n cy.qe('Update sla to show using saveAppSetting graphql')\n cy.hideSla(false).then((sla) => {\n graphql(\n FEDEX_SHIPPING_APP,\n saveAppSetting(appSetting, sla),\n validateSaveAppSettingResponse\n )\n })\n })\n\n it(`${prefix} - Calculate shipping price`, updateRetry(2), () => {\n loadCalculateShippingAPI(data, validateCalculateShipping)\n })\n})\n\n```" } ]
code_cy-runner_acdb304e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of cy-runner/cypress-shared/integration/fedex-shipping/2.11-validate-surcharge-percentage.spec.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/valid-expect */\n/* eslint-disable jest/expect-expect */\n/* eslint-disable jest/valid-expect-in-promise */\nimport { updateRetry, loginViaCookies } from '../../support/common/support'\nimport { appSetting } from '../../support/fedex-shipping/outputvalidation'\nimport { data } from '../../fixtures/fedex-shipping-fixtures/shippingRatePayload.json'\nimport { updateSLASettings } from '../../support/fedex-shipping/common.js'\nimport {\n loadCalculateShippingAPI,\n validateCalculateShipping,\n} from '../../support/fedex-shipping/api_testcase'\n\nconst prefix = 'Shipping Optimize'\nlet shippingMethods = []\nconst surchargeFlatRate = 0\nconst surchargePercent = 30\n\ndescribe('Modify SLA - Validate Surcharge Percentage in checkout', () => {\n loginViaCookies()\n\n it(`${prefix} - Update Surcharge Flat Rate`, updateRetry(3), () => {\n updateSLASettings(appSetting)\n })\n\n it(`${prefix} - Verify shipping price`, updateRetry(3), () => {\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n shippingMethods = response.body\n })\n })\n\n it(` ${prefix} - Update Surcharge percentage`, updateRetry(3), () => {\n updateSLASettings(appSetting, surchargeFlatRate, surchargePercent)\n })\n\n it(\n `${prefix} - Validate Surcharge Percentage Changes`,\n updateRetry(3),\n () => {\n // eslint-disable-next-line jest/valid-expect-in-promise\n loadCalculateShippingAPI(data).then((response) => {\n validateCalculateShipping(response)\n\n shippingMethods.forEach((shippingMethod) => {\n response.body.forEach((res) => {\n // eslint-disable-next-line vtex/prefer-early-return\n if (res.shippingMethod === shippingMethod.shippingMethod) {\n const calculatePercentage =\n (shippingMethod.price * surchargePercent) / 100\n\n const calculateFlatRate = shippingMethod.price + surchargeFlatRate\n\n // eslint-disable-next-line jest/no-conditional-expect\n expect(parseFloat(res.price.toFixed(2))).to.equal(\n parseFloat((calculatePercentage + calculateFlatRate).toFixed(2))\n )\n }\n })\n })\n })\n }\n )\n})\n\n```" } ]