id
stringlengths
12
53
messages
listlengths
3
3
code_cy-runner_4ad92295
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/README.md from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Cypress-Template\n\nThe repo contains common selectors, apis, constants, support file that can be used for test automation with VTEX apps using Cypress\n\nSteps:\n\n1. Install Cypress in your vtex-apps repo\n `yarn add -D cypress`\n2. Open cypress `yarn cypress open` - This creates Cypress directory and Cypress.json file\n3. Copy cypress.json from this repo and paste in your repo. Update the keys appropriately\n4. Go into cypress/support directory\n `cd cypress/support`\n5. Add cypress-template as a submodule in the cypress/support directory by executing the command below,\n `git clone --recurse-submodules git@github.com:vtex/cypress-template.git`\n6. Now, you can import selectors, apis, constants in your code\n7. To make cypress commands available in your test case\n `eg: loginAsAdmin`\n You need to open cypress/support/commands.js file\n Add below lines of code\n\n ```nodejs\n import {loginAsAdmin} from './cypress-template/support.js'\n Cypress.Commands.add('loginAsAdmin', loginAsAdmin)\n ```\n\n8. Now you can call `cy.loginAsAdmin()` in your code\n9. To pull latest code from Github submodule branch\n git submodule update --recursive --remote\n\nReferences:\n\n1. Cypress - https://www.cypress.io/\n2. Git Submodules - https://git-scm.com/book/en/v2/Git-Tools-Submodules\n\n```" } ]
code_cy-runner_e7a92396
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/headers.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport default {\n SignIn: 'Sign In',\n MyAccount: 'My Account',\n Logout: 'Logout',\n HomePageTitle: 'test',\n SigInByEmail: 'Sign in with e-mail and password',\n}\n\n```" } ]
code_cy-runner_56033da6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/checkout_ui_custom.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst getConfiguration = (workspace) => {\n if (!workspace) throw new Error('Workspace should be passed to this function')\n\n return {\n email: 'syed.mujeeb@vtex.com.br',\n workspace,\n layout: {\n type: 'vertical',\n accordionPayments: false,\n deliveryDateFormat: false,\n showCartQuantityPrice: false,\n showNoteField: false,\n hideEmailStep: true,\n customAddressForm: false,\n fontSize: '12px',\n borderRadius: '8px',\n btnBorderRadius: '32px',\n maxWrapper: '980px',\n inputHeight: '40px',\n bordersContainers: 'none',\n fontFamily: '\"Roboto\", sans-serif',\n currentPreview:\n 'https://productusqa.vtexassets.com/_v/public/assets/v1/published/vtex.checkout-ui-custom@0.8.14/public/react/cdabb94cf787f1e2c9fdbc50a6365dc5.png',\n },\n javascript:\n \"function updateOrderForm(method, exemptionNumber) {\\n let orderFormID = vtexjs.checkout.orderFormId\\n $.ajax({\\n url:\\n window.location.origin +\\n '/api/checkout/pub/orderForm/' +\\n orderFormID +\\n '/customData/avalara/exemptionNumber',\\n type: method,\\n data: { value: exemptionNumber },\\n success: function () {\\n vtexjs.checkout.getOrderForm().done(function (orderForm) {\\n if (orderForm.customData) {\\n //doSomething()\\n $('.tax-exemption__form').addClass('js-success')\\n } else {\\n //doSomethingElse()\\n $('.tax-exemption__input').val('')\\n $('.tax-exemption__form').removeClass('js-success')\\n }\\n //refresh the summary\\n vtexjs.checkout.getOrderForm().then(function (orderForm) {\\n var clientProfileData = orderForm.clientProfileData\\n return vtexjs.checkout.sendAttachment(\\n 'clientProfileData',\\n clientProfileData\\n )\\n })\\n })\\n },\\n })\\n}\\n\\nlet taxExemptionFieldHtml = `\\n <div class=\\\"tax-exemption\\\">\\n <p>Tax Exemption Certificate Number</p>\\n <form class=\\\"tax-exemption__form\\\">\\n <input type=\\\"text\\\" required maxlength=\\\"25\\\" class=\\\"tax-exemption__input\\\" name=\\\"tax-exemption__input\\\"/>\\n <input type=\\\"submit\\\" class=\\\"tax-exemption__button btn btn-primary\\\" value=\\\"OK\\\" />\\n <button class=\\\"tax-exemption__button--remove\\\">remove</button>\\n </form>\\n </div>\\n`\\n\\nfunction taxExemptionBinds() {\\n $('.tax-exemption__form').on('submit', function (e) {\\n e.preventDefault()\\n let exptN = $('.tax-exemption__input').val()\\n if (exptN) updateOrderForm('PUT', exptN)\\n return false\\n })\\n\\n $('.tax-exemption__button--remove').on('click', function (e) {\\n e.preventDefault()\\n updateOrderForm('DELETE', '')\\n })\\n}\\n\\nfunction taxExemptionValidateForm(inputVal) {\\n if (inputVal) {\\n $('.tax-exemption__form').addClass('js-success')\\n $('.tax-exemption__input').val(inputVal)\\n }\\n}\\n\\nfunction appendField() {\\n if (\\n ~window.location.hash.indexOf('#/payment') &&\\n !$('.tax-exemption').length\\n ) {\\n let customTaxVal = vtexjs.checkout.orderForm?.customData\\n ? vtexjs.checkout.orderForm.customData.customApps\\n ? vtexjs.checkout.orderForm.customData.customApps.find(\\n (app) => app.id == 'avalara'\\n )\\n : ''\\n : ''\\n customTaxVal = customTaxVal ? customTaxVal.fields.exemptionNumber : ''\\n if (\\n !customTaxVal &&\\n !vtexjs.checkout.orderForm?.totalizers.find((x) => x.id === 'CustomTax')\\n )\\n return false\\n $('#payment-data form.form-step.box-new').prepend(taxExemptionFieldHtml)\\n taxExemptionValidateForm(customTaxVal)\\n taxExemptionBinds()\\n }\\n}\\n\\n$(window).on('hashchange', function () {\\n appendField()\\n})\\n\\n$(window).load(function () {\\n appendField()\\n})\\n\\n\\nfunction updateOrderFormVAT(method, vat) {\\n let orderFormID = vtexjs.checkout.orderFormId\\n $.ajax({\\n url:\\n window.location.origin +\\n '/api/checkout/pub/orderForm/' +\\n orderFormID +\\n '/customData/avalara/vatNumber',\\n type: method,\\n data: { value: vat },\\n success: function () {\\n vtexjs.checkout.getOrderForm().done(function (orderForm) {\\n if (orderForm.customData) {\\n //doSomething()\\n $('.business-vat__form').addClass('js-success')\\n } else {\\n //doSomethingElse()\\n $('.vat-number__input').val('')\\n $('.business-vat__form').removeClass('js-success')\\n }\\n //refresh the summary\\n vtexjs.checkout.getOrderForm().then(function (orderForm) {\\n var clientProfileData = orderForm.clientProfileData\\n return vtexjs.checkout.sendAttachment(\\n 'clientProfileData',\\n clientProfileData\\n )\\n })\\n })\\n },\\n })\\n}\\n\\nlet vatFieldHtml = `\\n <div class=\\\"vat-number\\\">\\n <p>Business VAT Number</p>\\n <form class=\\\"business-vat__form\\\">\\n <input type=\\\"text\\\" required maxlength=\\\"25\\\" class=\\\"vat-number__input\\\" name=\\\"vat-number__input\\\"/>\\n <input type=\\\"submit\\\" class=\\\"vat-number__button btn btn-primary\\\" value=\\\"OK\\\" />\\n <button class=\\\"vat-number__button--remove\\\">remove</button>\\n </form>\\n </div>\\n`\\n\\nfunction vatBinds() {\\n $('.business-vat__form').on('submit', function (e) {\\n e.preventDefault()\\n let vat = $('.vat-number__input').val()\\n if (vat) updateOrderFormVAT('PUT', vat)\\n return false\\n })\\n\\n $('.vat-number__button--remove').on('click', function (e) {\\n e.preventDefault()\\n updateOrderFormVAT('DELETE', '')\\n })\\n}\\n\\nfunction vatValidateForm() {\\n $('.business-vat__form').addClass('js-success')\\n}\\n\\nfunction appendFieldVAT() {\\n if (~window.location.hash.indexOf('#/payment') && !$('.vat-number').length) {\\n $('#payment-data form.form-step.box-new').prepend(vatFieldHtml)\\n vatValidateForm()\\n vatBinds()\\n }\\n}\\n\\n$(window).on('hashchange', function () {\\n appendFieldVAT()\\n})\\n\\n$(window).load(function () {\\n appendFieldVAT()\\n})\",\n css: '.tax-exemption {\\n margin-bottom: 10px;\\n}\\n.tax-exemption__form {\\n display: flex;\\n}\\n.tax-exemption__button {\\n margin-left: 10px;\\n border-radius: 4px;\\n}\\n\\n.tax-exemption__button--remove {\\n margin-left: 10px;\\n border-radius: 4px;\\n background: transparent;\\n border: none;\\n color: #ff4c4c;\\n display: none;\\n}\\n\\n.tax-exemption__form.js-success {\\n}\\n.tax-exemption__form.js-success input.tax-exemption__input {\\n border: none !important;\\n box-shadow: none;\\n pointer-events: none;\\n font-weight: bold;\\n}\\n.tax-exemption__form.js-success .tax-exemption__button {\\n display: none;\\n}\\n.tax-exemption__form.js-success .tax-exemption__button--remove {\\n display: block;\\n text-decoration: underline;\\n}\\n\\n.vat-number {\\n margin-bottom: 10px;\\n}\\n.business-vat__form {\\n display: flex;\\n}\\n.vat-number__button {\\n margin-left: 10px;\\n border-radius: 4px;\\n}\\n\\n.vat-number__button--remove {\\n margin-left: 10px;\\n}\\n\\n.vat-number__form.js-success input.vat-number__input {\\n border: none !important;\\n box-shadow: none;\\n pointer-events: none;\\n font-weight: bold;\\n}\\n.vat-number__form.js-success .vat-number__button {\\n display: none;\\n}\\n.vat-number__form.js-success .vat-number__button--remove {\\n display: block;\\n text-decoration: underline;\\n}',\n javascriptActive: true,\n cssActive: true,\n colors: {\n base: '#f4f2f2',\n baseInverted: '#21364f',\n actionPrimary: '#1a73e8',\n actionPrimaryDarken: '#1d63be',\n actionSecondary: '#f1f7ff',\n emphasis: '#000000',\n disabled: '#999999',\n success: '#2fba2d',\n successDarken: '#269e24',\n successFaded: '#beffa5',\n danger: '#ff4c4c',\n dangerFaded: '#ffe6e6',\n warning: '#ffb100',\n warningFaded: '#fff6e0',\n muted1: '#323232',\n muted2: '#676767',\n muted3: '#999999',\n muted4: '#cbcbcb',\n muted5: '#eeeeee',\n muted6: '#f3f3f3',\n },\n }\n}\n\nexport default getConfiguration\n\n```" } ]
code_cy-runner_89f20cd3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/refund_apis.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { updateRetry } from './support.js'\nimport { workFlowAPI, startHandlingAPI } from './apis.js'\nimport { VTEX_AUTH_HEADER } from './constants.js'\n\nexport function refund(\n { total, externalSeller, title, env },\n payload,\n { startHandling = true, sendInvoice = false } = {}\n) {\n const refundInvoiceNumber = '84321'\n\n if (startHandling) {\n it('Start handling', () => {\n cy.getVtexItems().then((vtex) => {\n cy.getOrderItems().then((order) => {\n cy.callRestAPIAndAddLogs({\n url: startHandlingAPI(vtex.baseUrl, order[env]),\n }).then((response) => {\n cy.qe('Verify response to be 204/409')\n expect(response.status).to.match(/204|409/)\n })\n })\n })\n })\n }\n\n if (sendInvoice && externalSeller) {\n it('Send Invoice', () => {\n cy.getOrderItems().then((order) => {\n cy.sendInvoiceAPI(\n {\n invoiceNumber: '54321',\n invoiceValue: total\n .replace('$ ', '')\n .replace(/\\./, '')\n .replace(/,/, ''),\n invoiceUrl: null,\n issuanceDate: new Date(),\n invoiceKey: null,\n },\n order[env],\n env === externalSeller.externalSaleEnv\n ).then((response) => {\n cy.qe('Verify response to be 200')\n expect(response.status).to.equal(200)\n })\n })\n })\n }\n\n it(\n 'Workflow API should have order status has invoiced',\n updateRetry(5),\n () => {\n cy.addDelayBetweenRetries(5000)\n cy.getVtexItems().then((vtex) => {\n cy.getOrderItems().then((order) => {\n cy.getAPI(\n workFlowAPI(vtex.baseUrl, order[env]),\n VTEX_AUTH_HEADER(vtex.apiKey, vtex.apiToken)\n ).then((response) => {\n cy.qe('Verify response to be 200')\n cy.qe('Verify response.body.currentState to be invoiced')\n expect(response.status).to.equal(200)\n cy.qe('Expect response.body.currentState to equal invoiced')\n expect(response.body.currentState).to.equal('invoiced')\n })\n })\n })\n }\n )\n\n it(`Rqeuest for ${title} refund`, () => {\n cy.getOrderItems().then((order) => {\n cy.sendInvoiceAPI(\n payload(refundInvoiceNumber, total, order[env]),\n order[env]\n ).then((response) => {\n cy.qe('Verify response to be 204/409')\n expect(response.status).to.match(/200|500/)\n })\n })\n })\n}\n\n```" } ]
code_cy-runner_33ef58ca
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/sandbox_products.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport const PRODUCTS = {\n shoesv5: 'forum low shoes v5',\n indigotshirt: 'adidas women indigo',\n pinktshirt: 'adidas women pink',\n}\n\n```" } ]
code_cy-runner_d4aa66b6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/outputvalidation.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { PRODUCTS } from './utils.js'\n\nexport default {\n singleProduct: {\n prefix: 'singleProduct',\n postalCode: '33180',\n totalAmount: '$ 1,160.95',\n tax: '0',\n taxWithoutExemption: '$ 75.95',\n productPrice: '540.00',\n subTotal: '$ 1,080.00',\n // singleProduct, taxExemption, vatNumber,multiProduct,refund,externalSeller uses below product\n productName: PRODUCTS.coconut,\n productQuantity: '2',\n totalProductPrice: '1085.00',\n totalWithoutTax: '$ 1,085.00',\n },\n multiProduct: {\n prefix: 'multiProduct',\n postalCode: '93200',\n pickUpPostalCode: '33180',\n totalAmount: '$ 1,416.00',\n tax: '0',\n taxWithoutExemption: '$ 236.00',\n subTotal: '$ 1,180.00',\n product1Name: PRODUCTS.coconut,\n product2Name: PRODUCTS.orange,\n totalWithoutTax: '$ 1,180.00',\n productQuantity: '2',\n product1Price: '540.00',\n product2Price: '100.00',\n totalProductPrice: '1,180.00',\n },\n discountProduct: {\n prefix: 'discountProduct',\n postalCode: '33180',\n totalAmount: '$ 101.65',\n tax: '$ 6.65',\n subTotal: '$ 100.00',\n totalWithoutTax: '$ 100.00',\n productQuantity: '1',\n productPrice: '100.00',\n productName: PRODUCTS.cauliflower,\n env: 'discountProductEnv',\n },\n discountShipping: {\n prefix: 'discountShipping',\n postalCode: '90290',\n totalAmount: '$ 109.50',\n tax: '$ 9.50',\n subTotal: '$ 100.00',\n productQuantity: '1',\n totalWithoutTax: '$ 100.00',\n productPrice: '100.00',\n shippingLabel: 'Free',\n productName: PRODUCTS.orange,\n env: 'discountShippingOrder',\n },\n addressVerificationAPIConstants: {\n invalidCountryValidation: (response) => {\n expect(response.status).to.equal(200)\n expect(response.body[0].summary).to.have.string('Not a valid country')\n },\n invalidDataResponse: (response) => {\n expect(response.status).to.equal(200)\n expect(response.body.isValidAddress).to.be.false\n expect(response.body.messages[0].source).to.equal('Avalara.AvaTax.Common')\n expect(response.body.messages[0].severity).to.equal('Error')\n },\n },\n externalSeller: {\n prefix: 'externalSeller',\n postalCode: '33180',\n product1Name: PRODUCTS.coconut,\n product2Name: PRODUCTS.tshirt,\n totalAmount: '$ 1,266.88',\n tax: '$ 82.88',\n directSaleAmount: '$ 1,160.95',\n directSaleTax: '$ 75.95',\n directSaleEnv: 'directSale',\n externalSellerAmount: '$ 105.93',\n externalSellerTax: '$ 6.93',\n externalSaleEnv: 'externalSale',\n subTotal: '$ 1,174.00',\n productQuantity: '2',\n product1Price: '540.00',\n },\n europeanShipping: {\n postalCode: '93200',\n totalAmount: '$ 1,296.00',\n subTotal: '$ 1,080.00',\n tax: '$ 216.00',\n totalWithoutTax: '$ 1,080.00',\n },\n requestRefund: {\n // orderId variable name for getFullRefundTotal\n fullRefundEnv: 'order1',\n // orderId variable name for getPartialRefund\n partialRefundEnv: 'order2',\n getFullRefundTotal: 108500,\n getPartialRefundTotal: 108500,\n subTotal: '$ 1,080.00',\n },\n promotionProduct: {\n prefix: 'promotionalProduct',\n postalCode: '90290',\n totalAmount: '$ 26.65',\n tax: '$ 1.88',\n salesTax: '$ 1.88',\n amount: '24.77',\n subTotal: '$ 39.54',\n discount: '$ -19.77',\n totalWithoutTax: '$ 26.65',\n productName: PRODUCTS.greenConventional,\n productQuantity: '2',\n productPrice: '19.77',\n env: 'promotionProductEnv',\n },\n}\n\n```" } ]
code_cy-runner_3c382896
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/refund.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport function getRefundPayload(invoiceNumber, invoiceValue, orderId) {\n return {\n invoiceNumber,\n invoiceValue,\n issuanceDate: new Date(),\n type: 'Input',\n items: [\n {\n uniqueId: '3C851E5766644AA18D67DF3A3ED14F73',\n id: '880300',\n productId: '880030',\n ean: null,\n lockId: `00-${orderId}`,\n itemAttachment: {\n content: {},\n name: null,\n },\n attachments: [],\n quantity: 2,\n seller: '1',\n name: 'Fresh Coconuts',\n refId: '880300a',\n price: 54000,\n listPrice: 54000,\n manualPrice: null,\n priceTags: [],\n imageUrl:\n 'https://productusqa.vteximg.com.br/arquivos/ids/155670-55-55/fresh-coconuts.jpg?v=637745847017730000',\n detailUrl: '/fresh-coconuts/p',\n components: [],\n bundleItems: [],\n params: [],\n offerings: [],\n sellerSku: '880300',\n priceValidUntil: null,\n commission: 0,\n tax: 0,\n preSaleDate: null,\n additionalInfo: {\n brandName: 'Brand',\n brandId: '9280',\n categoriesIds: '/9282/',\n categories: [\n {\n id: 9282,\n name: 'Food and beverage',\n },\n ],\n productClusterId: '139,141,145,146,147,148',\n commercialConditionId: '1',\n dimension: {\n cubicweight: 0.2083,\n height: 10,\n length: 10,\n weight: 10,\n width: 10,\n },\n offeringInfo: null,\n offeringType: null,\n offeringTypeId: null,\n },\n measurementUnit: 'un',\n unitMultiplier: 1,\n sellingPrice: 54000,\n isGift: false,\n shippingPrice: null,\n rewardValue: 0,\n freightCommission: 0,\n priceDefinition: {\n sellingPrices: [\n {\n value: 54000,\n quantity: 2,\n },\n ],\n calculatedSellingPrice: 54000,\n total: 108000,\n },\n taxCode: null,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n callCenterOperator: null,\n serialNumbers: null,\n assemblies: [],\n costPrice: 54000,\n index: 0,\n taxHubTotal: 0,\n warehouseId: '1_1',\n hasManualPrice: false,\n originalSellingPrice: 54000,\n selectableQuantity: [1, 2],\n selectedQuantity: 2,\n isSelected: true,\n },\n ],\n }\n}\n\n```" } ]
code_cy-runner_b3cb02fc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/commands.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport {\n FAIL_ON_STATUS_CODE_STRING,\n VTEX_AUTH_HEADER,\n FAIL_ON_STATUS_CODE,\n} from './constants.js'\nimport selectors from './selectors.js'\nimport {\n addProduct,\n fillAddress,\n searchProduct,\n verifyTotal,\n updateProductQuantity,\n updateShippingInformation,\n saveOrderId,\n} from './support.js'\nimport { generateAddtoCartCardSelector, getLogFile } from './utils.js'\n\nconst config = Cypress.env()\nconst { apiKey, apiToken, isCI } = config.base.vtex\n\nCypress.Commands.add('qe', (msg = '') => {\n if (msg === '') {\n cy.writeFile(getLogFile(), msg, { flag: 'w' })\n }\n\n const logs = Cypress.env('logs')\n\n cy.setLogs(`${logs} ${msg}\\n`)\n\n cy.log(msg)\n})\n\nCypress.Commands.add('localqe', (msg = '') => {\n if (!isCI) {\n cy.qe('Running in non CI mode - writing full request information')\n cy.writeFile(getLogFile(), msg ? `${msg}\\n` : msg, {\n flag: msg ? 'a+' : 'w',\n })\n cy.log(msg)\n }\n})\n\nCypress.Commands.add('clearLogs', () => {\n Cypress.env('logs', '')\n})\n\nCypress.Commands.add('setLogs', (msg) => {\n Cypress.env('logs', msg)\n})\n\nCypress.Commands.add('addGraphqlLogs', (query, variables) => {\n cy.qe(`Query - ${query}`)\n if (variables) {\n // eslint-disable-next-line no-extra-boolean-cast\n if (isCI) {\n cy.qe(`We are in CI mode, Skip writting variables inside logs`)\n } else {\n cy.qe('Running in non CI mode - writing full request information')\n cy.qe(`Variables - ${JSON.stringify(variables)}`)\n }\n }\n})\n\nCypress.Commands.add(\n 'callGraphqlAndAddLogs',\n ({ url, query, variables, headers }) => {\n cy.addGraphqlLogs(query, variables)\n cy.request({\n method: 'POST',\n url,\n body: {\n query,\n variables,\n },\n headers: headers || VTEX_AUTH_HEADER(apiKey, apiToken),\n ...FAIL_ON_STATUS_CODE,\n })\n }\n)\n\nCypress.Commands.add(\n 'callRestAPIAndAddLogs',\n ({\n method = 'POST',\n url,\n body = null,\n headers = null,\n auth = null,\n form = false,\n } = {}) => {\n headers = headers || VTEX_AUTH_HEADER(apiKey, apiToken)\n\n if (isCI) {\n cy.qe(\n `For full request run in local: \\n cy.request({method: ${method},url: ${url},${FAIL_ON_STATUS_CODE_STRING}})`\n )\n } else {\n cy.qe('Running in non CI mode - writing full request information')\n cy.qe(\n `cy.request({method: ${method},url: ${url},body:${JSON.stringify(\n body\n )},form:${form},auth:${JSON.stringify(auth)},headers:${JSON.stringify(\n headers\n )},form:${form},${FAIL_ON_STATUS_CODE_STRING}})`\n )\n }\n\n cy.request({\n url,\n method,\n body,\n headers,\n auth,\n form,\n ...FAIL_ON_STATUS_CODE,\n })\n }\n)\n\nCypress.Commands.add('addProduct', addProduct)\nCypress.Commands.add('fillAddress', fillAddress)\nCypress.Commands.add('searchProduct', searchProduct)\nCypress.Commands.add('updateProductQuantity', updateProductQuantity)\nCypress.Commands.add('updateShippingInformation', updateShippingInformation)\nCypress.Commands.add('verifyTotal', verifyTotal)\n\nCypress.Commands.add('getVtexItems', () => {\n return cy.wrap(Cypress.env().base.vtex, { log: false })\n})\n\nCypress.Commands.add('addDelayBetweenRetries', (delay) => {\n if (cy.state('runnable')._currentRetry > 0) {\n cy.qe(`Wait for ${delay} seconds`)\n cy.wait(delay)\n }\n})\n\nCypress.Commands.add('addReloadBetweenRetries', () => {\n if (cy.state('runnable')._currentRetry > 0) {\n cy.qe('Reload the page')\n cy.reload()\n }\n})\n\nCypress.Commands.add('reloadOnLastNAttempts', (n = 1) => {\n const retries = cy.state('runnable')._retries\n const currentRetry = cy.state('runnable')._currentRetry\n\n if (n > retries) {\n cy.log('Reload will be happen on every attempts')\n } else if (n === 0) {\n cy.lod('n is 0, So, reload will not be happened on any of the attempts')\n }\n\n /*\n Retries would be constant on all attempts\n Say, we set retries as 3 for it block and n as 2\n Then reload will happen on last 2 attempts\n\n Formula ->> retries-currentRetry<n then reload\n\n Iteration 1: retries=3,currentRetry=0,n=2\n 3-0 < 2 -> False -> Reload will not happen\n Iteration 2: retries=3,currentRetry=1,n=2\n 3-1 < 2 -> False -> Reload will not happen\n Iteration 3: retries=3,currentRetry=2,n=2\n 3-2 < 2 -> True -> Reload will happen\n Iteration 4: retries=3,currentRetry=3,n=2\n 3-3 < 2 -> True -> Reload will happen\n */\n if (retries - currentRetry < n) cy.reload()\n})\n\nCypress.Commands.add('closeCart', () => {\n cy.get('body').then(($body) => {\n if ($body.find(selectors.CloseCart).length) {\n cy.get(selectors.CloseCart).then(($el) => {\n if (Cypress.dom.isVisible($el)) {\n cy.get(selectors.CloseCart).click()\n }\n })\n }\n })\n})\n\nCypress.Commands.add('getIframeBody', (selector) => {\n // get the iframe > document > body\n // and retry until the body element is not empty\n return (\n cy\n .get(selector)\n .its('0.contentDocument.body')\n .should('not.be.empty')\n .should('be.visible')\n .should('not.be.undefined')\n\n // wraps \"body\" DOM element to allow\n // chaining more Cypress commands, like \".find(...)\"\n // https://on.cypress.io/wrap\n .then(cy.wrap)\n )\n})\n\nCypress.Commands.add('gotoProductDetailPage', () => {\n cy.get(selectors.ProductAnchorElement)\n .should('have.attr', 'href')\n .then((href) => {\n cy.get(generateAddtoCartCardSelector(href)).first().click()\n })\n})\n\nCypress.Commands.add(\n 'orderProduct',\n ({\n paymentSelector = selectors.PromissoryPayment,\n orderIdEnv = null,\n externalSeller = null,\n } = {}) => {\n cy.get('body').then(($body) => {\n cy.qe({ msg: `Select the payment option and order the product` })\n if ($body.find(selectors.FillInvoiceAddress).length === 2) {\n cy.get(selectors.FillInvoiceAddress).last().should('be.visible').click()\n }\n\n if ($body.find(selectors.ReceiverName).length) {\n cy.get(selectors.ReceiverName, {\n timeout: 5000,\n }).type('Syed')\n }\n })\n\n cy.get('body').then(($body) => {\n if ($body.find(selectors.GotoPaymentBtn).length) {\n cy.get(selectors.GotoPaymentBtn).click()\n }\n })\n\n cy.get(paymentSelector, { timeout: 5000 }).should('be.visible').click()\n\n cy.get(selectors.BuyNowBtn, {\n timeout: 10000,\n })\n .should('be.visible')\n .last()\n .click()\n cy.get(selectors.Search, { timeout: 30000 }).should('be.visible')\n // if orderIdEnv or externalSeller is must be passed then only we store orderId\n // otherwise we just verify order is placed or not\n saveOrderId(orderIdEnv, externalSeller)\n }\n)\n\nconst orderFormDebugJSON = '_orderFormDebug.json'\n\n// Set Debug items\nCypress.Commands.add('setorderFormDebugItem', () => {\n cy.window().then(($win) => {\n cy.readFile(orderFormDebugJSON).then((items) => {\n items[Cypress.currentTest.titlePath] = $win.vtexjs.checkout.orderForm\n cy.writeFile(orderFormDebugJSON, items)\n })\n })\n})\n\n```" } ]
code_cy-runner_218f2fba
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/utils.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport const PRODUCTS = {\n onion: 'Yellow Onions',\n coconut: 'Fresh Coconuts',\n waterMelon: 'Whole Watermelon',\n orange: 'Navel Oranges',\n cauliflower: 'Cauliflower Fresh',\n tshirt: 'green night',\n irobot: 'irobot',\n blackDecker: 'black decker',\n greenConventional: 'green conventional',\n}\n\nexport function generateAddtoCartSelector(href) {\n return `a[href='${href}'] > article > button`\n}\n\nexport function generateAddtoCartCardSelector(href) {\n return `a[href='${href}']`\n}\n\nexport const PRODUCTS_LINK_MAPPING = {\n orange: {\n name: 'Navel Oranges Grown Large Fresh Fruit',\n link: 'a[href*=\"/navel-oranges-grown-large-fresh-fruit/p\"]',\n },\n coconut: {\n name: 'Fresh Coconuts',\n link: 'a[href=\"/fresh-coconuts/p\"]',\n },\n}\n\nexport function isValidDate(d) {\n // eslint-disable-next-line no-restricted-globals\n return d instanceof Date && !isNaN(d)\n}\n\nexport function getLogFile() {\n return `${\n Cypress.spec.absolute.split('cy-runner')[0]\n }cy-runner/logs/${Cypress.spec.name.split('/').at(-1)}.log`\n}\n\n```" } ]
code_cy-runner_784b9613
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/gmail.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable func-names */\n/* eslint-disable no-console */\n\nimport axios from 'axios'\n\nconst qs = require('qs')\n\nasync function getHeaders(accessToken) {\n return {\n headers: {\n Authorization: `Bearer ${await accessToken}`,\n },\n }\n}\n\nclass GmailAPI {\n constructor(obj) {\n this.accessToken = this.getAcceToken(obj)\n }\n\n async getAcceToken({ clientId, clientSecret, refreshToken }) {\n const data = qs.stringify({\n clientId,\n clientSecret,\n refreshToken,\n grant_type: 'refresh_token',\n })\n\n const config = {\n method: 'post',\n url: 'https://accounts.google.com/o/oauth2/token',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n data,\n }\n\n let accessToken = ''\n\n await axios(config)\n .then(async function (response) {\n accessToken = await response.data.access_token\n })\n .catch(function () {\n throw new Error(\n 'Some of the keys (id, clientId, clientSecret, refreshToken) are invalid'\n )\n })\n\n return accessToken\n }\n\n async searchGmail(searchItem) {\n const config1 = {\n method: 'get',\n url: `https://www.googleapis.com/gmail/v1/users/me/messages?q=${searchItem}`,\n ...(await getHeaders(this.accessToken)),\n }\n\n let threadId = ''\n\n await axios(config1)\n .then(async function (response) {\n threadId = await response.data.messages[0].id\n })\n .catch(function (error) {\n console.log('SearchGmail', error)\n })\n\n return threadId\n }\n\n async readGmailContent(messageId) {\n const config = {\n method: 'get',\n url: `https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}`,\n ...(await getHeaders(this.accessToken)),\n }\n\n let data = {}\n\n await axios(config)\n .then(async function (response) {\n data = await response.data\n })\n .catch(function (error) {\n console.log('ReadGmailContent', error)\n })\n\n return data\n }\n\n async readInboxContent(searchText) {\n const threadId = await this.searchGmail(searchText)\n const message = await this.readGmailContent(threadId)\n\n let encodedMessage = await message.payload?.parts\n let decodedStr = null\n\n if (encodedMessage) {\n encodedMessage = encodedMessage[0].body.data\n decodedStr = Buffer.from(encodedMessage, 'base64').toString('ascii')\n }\n\n return decodedStr\n }\n}\n\nmodule.exports = GmailAPI\n\n```" } ]
code_cy-runner_b8bc3576
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/apis.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport default {\n invoiceAPI: (baseUrl) => {\n return `${baseUrl}/api/oms/pvt/orders`\n },\n workFlowAPI: (baseUrl, orderId) => {\n return `${baseUrl}/api/oms/pvt/orders/${orderId}/workflow`\n },\n getOrderAPI: (baseUrl, orderId) => {\n return `${baseUrl}/api/oms/pvt/orders/${orderId}`\n },\n startHandlingAPI: (baseUrl, orderId) => {\n return `${baseUrl}/api/oms/pvt/orders/${orderId}/start-handling`\n },\n cancelOrderAPI: (baseUrl, orderId) => {\n return `${baseUrl}/api/oms/pvt/orders/${orderId}/cancel`\n },\n transactionAPI: (baseUrl) => {\n return `${baseUrl}/api/payments/pvt/transactions`\n },\n AdminLogin: (apiKey, apiToken) => {\n return `https://vtexid.vtex.com.br/api/vtexid/pub/authenticate/default?user=${apiKey}&pass=${apiToken}`\n },\n affiliationAPI: (id = null) => {\n const url = 'https://productusqa.myvtex.com/api/payments/pvt/affiliations'\n\n if (id) return `${url}/${id}`\n\n return url\n },\n getPickupPoints: (baseUrl) => {\n return `${baseUrl}/api/logistics/pvt/configuration/pickuppoints`\n },\n deletePickupPoint: (baseUrl, pickupPointid) => {\n return `${baseUrl}/api/logistics/pvt/configuration/pickuppoints/${pickupPointid}`\n },\n loadDocksAPI: (baseUrl) => {\n return `${baseUrl}/admin/shipping-strategy/loading-docks/`\n },\n calculateShippingAPI: (account, workspace) => {\n return `https://app.io.vtex.com/vtexus.fedex-shipping/v1/${account}/${workspace}/shp-rates/calculate`\n },\n}\n\n```" } ]
code_cy-runner_64dcb53a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/wipe.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { VTEX_AUTH_HEADER } from './constants.js'\n\nconst generateSearchURL = (baseUrl, entities, searchQuery) => {\n return `${baseUrl}/api/dataentities/${entities.id}/search?${entities.searchKey}=${searchQuery}`\n}\n\nconst generateDeleteURL = (baseUrl, entities, documentId) => {\n return `${baseUrl}/api/dataentities/${entities.id}/documents/${documentId}`\n}\n\nexport function searchInMasterData(entities, searchQuery) {\n cy.getVtexItems().then((vtex) => {\n cy.getAPI(\n generateSearchURL(vtex.baseUrl, entities, searchQuery),\n VTEX_AUTH_HEADER(vtex.apiKey, vtex.apiToken)\n ).then((response) => {\n expect(response.status).to.equal(200)\n\n return cy.wrap(response.body, { log: false })\n })\n })\n}\n\nexport function deleteDocumentInMasterData(entities, documentId) {\n cy.getVtexItems().then((vtex) => {\n cy.callRestAPIAndAddLogs({\n method: 'DELETE',\n url: generateDeleteURL(vtex.baseUrl, entities, documentId),\n })\n .its('status')\n .should('equal', 204)\n })\n}\n\n```" } ]
code_cy-runner_9bb4ee24
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/common/shipping-policy.graphql.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst config = Cypress.env()\n\n// Constants\nconst { vtex } = config.base\n\nfunction commonGraphlValidation(response) {\n expect(response.status).to.equal(200)\n expect(response.body.data).to.not.equal(null)\n expect(response.body).to.not.equal('OK')\n expect(response.body).to.not.have.own.property('errors')\n}\n\nexport function graphql(getQuery, validateResponseFn = null) {\n const { query, queryVariables } = getQuery\n\n const APP = 'vtex.logistics-carrier-graphql'\n const CUSTOM_URL = `${vtex.baseUrl}/_v/private/admin-graphql-ide/v0/${APP}`\n\n cy.callGraphqlAndAddLogs({\n url: CUSTOM_URL,\n query,\n variables: queryVariables,\n }).as('RESPONSE')\n\n if (validateResponseFn) {\n cy.get('@RESPONSE').then((response) => {\n commonGraphlValidation(response)\n validateResponseFn(response)\n })\n } else {\n return cy.get('@RESPONSE')\n }\n}\n\nexport function updateShippingPolicy(data, { status = true, pickup = true }) {\n data.shippingPolicy.isActive = status\n data.shippingPolicy.deliveryChannel = pickup ? 'pickup-in-point' : 'delivery'\n const query =\n 'mutation' +\n '( $shippingPolicy: ShippingPolicyInput!)' +\n '{updateShippingPolicy(shippingPolicy:$shippingPolicy){id, name}}'\n\n return {\n query,\n queryVariables: data,\n }\n}\n\n```" } ]
code_cy-runner_092b2c09
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/packing-optimization/api_testcase.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { packAll } from './apis.js'\nimport { updateRetry } from '../common/support'\n\nconst config = Cypress.env()\n\nconst { baseUrl, AccessKey } = config.base.vtex\n\nexport function pack(data) {\n it('Pack All', updateRetry(3), () => {\n cy.callRestAPIAndAddLogs({\n url: packAll(baseUrl),\n headers: {\n AccessKey,\n },\n body: data,\n }).then((response) => {\n expect(response.status).to.have.equal(200)\n expect(response.body.packedResults)\n .to.be.an('array')\n .and.to.have.lengthOf.above(0)\n })\n })\n}\n\n```" } ]
code_cy-runner_e4468a61
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/packing-optimization/apis.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport default {\n packAll: (baseUrl) => {\n return `${baseUrl}/packAll`\n },\n}\n\n```" } ]
code_cy-runner_3f7dc70e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/affirm/testcase.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { sendInvoiceTestCase, invoiceAPITestCase } from '../common/testcase.js'\nimport selectors from '../common/selectors.js'\nimport {\n updateRetry,\n saveOrderId,\n clickBtnOnVisibility,\n} from '../common/support.js'\n\nexport function initiatePayment({\n prefix,\n orderIdEnv,\n expectedPhoneNo = '(312) 310 3249',\n completePayment = false,\n externalSeller = false,\n retries = 0,\n}) {\n it(\n `In ${prefix} - Initiate payment ${\n completePayment ? ' and complete the payment' : ''\n }`,\n updateRetry(retries),\n () => {\n clickBtnOnVisibility(selectors.Profile)\n cy.get(selectors.Phone)\n .invoke('val')\n .then((phone) => {\n if (phone !== expectedPhoneNo) {\n cy.get(selectors.Phone)\n .should('be.visible')\n .clear()\n .type(expectedPhoneNo, {\n delay: 100,\n })\n }\n })\n\n clickBtnOnVisibility(selectors.GoToPayment)\n clickBtnOnVisibility(selectors.ProceedtoShipping)\n\n cy.get(selectors.AffirmPaymentOption, { timeout: 10000 })\n .should('be.visible')\n .click()\n cy.get(selectors.InstallmentContainer)\n .should('be.visible')\n .contains('Total')\n cy.get(selectors.BuyNowBtn).last().should('be.visible').click()\n\n // Complete Payment\n if (completePayment) {\n cy.getIframeBody('#checkout-application')\n .find(selectors.AffirmPhoneNumberField, { timeout: 45000 })\n .should('be.visible')\n .type('3123103249', { force: true })\n\n cy.getIframeBody('#checkout-application')\n .find(selectors.AffirmSubmit)\n .should('be.visible')\n .click()\n\n cy.getIframeBody('#checkout-application')\n .find(selectors.AffirmPhonePin)\n .should('be.visible')\n .type('1234', { force: true })\n\n cy.getIframeBody('#checkout-application', { timeout: 40000 })\n .find('h1')\n .should('have.text', \"You're approved!\")\n\n cy.getIframeBody('#checkout-application')\n .find(selectors.AffirmInstallmentOption)\n .first()\n .click()\n cy.getIframeBody('#checkout-application')\n .contains('AutoPay')\n .scrollIntoView()\n cy.getIframeBody('#checkout-application')\n .find(selectors.AffirmIndicatorOption)\n .click()\n\n cy.getIframeBody('#checkout-application')\n .find(selectors.AffirmDisClosureCheckbox)\n .scrollIntoView()\n .click()\n\n cy.getIframeBody('#checkout-application')\n .find(selectors.AffirmSubmit)\n .click()\n\n cy.getVtexItems().then((vtex) => {\n cy.intercept('POST', `${vtex.baseUrl}/**`, (req) => {\n if (req.body.operationName === 'OrderUpdate') {\n req.continue()\n }\n }).as('OrderUpdate')\n cy.getIframeBody('#checkout-application')\n .contains('Thanks')\n .should('be.visible')\n cy.wait('@OrderUpdate', { timeout: 50000 })\n })\n\n saveOrderId(orderIdEnv, externalSeller)\n } else {\n cy.log('Complete Payment is disabled')\n }\n }\n )\n}\n\nexport function completeThePayment(\n product,\n { orderIdEnv, transactionIdEnv, sendInvoice = true, completePayment = true },\n externalSellerTestcase = false\n) {\n const { prefix } = product\n\n initiatePayment({\n prefix,\n completePayment,\n orderIdEnv,\n externalSeller: externalSellerTestcase ? product : false,\n })\n\n if (sendInvoice) {\n sendInvoiceTestCase({ product, orderIdEnv })\n }\n\n // Get transactionId from invoiceAPI and store in .orders.json\n invoiceAPITestCase({\n product,\n env: orderIdEnv,\n transactionIdEnv,\n })\n}\n\n```" } ]
code_cy-runner_c43146a5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/affirm/api_testcase.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { updateRetry } from '../common/support.js'\n\nexport function verifyTransactionInAffirm(\n { prefix, totalProductPrice, refundType, refundedAmount },\n { paymentTidEnv, orderIdEnv },\n refund = ''\n) {\n it(`For ${prefix} - Verify Affirm Transaction`, updateRetry(6), () => {\n cy.addDelayBetweenRetries(4000)\n cy.getOrderItems().then((order) => {\n cy.getVtexItems().then((vtex) => {\n cy.getAPI(\n `https://sandbox.affirm.com/api/v1/transactions/${order[paymentTidEnv]}`,\n {\n username: vtex.appKey,\n password: vtex.appToken,\n }\n ).then((response) => {\n expect(response.status).to.equal(200)\n expect(response.body.status).to.equal(\n refund ? refundType : 'captured'\n )\n // Affirm returns orderId like this 1256770739305\n // So, In 1256770739305-01 use split by - and fetch 1256770739305\n expect(response.body.order_id).to.equal(\n order[orderIdEnv].split('-')[0]\n )\n // Affirm returns amount like this 108500\n // So, In 1085.00 remove . from total amount\n expect(response.body.amount).to.equal(\n parseInt(totalProductPrice.replace('.', '').replace(',', ''), 10)\n )\n expect(response.body.id).to.equal(order[paymentTidEnv])\n refund &&\n expect(response.body.amount_refunded).to.equal(refundedAmount)\n })\n })\n })\n })\n}\n\n```" } ]
code_cy-runner_1297f4b6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/affirm/outputvalidation.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { PRODUCTS } from '../common/utils'\n\nexport default {\n singleProduct: {\n prefix: 'singleProduct',\n postalCode: '33180',\n productPrice: '540.00',\n productName: PRODUCTS.coconut,\n productQuantity: '2',\n totalProductPrice: '1085.00',\n refundedAmount: 108500,\n refundType: 'refunded',\n },\n multiProduct: {\n prefix: 'multiProduct',\n postalCode: '33180',\n product1Name: PRODUCTS.coconut,\n product2Name: PRODUCTS.orange,\n productQuantity: '2',\n product1Price: '540.00',\n product2Price: '100.00',\n totalProductPrice: '1,183.33',\n refundedAmount: 108500,\n refundType: 'partially_refunded',\n },\n discountProduct: {\n prefix: 'discountProduct',\n postalCode: '33180',\n productName: PRODUCTS.cauliflower,\n productQuantity: '1',\n totalProductPrice: '95.00',\n totalAmount: '$ 95.00',\n refundedAmount: 9500,\n refundType: 'refunded',\n },\n discountShipping: {\n prefix: 'discountShipping',\n postalCode: '90290',\n productQuantity: '1',\n shippingLabel: 'Free',\n productName: PRODUCTS.orange,\n env: 'discountShippingOrder',\n totalProductPrice: '100.00',\n },\n externalSeller: {\n prefix: 'externalSeller',\n postalCode: '33180',\n product1Name: PRODUCTS.coconut,\n product2Name: PRODUCTS.tshirt,\n totalAmount: '$ 1,266.88',\n tax: '$ 82.88',\n directSaleAmount: '$ 1,160.95',\n directSaleTax: '$ 75.95',\n directSaleEnv: 'directSale',\n externalSellerAmount: '$ 105.93',\n externalSellerTax: '$ 6.93',\n externalSaleEnv: 'externalSale',\n subTotal: '$ 1,174.00',\n productQuantity: '2',\n product1Price: '540.00',\n },\n}\n\n```" } ]
code_cy-runner_310b931f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/affirm/graphql_testcase.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/expect-expect */\nimport { FAIL_ON_STATUS_CODE } from '../common/constants'\n\nconst config = Cypress.env()\n\n// Constants\nconst { vtex } = config.base\n\nfunction commonGraphlValidation(response) {\n expect(response.status).to.equal(200)\n expect(response.body.data).to.not.equal(null)\n expect(response.body).to.not.have.own.property('errors')\n}\n\nexport function graphql(getQuery, validateResponseFn = null) {\n const { query, queryVariables } = getQuery\n\n // Define constants\n const APP_NAME = 'vtex.affirm-payment'\n const APP = `${APP_NAME}@2.x`\n const CUSTOM_URL = `${vtex.baseUrl}/_v/private/admin-graphql-ide/v0/${APP}`\n\n cy.request({\n method: 'POST',\n url: CUSTOM_URL,\n body: {\n query,\n variables: queryVariables,\n },\n ...FAIL_ON_STATUS_CODE,\n }).as('RESPONSE')\n\n cy.addGraphqlLogs(query, queryVariables)\n\n if (validateResponseFn) {\n cy.get('@RESPONSE').then((response) => {\n commonGraphlValidation(response)\n validateResponseFn(response)\n })\n } else {\n return cy.get('@RESPONSE')\n }\n}\n\nexport function version() {\n return {\n query: 'query' + '{version}',\n queryVariables: {},\n }\n}\n\nexport function affirmSettings() {\n return {\n query:\n 'query' +\n '{affirmSettings{isLive,enableKatapult,companyName,publicApiKey}}',\n queryVariables: {},\n }\n}\n\nexport function orderData() {\n return {\n query: 'query' + '{orderData{reference}}',\n queryVariables: {},\n }\n}\n\nexport function orderUpdate(orderInfo) {\n const query =\n 'mutation' +\n '($inboundUrl: String, $orderId: String, $callbackUrl: String)' +\n '{orderUpdate(inboundUrl: $inboundUrl, orderId: $orderId, callbackUrl: $callbackUrl)}'\n\n return {\n query,\n queryVariables: orderInfo,\n }\n}\n\nexport function validateGetVersionResponse(response) {\n expect(response.body.data).to.not.equal(null)\n}\n\nexport function validateAffirmSettingsResponse(response) {\n expect(response.body.data).to.not.equal(null)\n expect(response.body.data.affirmSettings.publicApiKey).to.not.equal(null)\n}\n\nexport function validateOrderDataResponse(response) {\n expect(response.body.data).to.not.equal(null)\n}\n\nexport function validateOrderUpdateResponse(response) {\n expect(response.body.data).to.not.equal(null)\n}\n\n```" } ]
code_cy-runner_e5787757
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/quick-order/graphql.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport const APP = 'vtex.quickorder@*.x'\n\nexport function getSellers() {\n return {\n query:\n 'query' +\n '{sellers @context(provider: \"vtex.quickorder\")' +\n '{items{id,name}}}',\n queryVariables: {},\n }\n}\n\nexport function validateSellers(response) {\n expect(response.body.data.sellers.items).to.not.equal(null)\n expect(response.body.data.sellers.items).to.deep.include.members([\n {\n id: '1',\n name: 'VTEX',\n },\n {\n id: 'productusqa2',\n name: 'productusqa2',\n },\n ])\n}\n\nexport function getSkuFromRefIds(orderFormId) {\n return {\n query:\n 'query' +\n '($refids:[String],$orderFormId: String,$refIdSellerMap: RefIdSellerMap,$refIdQuantityMap: RefIdQuantityMap)' +\n '{skuFromRefIds(refids: $refids,refIdQuantityMap: $refIdQuantityMap,orderFormId:$orderFormId,refIdSellerMap:$refIdSellerMap)' +\n '{items{sku,refid,sellers{id,name,availability,unitMultiplier,availableQuantity}}}}',\n queryVariables: {\n refids: ['880320a'],\n orderFormId,\n refIdSellerMap: { '880320a': 100 },\n refIdQuantityMap: { '880320a': 100 },\n },\n }\n}\n\nexport function validateSkuFromRefIdsResponse(response) {\n expect(response.body.data.skuFromRefIds.items).to.not.equal(null)\n expect(response.body.data.skuFromRefIds.items).to.deep.include.members([\n {\n sku: '880320',\n refid: '880320a',\n sellers: [\n {\n availability: 'partiallyAvailable',\n availableQuantity: 50,\n id: '1',\n name: 'VTEX',\n unitMultiplier: 1,\n },\n ],\n },\n ])\n}\n\n```" } ]
code_cy-runner_3d37c065
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/quick-order/testcase.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport selectors from '../common/selectors.js'\nimport { fillQuoteInformation } from '../b2b/quotes.js'\nimport { BUTTON_LABEL, TOAST_MSG } from '../validation_text.js'\nimport { GRAPHL_OPERATIONS } from '../graphql_operations.js'\nimport { validateToastMsg, validateToolTipMsg } from '../b2b/utils.js'\nimport { updateRetry } from '../common/support.js'\n\nexport const POPUP_MSG = \"You can't have more than 50 items\"\nexport const TOOLTIP_MSG = {\n skuNotFound: /SKU Not Found/i,\n maxQuantity: /Max quantity is 50(.*)/i,\n}\n\nfunction ProceedToCheckOut() {\n cy.qe('Clicking on proceed to checkout')\n cy.get(selectors.ProceedToCheckOut).should('be.visible').click()\n}\n\nfunction fillSkuAndQuantity(textArea, validate, skuQuantity) {\n cy.qe(\n 'Fill the skuquantity ,check the validate text visibility and click on it'\n )\n cy.get(textArea).clear().type(skuQuantity, { force: true })\n cy.get(validate).should('be.visible').click()\n}\n\nfunction checkBackButtonIsVisible() {\n cy.qe('Checking the back button visisbility in the page')\n cy.closeMenuIfOpened()\n const [buttonsBlock, button] = [\n 'div[class*=buttonsBlock]',\n 'div[class*=vtex-button]',\n ]\n\n cy.get('body').then(($body) => {\n if ($body.find(buttonsBlock).length) {\n cy.get(button).contains(BUTTON_LABEL.back).click()\n }\n })\n}\n\nexport function quickOrderBySkuAndQuantityTestCase2(role, b2b = true) {\n it(\n `Verify ${role} is able remove invalid skus in quick order - [Sku's Code],[Quantity]`,\n updateRetry(2),\n () => {\n const { textArea, validate } = selectors.QuickOrderPage().skus\n\n cy.gotoQuickOrder(b2b)\n checkBackButtonIsVisible()\n fillSkuAndQuantity(textArea, validate, '880270a,2{enter}1,2{enter}')\n checkBackButtonIsVisible()\n }\n )\n}\n\nexport function quickOrderBySkuAndQuantityTestCase1(\n role,\n quoteEnv = false,\n totalPrice = '$180.00'\n) {\n const title = `Verify ${role} is able to ${\n quoteEnv\n ? 'create quote by quick order'\n : 'add product to cart & perform checkout'\n } - [Sku's Code],[Quantity]`\n\n it(title, updateRetry(2), () => {\n const { textArea, validate, invalid, content, addtoCart } =\n selectors.QuickOrderPage().skus\n\n cy.gotoQuickOrder(quoteEnv)\n checkBackButtonIsVisible()\n fillSkuAndQuantity(textArea, validate, '1,2{enter}')\n cy.get(invalid).should('be.visible')\n cy.get(content).clear().type('880270a,2{enter}').focus()\n cy.get(invalid).click()\n cy.qe(`Click on Add to cart`)\n cy.waitForGraphql(GRAPHL_OPERATIONS.addToCart, addtoCart)\n validateToastMsg(TOAST_MSG.addedToTheCart)\n cy.qe(`Open the cart and click on the first item`)\n cy.get(selectors.OpenCart).first().should('be.visible').click()\n cy.qe(`The minicart should contain the product name Cauliflower`)\n cy.get(selectors.MiniCartProductName).should('contain', 'Cauliflower')\n cy.qe(`Verifying the total price`)\n cy.get(selectors.TotalPrice).should('have.text', totalPrice)\n quoteEnv ? fillQuoteInformation({ quoteEnv }) : ProceedToCheckOut()\n })\n}\n\nexport function quickOrderBySkuAnd51QuantityTestCase(role, b2b = true) {\n it(\n `Verify ${role} is able to add 50 products to cart with 51 quantity by quick order - [Sku's Code],[Quantity]`,\n updateRetry(2),\n () => {\n const { textArea, validate, addtoCart } = selectors.QuickOrderPage().skus\n\n cy.gotoQuickOrder(b2b)\n checkBackButtonIsVisible()\n fillSkuAndQuantity(textArea, validate, '880270a,51{enter}')\n cy.qe('The addtoCart button should not exist')\n cy.get(addtoCart).should('not.exist')\n validateToolTipMsg(TOOLTIP_MSG.maxQuantity)\n }\n )\n}\n\nexport function quickOrderBySkuAndQuantityWithValidAndInValidSkuTestCase(\n role,\n b2b = true\n) {\n it(\n `Verify ${role} is not able to use one invalid & valid skus - [Sku's Code],[Quantity]`,\n updateRetry(2),\n () => {\n const { textArea, validate, addtoCart } = selectors.QuickOrderPage().skus\n\n cy.gotoQuickOrder(b2b)\n checkBackButtonIsVisible()\n fillSkuAndQuantity(textArea, validate, '880270a,51{enter}1,2{enter}')\n cy.qe('The addtoCart button should not exist')\n cy.get(addtoCart).should('not.exist')\n validateToolTipMsg(TOOLTIP_MSG.maxQuantity, 0)\n validateToolTipMsg(TOOLTIP_MSG.skuNotFound, 1)\n }\n )\n}\n\nfunction searchOneByOneProduct(search, { product, quantity }, number) {\n cy.qe(`Search for the product ${product}`)\n cy.get(search).should('be.visible').should('be.enabled').clear()\n cy.get(search).should('be.visible').type(product)\n // Product will be shown in results only after below selector gets visibled\n cy.get('button[class*=customOption]').should('be.visible')\n cy.get(search).type('{downarrow}{enter}')\n number > 1 &&\n cy\n .get(quantity, { timeout: 10000 })\n .should('be.visible')\n .clear()\n .type(`${number}`)\n}\n\nexport function quickOrderByOneByOneTestCase(\n role,\n product,\n quoteEnv,\n totalPrice = '$540.00'\n) {\n it(\n `Verify ${role} is able to ${\n quoteEnv ? 'create quote by' : 'use'\n } quick order - One by One`,\n updateRetry(2),\n () => {\n cy.gotoQuickOrder(quoteEnv)\n const { search, quantity, add } = selectors.QuickOrderPage().oneByOne\n\n searchOneByOneProduct(search, { product, quantity }, 1)\n cy.get(add).should('be.visible').click()\n cy.get(selectors.QuickOrderPage().popupMsgSelector).should('be.visible')\n cy.get(selectors.ToastMsgInB2B)\n .should('be.visible')\n .contains('added to the cart')\n cy.get(selectors.OpenCart).first().click()\n cy.get(selectors.MiniCartProductName).should('contain', product)\n cy.get(selectors.TotalPrice).should('have.text', totalPrice)\n quoteEnv && fillQuoteInformation({ quoteEnv })\n }\n )\n}\n\nexport function quickOrderByOneByOneNegativeTestCase(\n role,\n product,\n quoteEnv,\n totalPrice = '$27,000.00'\n) {\n it(\n `Verify ${role} is able to ${\n quoteEnv ? 'create quote by' : 'use'\n } quick order with 51 products - One by One`,\n updateRetry(2),\n () => {\n cy.gotoQuickOrder(quoteEnv)\n const { search, quantity, add } = selectors.QuickOrderPage().oneByOne\n\n searchOneByOneProduct(search, { product, quantity }, 51)\n cy.get(add).should('be.visible').click()\n cy.qe(`Verify the ${POPUP_MSG} in the QuickorderPage`)\n cy.get(selectors.QuickOrderPage().popupMsgSelector).contains(POPUP_MSG)\n cy.qe('Opening the cart and selecting the first item')\n cy.get(selectors.OpenCart).first().click()\n cy.qe(`Verifying if the mininCartproductname contains ${product}`)\n cy.get(selectors.MiniCartProductName)\n .should('be.visible')\n .should('contain', product)\n cy.qe(`Verifying the totalprice - ${totalPrice}`)\n cy.get(selectors.TotalPrice).should('have.text', totalPrice)\n cy.qe('The minicartQuantity should have the value of 50')\n cy.get(selectors.MiniCartQuantityForMaxOrder).should('have.value', '50')\n // Use the product which is already added in cart\n quoteEnv && fillQuoteInformation({ quoteEnv })\n }\n )\n}\n\nfunction quickOrderCategory(quoteEnv, number, totalPrice) {\n cy.gotoQuickOrder(quoteEnv)\n const { product, addtoCart, quantity } = selectors.QuickOrderPage().categories\n\n cy.qe('The addtoCart should be visible and it should contain the product')\n cy.get(addtoCart).should('be.visible')\n cy.qe(`Click the product - ${product}`)\n cy.contains(product).should('be.visible').click()\n cy.get(quantity, { timeout: 15000 })\n .first()\n .scrollIntoView()\n .clear({ timeout: 8000 })\n .type(number, { force: true })\n cy.qe('The addtoCart should be visible and we should click on the product')\n cy.get(addtoCart).should('be.visible').click()\n cy.get(selectors.ToastMsgInB2B, { timeout: 10000 })\n .should('be.visible')\n .contains(number > 50 ? POPUP_MSG : TOAST_MSG.addedToTheCart)\n cy.qe(`The openCart is visible and clickable`)\n cy.get(selectors.OpenCart).first().should('be.visible').click()\n cy.qe('The MiniCartProductname should contain Golf Shoes')\n cy.get(selectors.MiniCartProductName).should('contain', 'Golf Shoes')\n cy.qe(`Verifying the totalPrice - ${totalPrice}`)\n cy.get(selectors.TotalPrice).should('have.text', totalPrice)\n if (number > 50) {\n cy.get(selectors.MiniCartQuantityForMaxOrder).should('have.value', '50')\n }\n\n // Use the product which is already added in cart\n quoteEnv && fillQuoteInformation({ quoteEnv })\n}\n\nexport function quickOrderByCategory(role, quoteEnv, totalPrice = '$94.00') {\n it(\n `Verify ${role} is able ${\n quoteEnv ? `to create quote by` : `use`\n } quick order - Categories`,\n updateRetry(2),\n () => {\n quickOrderCategory(quoteEnv, 1, totalPrice)\n }\n )\n}\n\nexport function quickOrderByCategoryNegativeTestCase(\n role,\n quoteEnv,\n totalPrice = '$4,700.00'\n) {\n it(\n `Verify ${role} is able to create quote by quick order with 51 products - Categories`,\n updateRetry(2),\n () => {\n quickOrderCategory(quoteEnv, 51, totalPrice)\n }\n )\n}\n\nfunction validateForm(quoteEnv, vtex, productCount) {\n cy.qe('Adding intercept for validateForm')\n cy.intercept('POST', `${vtex.baseUrl}/**`).as('validateForm')\n // eslint-disable-next-line cypress/no-unnecessary-waiting\n cy.wait(5000)\n cy.qe('Verifying if AddToCart button is visible and clicking on it')\n cy.contains(BUTTON_LABEL.AddToCart).should('be.visible').click()\n cy.wait('@validateForm')\n cy.qe('Validate the Quantity in QuantityBadgeCart')\n cy.get(selectors.QuantityBadgeInCart, { timeout: 15000 }).should(\n 'have.text',\n productCount\n )\n cy.qe('Verifying if openCart is visible and then click on it')\n cy.get(selectors.OpenCart).first().should('be.visible').click()\n quoteEnv ? fillQuoteInformation({ quoteEnv }) : ProceedToCheckOut()\n}\n\nfunction uploadXLS(filePath, b2b) {\n const { deleteFile } = selectors.QuickOrderPage().uploadXLS\n\n cy.qe(`The profile should be visible on the QuickOrder home page`)\n cy.gotoQuickOrder(b2b)\n\n // If deleteFile selector exist then, it means we are retrying this testcase\n // close and upload CSV\n cy.get('body').then(($body) => {\n if ($body.find(deleteFile).length) {\n cy.get(deleteFile, { timeout: 10000 })\n .should('be.visible')\n .click({ multiple: true })\n }\n })\n cy.qe(`Check the backbutton visibility in the page`)\n checkBackButtonIsVisible()\n cy.qe(`Attaching the Xls file `)\n cy.get(selectors.QuickOrderPage().uploadXLS.file, {\n timeout: 10000,\n }).attachFile(filePath)\n cy.qe(`The validate button should be enabled, and visible; then click on it`)\n cy.get(selectors.QuickOrderPage().uploadXLS.validate)\n .should('be.visible')\n .should('be.enabled')\n .click()\n}\n\nexport function quickOrderByXLS(quoteEnv = false) {\n it(`Create quick order by uploading excel`, updateRetry(3), () => {\n cy.getVtexItems().then((vtex) => {\n cy.qe(`Pass the pathname to upload an XLS file`)\n const filePath = 'model-quickorder.xls'\n\n uploadXLS(filePath, quoteEnv)\n validateForm(quoteEnv, vtex, 2)\n })\n })\n}\n\nfunction validateNegativeTestCase() {\n cy.contains(BUTTON_LABEL.AddToCart).should('not.exist')\n}\n\nexport function quickOrderByXLSNegativeTestCase2(quoteEnv = false) {\n it(`Create quick order with above max quantity`, updateRetry(3), () => {\n const filePath = 'quickorder_with_max_quantity.xls'\n\n cy.qe('Uploading the XLS file with one valid and one invalid sku')\n uploadXLS(filePath, quoteEnv)\n cy.qe('The addToCart button should not exist')\n validateNegativeTestCase()\n cy.qe(`Validate the ${TOOLTIP_MSG.maxQuantity}`)\n validateToolTipMsg(TOOLTIP_MSG.maxQuantity)\n })\n}\n\nexport function quickOrderByXLSNegativeTestCase(quoteEnv) {\n it(\n `Create quick order by uploading xls with one valid and one invalid sku line item`,\n updateRetry(3),\n () => {\n const filePath = 'model-quickorder1.xls'\n\n cy.qe('Uploading the XLS file with one valid and one invalid sku')\n uploadXLS(filePath, quoteEnv)\n cy.qe(`Validate the ${TOOLTIP_MSG.maxQuantity}`)\n validateToolTipMsg(TOOLTIP_MSG.maxQuantity)\n cy.qe(`Validate the ${TOOLTIP_MSG.skuNotFound}`)\n validateToolTipMsg(TOOLTIP_MSG.skuNotFound, 1)\n cy.get('svg[class*=vtex__icon-delete]:nth-child(1)').last().click()\n cy.qe('Validate addToCart should not exist')\n validateNegativeTestCase()\n cy.qe(`Validate the ${TOOLTIP_MSG.maxQuantity}`)\n validateToolTipMsg(TOOLTIP_MSG.maxQuantity)\n }\n )\n}\n\nexport function verifyExcelFile(fileName, products) {\n it('verify the data and extension', updateRetry(3), () => {\n cy.qe(`The XLS data should be equal and it should be greater than one`)\n cy.task('readXlsx', {\n file: fileName,\n sheet: 'SheetJS',\n }).then((rows) => {\n expect(rows.length).to.be.greaterThan(1)\n expect(JSON.stringify(rows)).to.be.equal(JSON.stringify(products))\n })\n })\n}\n\n```" } ]
code_cy-runner_14486edc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/quick-order/product.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport const products = [\n {\n SKU: 'AB120',\n Quantity: 2,\n },\n {\n SKU: 'AB121',\n Quantity: 3,\n },\n {\n SKU: 'AB122',\n Quantity: 5,\n },\n {\n SKU: 'AB123',\n Quantity: 10,\n },\n {\n SKU: 'AB124',\n Quantity: 1,\n },\n {\n SKU: 'AB125',\n Quantity: 20,\n },\n]\n\n```" } ]
code_cy-runner_8ab99fed
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/location-availability/shipping-policy.json from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"ship1\": {\n \"shippingPolicy\": {\n \"numberOfItemsPerShipment\": 1,\n \"id\": \"sha1920ede3r\",\n \"name\": \"Test Shipping\",\n \"shippingMethod\": \"Normal (1234)\",\n \"carrierSchedule\": [\n {\n \"dayOfWeek\": 0,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 1,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 2,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 3,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 4,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 5,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 6,\n \"timeLimit\": \"23:59:59\"\n }\n ],\n \"pickupPointsSettings\": {\n \"pickupPointIds\": [\"1\", \"2\", \"3\"],\n \"pickupPointTags\": [],\n \"sellers\": []\n },\n \"shippingHoursSettings\": {\n \"shippingHours\": [\n {\n \"dayOfWeek\": 0,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 1,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 2,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 3,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 4,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 5,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 6,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n }\n ],\n \"acceptOrdersOutsideShippingHours\": true\n }\n }\n },\n \"ship2\": {\n \"shippingPolicy\": {\n \"numberOfItemsPerShipment\": 1,\n \"id\": \"LAS\",\n \"name\": \"Location Availability Shipping\",\n \"shippingMethod\": \"Normal (1234) (P1)\",\n \"carrierSchedule\": [\n {\n \"dayOfWeek\": 0,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 1,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 2,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 3,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 4,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 5,\n \"timeLimit\": \"23:59:59\"\n },\n {\n \"dayOfWeek\": 6,\n \"timeLimit\": \"23:59:59\"\n }\n ],\n \"pickupPointsSettings\": {\n \"pickupPointIds\": [\"4\"],\n \"pickupPointTags\": [],\n \"sellers\": []\n },\n \"shippingHoursSettings\": {\n \"shippingHours\": [\n {\n \"dayOfWeek\": 0,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 1,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 2,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 3,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 4,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 5,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n },\n {\n \"dayOfWeek\": 6,\n \"ranges\": [\n {\n \"openingTime\": \"00:00:00\",\n \"closingTime\": \"23:59:59\"\n }\n ]\n }\n ],\n \"acceptOrdersOutsideShippingHours\": true\n }\n }\n }\n}\n\n```" } ]
code_cy-runner_3cf9183e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/location-availability/support.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport selectors from '../common/selectors'\nimport { updateRetry } from '../common/support'\nimport { getPickupPoints, deletePickupPoint } from './pickup-points.api'\n\nexport function verifyUpdatedAddress(postalCode, address, city, state) {\n it('Verify on click to postal code it opens the location popup', () => {\n cy.qe('In specification page clicking on address container')\n cy.get(selectors.AvailabilityHeader).click()\n cy.qe(\n 'Once address container clicked, it will show an popup of layout to add shipping address'\n )\n cy.get(selectors.AddressModelLayout).should('be.visible')\n cy.get(selectors.countryDropdown).select('USA')\n cy.get(selectors.addressInputContainer).eq(0).clear().type(postalCode)\n if (city) {\n cy.get(selectors.Address)\n .contains('City')\n .parent()\n .within(() => {\n cy.get(selectors.InputText)\n .should('not.have.value', '')\n .clear()\n .type(city)\n })\n }\n\n if (address) {\n cy.get(selectors.Address)\n .contains('Address Line 1')\n .parent()\n .within(() => {\n cy.get(selectors.InputText).clear().type(address, { delay: 50 })\n })\n }\n\n if (state) {\n cy.get(selectors.ProvinceField).should('exist').select(state)\n }\n\n cy.waitForGraphql('setRegionId', selectors.SaveButtonInChangeLocationPopUp)\n cy.once('uncaught:exception', () => false)\n })\n it('Verify updated address is shown in the screen', updateRetry(2), () => {\n cy.get(selectors.AvailabilityHeader).should('have.text', postalCode)\n cy.get(selectors.AddtoCart)\n .contains(/Add to Cart/i)\n .click({ force: true })\n cy.get(selectors.ProceedtoCheckout).click()\n cy.get(selectors.orderButton).should('be.visible').click()\n })\n}\n\nexport function addPickUpPoint(pickPointName, pickUpId) {\n cy.qe('Clicking Add Pickup Point button in admin')\n cy.contains(/Add Pickup Point/i).click()\n cy.qe('Type a new pickuppoint name')\n cy.get(selectors.PickUpPointName).clear().type(pickPointName)\n cy.qe('Type a new pickuppoint id')\n cy.get(selectors.PickUpPointId).should('be.visible').type(pickUpId)\n cy.qe('Select a USA country')\n cy.get('select')\n .select('United States of America')\n .should('have.value', 'USA')\n /* eslint-disable cypress/no-unnecessary-waiting */\n cy.wait(1000)\n /* eslint-disable cypress/no-unnecessary-waiting */\n cy.qe('Type a street address')\n cy.get(selectors.PickUpAddress)\n .type('1481 Maple View Dr,Promona,CA,USA', { delay: 50 })\n .wait(500)\n .type('{downarrow}{enter}')\n cy.get(selectors.CheckBox).click()\n cy.qe('Adding business hours')\n cy.get(selectors.WorkStartTime).eq(1).type('10:00')\n cy.get(selectors.WorkEndTime).eq(1).type('19:00')\n cy.get(selectors.SaveChanges).click()\n cy.qe(\"Once save button clicked it show an popup as 'Changes saved'\")\n cy.get(selectors.ChangesSaved).should('be.visible').contains('Changes saved')\n cy.contains('Back to pickup points').click()\n}\n\nexport function deleteAllPickupPoints() {\n const FILTER_PICKUP_POINT_KEY = 'Location availability'\n\n it(\n `Filter and delete pickup point which starts with \"${FILTER_PICKUP_POINT_KEY}\"`,\n updateRetry(5),\n () => {\n cy.getVtexItems().then((vtex) => {\n cy.getAPI(getPickupPoints(vtex.baseUrl)).then((response) => {\n // Pickup points created in E2E tests should start with text \"pickup example\"\n // If we create other pickup points then it will not be deleted in wipe\n const filterPickUpPoints = response.body.filter((b) =>\n b.name.includes(FILTER_PICKUP_POINT_KEY)\n )\n\n if (filterPickUpPoints.length > 0) {\n for (const element of filterPickUpPoints) {\n cy.callRestAPIAndAddLogs({\n method: 'DELETE',\n url: deletePickupPoint(vtex.baseUrl, element.id),\n }).then((deleteResponse) => {\n expect(deleteResponse.status).to.equal(204)\n })\n }\n }\n })\n })\n }\n )\n}\n\n```" } ]
code_cy-runner_2fbb65e7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/location-availability/pickup-points.api.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport default {\n getPickupPoints: (baseUrl) => {\n return `${baseUrl}/api/logistics/pvt/configuration/pickuppoints`\n },\n deletePickupPoint: (baseUrl, pickupPointid) => {\n return `${baseUrl}/api/logistics/pvt/configuration/pickuppoints/${pickupPointid}`\n },\n}\n\n```" } ]
code_cy-runner_4deeea4e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/location-availability/common.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport selectors from '../common/selectors'\n\nexport function verifyHomePage(city, postalCode, distance = false) {\n cy.scrollTo(0, 500)\n cy.getVtexItems().then((vtex) => {\n cy.intercept('POST', `${vtex.baseUrl}/**`, (req) => {\n if (req.body.operationName === 'updateOrderFormShipping') {\n req.continue()\n }\n }).as('updateOrderFormShipping')\n // eslint-disable-next-line cypress/no-unnecessary-waiting\n cy.wait(10000)\n cy.get(selectors.addressContainer).should('be.visible')\n if (distance) {\n cy.get(selectors.Distance).should('not.exist')\n cy.get(selectors.shippingInfo).contains('Get it in')\n } else {\n cy.get(selectors.AddressCity).contains(city)\n cy.get(selectors.AddressZip).contains(postalCode)\n cy.get(selectors.Distance).contains('Distance:')\n cy.wait('@updateOrderFormShipping', { timeout: 20000 })\n }\n })\n}\n\n```" } ]
code_cy-runner_1b376bc5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/location-availability/product.js from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport default {\n orange: {\n name: 'Navel Oranges Grown Large Fresh Fruit',\n link: 'a[href*=\"/navel-oranges-grown-large-fresh-fruit/p\"]',\n },\n coconut: {\n name: 'Fresh Coconuts',\n link: 'a[href=\"/fresh-coconuts/p\"]',\n },\n}\n\n```" } ]
code_cy-runner_1cde1121
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/fedex-shipping-fixtures/shippingOptimizePayload.json from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"data\": {\n \"items\": [\n {\n \"id\": \"880350\",\n \"quantity\": 1,\n \"groupId\": null,\n \"unitPrice\": 94.0,\n \"modal\": \"\",\n \"unitDimension\": {\n \"weight\": 10,\n \"height\": 10,\n \"width\": 10,\n \"length\": 10\n }\n },\n {\n \"id\": \"80008075\",\n \"quantity\": 1,\n \"groupId\": null,\n \"unitPrice\": 139.0,\n \"modal\": \"\",\n \"unitDimension\": {\n \"weight\": 12,\n \"height\": 16,\n \"width\": 16,\n \"length\": 10\n }\n }\n ],\n \"origin\": {\n \"zipCode\": \"33020\",\n \"country\": \"USA\",\n \"state\": \"FL\",\n \"city\": \"Hollywood\",\n \"coordinates\": null,\n \"residential\": false\n },\n \"destination\": {\n \"zipCode\": \"00010002\",\n \"country\": \"USA\",\n \"state\": null,\n \"city\": null,\n \"coordinates\": null,\n \"residential\": false\n },\n \"shippingDateUTC\": \"2022-05-31T01:02:45.128577+00:00\",\n \"currency\": null\n }\n}\n\n```" } ]
code_cy-runner_f7ad9775
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/fedex-shipping-fixtures/shippingRatePayload.json from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"data\": {\n \"items\": [\n {\n \"id\": \"880340\",\n \"quantity\": 1,\n \"groupId\": null,\n \"unitPrice\": 500.0,\n \"modal\": \"\",\n \"unitDimension\": {\n \"weight\": 10.0,\n \"height\": 10,\n \"width\": 10,\n \"length\": 10\n }\n }\n ],\n \"origin\": {\n \"zipCode\": \"33020\",\n \"country\": \"USA\",\n \"state\": \"FL\",\n \"city\": \"Hollywood\",\n \"coordinates\": null,\n \"residential\": false\n },\n \"destination\": {\n \"zipCode\": \"00010002\",\n \"country\": \"USA\",\n \"state\": null,\n \"city\": null,\n \"coordinates\": null,\n \"residential\": false\n },\n \"shippingDateUTC\": \"2022-05-31T01:02:45.128577+00:00\",\n \"currency\": null\n }\n}\n\n```" } ]
code_cy-runner_7f3d26ce
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/fedex-shipping-fixtures/multiProductPayload.json from the cy-runner VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"data\": {\n \"items\": [\n {\n \"id\": \"880340\",\n \"quantity\": 1,\n \"groupId\": null,\n \"unitPrice\": 94.0,\n \"modal\": \"\",\n \"unitDimension\": {\n \"weight\": 10,\n \"height\": 10,\n \"width\": 10,\n \"length\": 10\n }\n },\n {\n \"id\": \"880330\",\n \"quantity\": 1,\n \"groupId\": null,\n \"unitPrice\": 94.0,\n \"modal\": \"\",\n \"unitDimension\": {\n \"weight\": 10,\n \"height\": 10,\n \"width\": 10,\n \"length\": 10\n }\n }\n ],\n \"origin\": {\n \"zipCode\": \"33020\",\n \"country\": \"USA\",\n \"state\": \"FL\",\n \"city\": \"Hollywood\",\n \"coordinates\": null,\n \"residential\": false\n },\n \"destination\": {\n \"zipCode\": \"00010002\",\n \"country\": \"USA\",\n \"state\": null,\n \"city\": null,\n \"coordinates\": null,\n \"residential\": false\n },\n \"shippingDateUTC\": \"2022-05-31T01:02:45.128577+00:00\",\n \"currency\": null\n }\n}\n\n```" } ]
code_suiteshare_b8687c79
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of suiteshare/docs/README.md from the suiteshare VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Suiteshare\n[Suiteshare](https://apps.vtex.com/vtex-suite-share/p) is a sales and service platform for WhatsApp, and with this app, you can:\n- Create solutions to attract and capture more customers.\n- Organize your support team’s demands.\n- Analyze the results to find out where your customers are.\n- Optimize your campaigns.\n\nThis app integrates your store with the Suiteshare platform, adding the WhatsApp widget to all pages. The Suiteshare widget provides easy access for communication through Whatsapp and includes several configurations, triggers, and personalized messages customized on their platform.\n\n>Suiteshare app is only compatible with IO Stores.\n\n\n## Step by Step\n1. Go to [VTEX App Store](https://apps.vtex.com/vtex-suite-share/p).\n2. Click on the button _GET APP_.\n3. Type your account and click on _CONFIRM_.\n4. Click on _PLACE ORDER_ to finish your purchase and agree with Suiteshare terms and conditions.\n\n\n>The app purchase is free. However, it requires an external subscription to the service provided by Suiteshare, which you can do on [Suiteshare page](https://suiteshare.com).\n\n\n5. Go to the app settings and type your _Suiteshare Id_. You can find your Suiteshare Id on the main Suiteshare dashboard. It is the last code on the installation instructions, and you type only the characters in, for example:\n\n `ba776dfa9e2fe90641696945dfea429113110686`\n\n![SuiteshareId](https://user-images.githubusercontent.com/1629129/119191255-c0d2ed00-ba54-11eb-94a1-13027c6c1c51.png)\n \nAfter completing the app installation and setup, you are all set! Additional settings can be found in your [Suiteshare account](https://suiteshare.com/auth/signin).\n\n\n\n```" } ]
code_suiteshare_3925e791
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of suiteshare/public/metadata/messages/es-AR.json from the suiteshare VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Suiteshare\",\n \"headline\": \"Integre su tienda con la plataforma Suiteshare.\",\n \"overview\": \"Esta aplicación se integra con la plataforma Suiteshare, agregando un botón para whatsapp en todas las páginas.\\\\nEl widget proporciona al cliente un fácil acceso para comunicarse a través de Whatsapp y tiene varias configuraciones, disparadores y mensajes personalizados configurados en Suiteshare.\",\n \"features\": [\n \"Hace que el widget de WhatsApp de Suiteshare esté disponible en todas las páginas\"\n ],\n \"additionalInformation\": \"Para utilizar esta app, es necesario tener una cuenta de Suiteshare activa y configurar el ID de integración en la configuración de la app.\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n```" } ]
code_suiteshare_dd93ef8d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of suiteshare/public/metadata/messages/pt-BR.json from the suiteshare VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Suiteshare\",\n \"headline\": \"Integre sua loja com a plataforma Suiteshare.\",\n \"overview\": \"Este aplicativo realiza a integração com a plataforma Suiteshare, adicionando um botão para o whatsapp em todas as páginas.\\\\nO widget promove ao cliente um fácil acesso para comunicação via Whatsapp e possui diversas configurações, gatilhos, e mensagens personalizadas configurados pelo Suiteshare.\",\n \"features\": [\n \"Disponibiliza o widget de whatsapp da Suiteshare em todas as páginas\"\n ],\n \"additionalInformation\": \"Para utilizar esse App é necessário ter uma conta ativa no Suiteshare e configurar o ID de integração nas configurações do App.\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n```" } ]
code_suiteshare_0532fd3b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of suiteshare/public/metadata/messages/en-US.json from the suiteshare VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Suiteshare\",\n \"headline\": \"Integrate your store with the Suiteshare platform.\",\n \"overview\": \"This app integrates your store with the Suiteshare platform, adding the whatsapp widget to all pages.\\\\nThe widget provides the customer an easy access for communication through Whatsapp and includes several configurations, triggers, and personalized messages and can be customized on Suiteshare.\",\n \"features\": [\n \"Adds Suiteshare's whatsapp widget to all store pages\"\n ],\n \"additionalInformation\": \"In order to use this app you need to have an active account on Suiteshare and configure your integration ID in the App Settings.\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n```" } ]
code_external-promotion-provider-middleware_a85fd348
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/docs/README.md from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Promotion Provider Middleware\n\n## ⚠️ Maintenance ⚠️\n*Starting June 1st 2023, this application will no longer be maintained by VTEX.*\n\n---\n\nThis app allows external providers to apply promotions to any SKUs in the shopping cart during an end-user checkout experience.\n\n## Getting Started\n\nYou can install it through the command-line interface:\n\n```\nvtex install vtex.promotion-provider-middleware@0.x\n```\n\nRight after installation, the external endpoint needs to be set. To make this configuration, go to the page `https://{{accountName}}.myvtex.com/admin/apps` , search for `Promotion Provider Middleware`, click on the Settings button, set the External Endpoint and save your configurations.\n\nUpon saving the settings, this application will set the whole environment to comply with its necessities, meaning that the following actions will be done automatically by the app:\n\n* `allowManualPrice` will be set to `true` in the [orderForm Configurations](https://developers.vtex.com/vtex-rest-api/reference/configuration#getorderformconfiguration);\n* Create a new object in the `apps` array at [orderForm Configurations](https://developers.vtex.com/vtex-rest-api/reference/configuration#getorderformconfiguration), this allows your promotions data to be stored in the customData object (inside orderForm) for every order.\n\nUpon installing, the public routes will become instantly available to use.\n\nIt's worth mentioning that Order Authorization configurations could interfere with key functional aspects of this application. If the account has any Manual Discount rules configured, make sure to verify if the promotions applied by the external provider comply with the range set in Manual Discount rules. The reason for the impact is that this application makes use of [Update cart items](https://developers.vtex.com/vtex-rest-api/reference/cart-update#itemsupdate) to apply discounts.\n\n## Syntax and Supported Routes\n\n### Notification:\n`POST /_v/promotion-provider/notification`\n\nThis route is responsible for consulting the external provider and applying the discounts afterwards.\n\nAll this route needs to be initiated is the cookie `checkout.vtex.com` containing the orderformId in the format `__ofid={{orderFormId}}`. After receiving this cookie in the headers, the middleware will go through the following steps:\n\n* Fetch the orderForm through the orderFormId sent inside the cookie;\n* Clean all manual prices currently active in the orderForm;\n* Parse the orderForm according to the protocol (more details later on);\n* Send the payload to the external provider.\n\n> 🔎 It is worth mentioning that there's a 12.5 seconds timeout attributed to the external provider with 0 retries. Meaning that the external provider has this exact time to deliver a response to our application.\nThe object sent to the external provider looks like the following:\n> Observation: The objects customData, shippingData, clientProfileData, paymentData are exactly the same as seen in the orderForm.\n```typescript\ninterface ExternalPromotionsRequestProtocol {\n items: {\n id: string\n productId: string\n refId?: any\n ean: string\n name: string\n skuName: string\n modalType?: any\n productCategoryIds: string\n productCategories: ProductCategories\n availability: string\n measurementUnit: string\n variations: {\n index: number\n assemblies: any[]\n tax: number\n price: number\n listPrice: number\n manualPrice?: any\n sellingPrice: number\n isGift: boolean\n quantity: number\n attachments: Attachment[]\n attachmentOfferings: AttachmentOffering[]\n offerings: any[]\n priceTags: PriceTag[]\n unitMultiplier: number\n seller: string\n sellerChain: string[]\n }[]\n }[]\n customData: CustomData\n shippingData: ShippingData\n clientProfileData: ClientProfileData\n marketingData?: MarketingData\n paymentData: PaymentData\n totalizers: {\n id: string\n name: string\n value: number\n }[]\n}\n```\n\nWhen it comes to the external provider response, we expect the following objects (example at the end of this documentation):\n\n```typescript\ninterface ExternalPromotionsResponseProtocol {\n items: {\n id: number\n variations: {\n requestIndex: number\n quantity: number\n externalPromotions: {\n matchedParameters: {[key: string]: string}\n identifier: string\n isPercentual: boolean\n value: number\n }[]\n }[]\n }[]\n}\n```\n\nIt's important to notice that in cases where `isPercentual` is `true`, the `value` property should contain numbers between `0` and `1`, for example: `0.35`. If `isPercentual` is `false`, the `value` property should have negative values such as `-100` or `-2500` for a nominal discount of $1,00 and $25,00 respectively.\n\nThe `requestIndex` field (present in the external provider response) should match the index from the payload sent while also respecting it's variations. If the payload sent has 3 SKU's, but 1 SKU has 2 variations (due to split index), then your request index could vary from 0 to 4. If this is not respected, the middleware will throw an error and not apply any discount.\n\n> 🚨 Warning: The `items` array (present in the external provider response) should <strong>only</strong> contain the items that will be affected by any promotion. If no items should be impacted, then the `items` array should be sent empty.\n\nAnother important observation is that the discount will be applied over the summed `price` of the skuId based on its quantity. Also worth mentioning that percentual discounts will be applied first and nominal discounts afterwards.\n\n> ❗ Reminder: We are talking about the `price` property as found in the orderForm, we are <strong>not</strong> talking about `sellingPrice` nor `listPrice`.\n\nThe `matchedParameters` property should have `key` and `value` as strings with a maximum of 50 characters.\n\nAfter the external provider response, if it all went well, the middleware will use the API [Update cart items](https://developers.vtex.com/vtex-rest-api/reference/cart-update#itemsupdate) to update the prices in the cart respecting the discounts sent.\n\nAn important reminder, every promotion configured in the promotions module is equipped with a flag called `Allows accumulate with manual prices`, if this flag is checked, first the external promotion will be applied, and only then the other promotions will apply. If this flag remains unchecked, when the external promotion gets applied, the respective promotion will not be applied.\n\n### Simulation:\n`POST /_v/promotion-provider/simulation`\n\nThis route is only responsible for consulting the external provider, and <strong>does not</strong> apply discounts.\n\nIn order to put this route in use, all you need to do is send a request body containing the `items` array, which for this route is exactly the same as it is in the orderForm.\n\nBesides the `items` array, you could also send `customData`, `shippingData`, `clientProfileData`, `marketingData`, `paymentData`.\n\n> Observation: The only field required in this request is the `id` property inside each object present in the `items` array.\n\n## External Provider Response Example (Response Body):\n\n```json\n{\n \"items\": [\n {\n \"id\": 33, //required\n \"variations\": [\n {\n \"requestIndex\": 0, //required\n \"quantity\": 1, //required\n \"externalPromotions\": [\n {\n \"matchedParameters\": {\n \"slaIds\": \"transportadora genérica\"\n },\n \"identifier\": \"anyName\",\n \"isPercentual\": false, //required\n \"value\": -200 //required\n },\n {\n \"matchedParameters\": {\n \"skuId\": \"33\"\n },\n \"identifier\": \"10off\",\n \"isPercentual\": true, //required\n \"value\": 0.10 //required\n }\n ]\n },\n {\n \"requestIndex\": 1, //required\n \"quantity\": 1, //required\n \"externalPromotions\": [\n {\n \"isPercentual\": true, //required\n \"value\": 0.50 //required\n }\n ]\n }\n ]\n }\n ]\n}\n```\n\n```" } ]
code_external-promotion-provider-middleware_14eb6568
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/service.json from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 120,\n \"timeout\": 30,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"workers\": 1,\n \"routes\": {\n \"orderFormNotification\": {\n \"path\": \"/_v/promotion-provider/notification\",\n \"public\": true\n },\n \"simulation\": {\n \"path\": \"/_v/promotion-provider/simulation\",\n \"public\": true\n }\n },\n \"events\": {\n \"onAppInstalled\": {\n \"sender\": \"apps\",\n \"keys\": [\"setup\"],\n \"settingsType\": \"workspace\"\n },\n \"onSettingsChanged\": {\n \"sender\": \"apps\",\n \"keys\": [\"settings\"]\n }\n }\n}\n\n```" } ]
code_external-promotion-provider-middleware_4c555647
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/package.json from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"@vtex/clients\": \"^2.13.0\",\n \"co-body\": \"^6.0.0\",\n \"ramda\": \"^0.25.0\",\n \"yup\": \"^0.32.9\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.12\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"typescript\": \"3.9.7\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\",\n \"test\": \"vtex-test-tools test --collectCoverage\"\n },\n \"version\": \"0.24.6\"\n}\n\n```" } ]
code_external-promotion-provider-middleware_13fd54d2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/index.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n ClientsConfig,\n ServiceContext,\n RecorderState,\n EventContext,\n} from '@vtex/api'\nimport { method, LRUCache, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport {\n setupAppConfiguration,\n getOrderFormById,\n calculateExternalBenefits,\n applyManualPrices,\n getAppConfiguration,\n} from './middlewares'\nimport type { CheckoutOrderForm } from './typings/global'\nimport type { ExternalPromotionsRequestProtocol } from './typings/protocol/request'\nimport type { ExternalPromotionsResponseProtocol } from './typings/protocol/response'\n\nconst TIMEOUT_MS = 5500\n\n// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.\nconst memoryCache = new LRUCache<string, any>({ max: 5000 })\n\nmetrics.trackCache('get-benefits', memoryCache)\n\n// This is the configuration for clients available in `ctx.clients`.\nconst clients: ClientsConfig<Clients> = {\n // We pass our custom implementation of the clients bag, containing the Status client.\n implementation: Clients,\n options: {\n // All IO Clients will be initialized with these options, unless otherwise specified.\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n },\n}\n\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\n type Context = ServiceContext<Clients, State>\n\n interface InstalledAppEvent extends EventContext<Clients> {\n body: { id?: string }\n }\n\n interface State extends RecorderState {\n orderForm: CheckoutOrderForm\n orderFormId?: string\n appSettings: { externalEndpoint?: string }\n externalProviderResponse: ExternalPromotionsResponseProtocol\n parsedRequestProtocol: ExternalPromotionsRequestProtocol\n }\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service({\n clients,\n routes: {\n orderFormNotification: method({\n POST: [\n getAppConfiguration,\n getOrderFormById,\n calculateExternalBenefits,\n applyManualPrices,\n ],\n }),\n simulation: method({\n POST: [getAppConfiguration, calculateExternalBenefits],\n }),\n },\n events: {\n onAppInstalled: setupAppConfiguration,\n onSettingsChanged: setupAppConfiguration,\n },\n})\n\n```" } ]
code_external-promotion-provider-middleware_b65ae79c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/clients/externalProvider.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nimport type { ExternalPromotionsRequestProtocol } from '../typings/protocol/request'\nimport type { ExternalPromotionsResponseProtocol } from '../typings/protocol/response'\n\nconst TIMEOUT_EXTERNAL = 12500\n\nexport default class ExternalProvider extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context.settings.externalEndpoint, context, options)\n }\n\n public async getBenefits(\n payload: ExternalPromotionsRequestProtocol\n ): Promise<ExternalPromotionsResponseProtocol> {\n try {\n const response = await this.http.post<ExternalPromotionsResponseProtocol>(\n '/',\n payload,\n {\n metric: 'get-benefits',\n timeout: TIMEOUT_EXTERNAL,\n timeoutErrorMessage:\n 'Timeout waiting for response from external provider',\n retries: 0,\n }\n )\n\n return response\n } catch (err) {\n throw new Error(\n `External endpoint (${this.context.settings.externalEndpoint}) returned error. ${err}`\n )\n }\n }\n}\n\n```" } ]
code_external-promotion-provider-middleware_8c39c94d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/clients/index.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\nimport { Checkout } from '@vtex/clients'\n\nimport ExternalProvider from './externalProvider'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get checkout() {\n return this.getOrSet('checkout', Checkout)\n }\n\n public get externalProvider() {\n return this.getOrSet('externalProvider', ExternalProvider)\n }\n}\n\n```" } ]
code_external-promotion-provider-middleware_cc64c3f6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/constants/orderFormConfiguration.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { OrderFormConfiguration } from '@vtex/clients'\n\nexport const orderFormConfigurationConstant = {\n allowManualPrice: true,\n apps: [\n {\n fields: ['externalPromotions'],\n id: 'promotion-provider-middleware',\n major: 0,\n },\n ],\n} as OrderFormConfiguration\n\n```" } ]
code_external-promotion-provider-middleware_afce92db
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/typings/global.d.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface CheckoutOrderForm {\n orderFormId: string\n salesChannel: string\n loggedIn: boolean\n isCheckedIn: boolean\n storeId?: any\n checkedInPickupPointId?: any\n allowManualPrice: boolean\n canEditData: boolean\n userProfileId: string | null\n userType?: any\n ignoreProfileData: boolean\n value: number\n messages: Message[]\n items: Item[]\n selectableGifts: any[]\n totalizers: Totalizer[]\n shippingData: ShippingData\n clientProfileData: ClientProfileData\n paymentData: PaymentData\n marketingData?: any\n sellers: Seller[]\n clientPreferencesData: ClientPreferencesData\n commercialConditionData?: any\n storePreferencesData: StorePreferencesData\n giftRegistryData?: any\n openTextField?: any\n invoiceData?: any\n customData: CustomData\n itemMetadata: ItemMetadata\n hooksData?: any\n ratesAndBenefitsData: RatesAndBenefitsData\n subscriptionData: SubscriptionData\n itemsOrdination?: any\n}\n\nexport interface Message {\n code?: any\n text: string\n status: string\n fields: any\n}\n\nexport interface AdditionalInfo {\n dimension?: any\n brandName: string\n brandId: string\n offeringInfo?: any\n offeringType?: any\n offeringTypeId?: any\n}\n\nexport interface ProductCategories {\n [key: string]: string\n}\n\nexport interface Content {\n [key: string]: any\n}\n\nexport interface Attachment {\n name: string\n content: Content\n}\n\nexport interface Schema {\n [key: string]: any\n}\n\nexport interface AttachmentOffering {\n name: string\n required: boolean\n schema: Schema\n}\n\nexport interface MatchedParameters {\n [key: string]: any\n}\n\nexport interface RatesAndBenefitsIdentifier {\n id: string\n name: string\n featured: boolean\n description?: any\n matchedParameters: MatchedParameters\n additionalInfo?: any\n}\n\nexport interface PriceTag {\n name: string\n value: number\n rawValue: number\n isPercentual: boolean\n identifier: string\n ratesAndBenefitsIdentifier: RatesAndBenefitsIdentifier\n}\n\nexport interface SellingPrice {\n value: number\n quantity: number\n}\n\nexport interface PriceDefinition {\n calculatedSellingPrice: number\n total: number\n sellingPrices: SellingPrice[]\n}\n\nexport interface Item {\n uniqueId?: string\n id: string\n productId?: string\n productRefId?: string\n refId?: string\n ean?: string\n name?: string\n skuName?: string\n modalType?: any\n parentItemIndex?: any\n parentAssemblyBinding?: any\n assemblies?: any[]\n priceValidUntil?: Date\n tax?: number\n price?: number\n listPrice?: number\n manualPrice?: number\n manualPriceAppliedBy?: string\n sellingPrice?: number\n rewardValue?: number\n isGift?: boolean\n additionalInfo?: AdditionalInfo\n preSaleDate?: any\n productCategoryIds?: string\n productCategories?: ProductCategories\n quantity: number\n seller?: string\n sellerChain?: string[]\n imageUrl?: string\n detailUrl?: string\n components?: any[]\n bundleItems?: any[]\n attachments?: Attachment[]\n attachmentOfferings?: AttachmentOffering[]\n offerings?: any[]\n priceTags?: PriceTag[]\n availability?: string\n measurementUnit?: string\n unitMultiplier?: number\n manufacturerCode?: any\n priceDefinition?: PriceDefinition\n}\n\nexport interface Totalizer {\n id: string\n name: string\n value: number\n}\n\nexport interface Address {\n addressType: string\n receiverName: string\n addressId: string\n isDisposable: boolean\n postalCode: string\n city: string\n state: string\n country: string\n street: string\n number: string\n neighborhood: string\n complement: string\n reference?: any\n geoCoordinates: any[]\n}\n\nexport interface DeliveryId {\n courierId: string\n warehouseId: string\n dockId: string\n courierName: string\n quantity: number\n kitItemDetails: any[]\n}\n\nexport interface PickupStoreInfo {\n isPickupStore: boolean\n friendlyName?: any\n address?: any\n additionalInfo?: any\n dockId?: any\n}\n\nexport interface Sla {\n id: string\n deliveryChannel: string\n name: string\n deliveryIds: DeliveryId[]\n shippingEstimate: string\n shippingEstimateDate?: any\n lockTTL?: any\n availableDeliveryWindows: any[]\n deliveryWindow?: any\n price: number\n listPrice: number\n tax: number\n pickupStoreInfo: PickupStoreInfo\n pickupPointId?: any\n pickupDistance: number\n polygonName?: any\n transitTime: string\n}\n\nexport interface DeliveryChannel {\n id: string\n}\n\nexport interface LogisticsInfo {\n itemIndex: number\n selectedSla: string\n selectedDeliveryChannel: string\n addressId: string\n slas: Sla[]\n shipsTo: string[]\n itemId: string\n deliveryChannels: DeliveryChannel[]\n}\n\nexport interface SelectedAddress {\n addressType: string\n receiverName: string\n addressId: string\n isDisposable: boolean\n postalCode: string\n city: string\n state: string\n country: string\n street: string\n number: string\n neighborhood: string\n complement: string\n reference?: any\n geoCoordinates: any[]\n}\n\nexport interface AvailableAddress {\n addressType: string\n receiverName: string\n addressId: string\n isDisposable: boolean\n postalCode: string\n city: string\n state: string\n country: string\n street: string\n number: string\n neighborhood: string\n complement: string\n reference?: any\n geoCoordinates: any[]\n}\n\nexport interface ShippingData {\n address: Address\n logisticsInfo: LogisticsInfo[]\n selectedAddresses: SelectedAddress[]\n availableAddresses: AvailableAddress[]\n pickupPoints: any[]\n}\n\nexport interface ClientProfileData {\n email: string\n firstName: string\n lastName: string\n document: string\n documentType: string\n phone: string\n corporateName?: any\n tradeName?: any\n corporateDocument?: any\n stateInscription?: any\n corporatePhone?: any\n isCorporate: boolean\n profileCompleteOnLoading: boolean\n profileErrorOnLoading: boolean\n customerClass?: any\n}\n\nexport interface SellerMerchantInstallment {\n id: string\n count: number\n hasInterestRate: boolean\n interestRate: number\n value: number\n total: number\n}\n\nexport interface Installment {\n count: number\n hasInterestRate: boolean\n interestRate: number\n value: number\n total: number\n sellerMerchantInstallments: SellerMerchantInstallment[]\n}\n\nexport interface InstallmentOption {\n paymentSystem: string\n bin: string\n paymentName?: any\n paymentGroupName?: any\n value: number\n installments: Installment[]\n}\n\nexport interface Validator {\n regex: string\n mask: string\n cardCodeRegex: string\n cardCodeMask: string\n weights: number[]\n useCvv: boolean\n useExpirationDate: boolean\n useCardHolderName: boolean\n useBillingAddress: boolean\n}\n\nexport interface PaymentSystem {\n id: number\n name: string\n groupName: string\n validator: Validator\n stringId: string\n template: string\n requiresDocument: boolean\n isCustom: boolean\n description?: any\n requiresAuthentication: boolean\n dueDate: Date\n availablePayments?: any\n}\n\nexport interface MerchantSellerPayment {\n id: string\n installments: number\n referenceValue: number\n value: number\n interestRate: number\n installmentValue: number\n}\n\nexport interface Payment {\n paymentSystem: string\n bin: string\n accountId: string\n tokenId?: any\n installments: number\n referenceValue: number\n value: number\n merchantSellerPayments: MerchantSellerPayment[]\n}\n\nexport interface AvailableAccount {\n accountId: string\n paymentSystem: string\n paymentSystemName: string\n cardNumber: string\n bin: string\n availableAddresses: string[]\n expirationDate: string\n isExpired: boolean\n}\n\nexport interface PaymentData {\n updateStatus: string\n installmentOptions: InstallmentOption[]\n paymentSystems: PaymentSystem[]\n payments: Payment[]\n giftCards: any[]\n giftCardMessages: any[]\n availableAccounts: AvailableAccount[]\n availableTokens: any[]\n}\n\nexport interface Seller {\n id: string\n name: string\n logo: string\n}\n\nexport interface ClientPreferencesData {\n locale: string\n optinNewsLetter: boolean\n}\n\nexport interface CurrencyFormatInfo {\n currencyDecimalDigits: number\n currencyDecimalSeparator: string\n currencyGroupSeparator: string\n currencyGroupSize: number\n startsWithCurrencySymbol: boolean\n}\n\nexport interface StorePreferencesData {\n countryCode: string\n saveUserData: boolean\n timeZone: string\n currencyCode: string\n currencyLocale: number\n currencySymbol: string\n currencyFormatInfo: CurrencyFormatInfo\n}\n\nexport interface CustomApp {\n fields: any\n id: string\n major: number\n}\n\nexport interface CustomData {\n customApps: CustomApp[]\n}\n\nexport interface InputValues {\n [key: string]: any\n}\n\nexport interface AssemblyOption {\n id: string\n name: string\n required: boolean\n inputValues: InputValues\n composition?: any\n}\n\nexport interface ItemMetadata {\n items: any[]\n}\n\nexport interface RateAndBenefitsIdentifier {\n id: string\n name: string\n featured: boolean\n description?: any\n matchedParameters: MatchedParameters\n additionalInfo?: any\n}\n\nexport interface RatesAndBenefitsData {\n rateAndBenefitsIdentifiers: RateAndBenefitsIdentifier[]\n teaser: any[]\n}\n\nexport interface Subscription {\n itemIndex: number\n plan: any\n executionCount: number\n}\n\nexport interface SubscriptionData {\n subscriptions: Subscription[]\n}\n\n```" } ]
code_external-promotion-provider-middleware_6438b82e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/middlewares/calculateExternalBenefits.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nimport { parseOrderFormToProtocol } from '../utils/index'\n\nconst calculateExternalBenefits = async (\n ctx: Context,\n next: () => Promise<any>\n) => {\n try {\n const simulationRequestBody = await json(ctx.req)\n\n ctx.state.parsedRequestProtocol = parseOrderFormToProtocol(\n ctx.state.orderForm ?? simulationRequestBody\n )\n\n ctx.state.externalProviderResponse = await ctx.clients.externalProvider.getBenefits(\n ctx.state.parsedRequestProtocol\n )\n } catch (err) {\n ctx.vtex.logger.error({\n calculateExternalBenefits: {\n status: 'failed',\n content: err.message,\n },\n })\n\n ctx.status = 400\n ctx.body = {\n error: err.message,\n }\n\n return\n }\n\n if (ctx.vtex.route.id === 'simulation') {\n ctx.status = 200\n ctx.body = ctx.state.externalProviderResponse\n\n return\n }\n\n const {\n orderForm: {\n items,\n totalizers,\n clientProfileData,\n shippingData,\n paymentData: { payments },\n customData,\n },\n externalProviderResponse,\n } = ctx.state\n\n ctx.vtex.logger.info({\n calculateExternalBenefits: {\n status: 'External endpoint successfully returned',\n content: {\n orderFormId: ctx.state.orderFormId,\n orderForm: {\n items,\n totalizers,\n clientProfileData,\n shippingData,\n payments,\n customData,\n },\n externalProviderResponse,\n },\n },\n })\n\n if (\n Array.isArray(ctx.state.externalProviderResponse.items) &&\n !ctx.state.externalProviderResponse.items.length\n ) {\n ctx.status = 200\n ctx.body = {\n message:\n 'No promotions applied, Items array was sent empty by the external provider',\n }\n\n return\n }\n\n await next()\n}\n\nexport default calculateExternalBenefits\n\n```" } ]
code_external-promotion-provider-middleware_a38aac80
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/middlewares/setupAppConfiguration.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { orderFormConfigurationConstant } from '../constants/orderFormConfiguration'\nimport { orderFormConfiguration } from '../services'\n\nconst setupAppConfiguration = async (\n ctx: InstalledAppEvent,\n next: () => Promise<any>\n) => {\n const { checkout } = ctx.clients\n\n try {\n await orderFormConfiguration.setConfiguration({\n client: checkout,\n configuration: orderFormConfigurationConstant,\n })\n } catch (error) {\n ctx.vtex.logger.error({\n setupAppConfigurationError: {\n status: 'failed',\n content: error,\n },\n })\n throw new Error(\"Couldn't set orderform configuration\")\n }\n\n await next()\n}\n\nexport default setupAppConfiguration\n\n```" } ]
code_external-promotion-provider-middleware_a9f1c924
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/middlewares/applyManualPrices.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { applyApportionment, validateProviderResponse } from '../utils'\nimport { customData } from '../services'\n\nconst applyManualPrices = async (ctx: Context, next: () => Promise<any>) => {\n try {\n await validateProviderResponse.schemaConsistency(\n ctx.state.externalProviderResponse\n )\n\n validateProviderResponse.indexConsistency(\n ctx.state.orderForm,\n ctx.state.externalProviderResponse\n )\n\n const apportionedPayload = applyApportionment(\n ctx.state.parsedRequestProtocol,\n ctx.state.externalProviderResponse\n )\n\n await ctx.clients.checkout.updateItems(\n ctx.state.orderFormId as string,\n apportionedPayload,\n 'AUTH_TOKEN'\n )\n\n await customData.setCustomData({\n client: ctx.clients.checkout,\n orderForm: ctx.state.orderForm,\n externalProviderResponse: ctx.state.externalProviderResponse,\n })\n\n ctx.status = 204\n } catch (err) {\n ctx.vtex.logger.error({\n applyManualPrices: {\n status: 'failed',\n content: {\n error: err.message,\n orderForm: ctx.state.orderForm,\n externalProviderResponse: ctx.state.externalProviderResponse,\n },\n },\n })\n ctx.status = 400\n ctx.body = { error: err.message }\n\n return\n }\n\n await next()\n}\n\nexport default applyManualPrices\n\n```" } ]
code_external-promotion-provider-middleware_2f1ba974
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/middlewares/index.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport applyManualPrices from './applyManualPrices'\nimport calculateExternalBenefits from './calculateExternalBenefits'\nimport getOrderFormById from './getOrderFormById'\nimport setupAppConfiguration from './setupAppConfiguration'\nimport getAppConfiguration from './getAppConfiguration'\n\nexport {\n setupAppConfiguration,\n getOrderFormById,\n applyManualPrices,\n calculateExternalBenefits,\n getAppConfiguration,\n}\n\n```" } ]
code_external-promotion-provider-middleware_c6a9317c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/middlewares/getOrderFormById.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { customData, orderform } from '../services'\nimport { getOrderFormId } from '../utils'\n\nconst getOrderFormById = async (ctx: Context, next: () => Promise<any>) => {\n try {\n ctx.state.orderFormId = getOrderFormId(ctx.cookies)\n\n const currentOrderform = await orderform.getOrderFormById(\n ctx.clients.checkout,\n ctx.state.orderFormId as string\n )\n\n ctx.state.orderForm = await orderform.deleteAllManualPrices(\n ctx.clients.checkout,\n ctx.vtex.logger,\n currentOrderform\n )\n\n // this method is necessary to clean customData\n await customData.setCustomData({\n client: ctx.clients.checkout,\n orderForm: ctx.state.orderForm,\n externalProviderResponse: null,\n })\n } catch (error) {\n ctx.vtex.logger.error({\n getOrderFormById: {\n status: 'failed',\n error: error.message,\n orderFormId: ctx.state.orderFormId,\n },\n })\n ctx.status = 400\n ctx.body = { error: error.message }\n\n return\n }\n\n await next()\n}\n\nexport default getOrderFormById\n\n```" } ]
code_external-promotion-provider-middleware_a9619f71
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/middlewares/getAppConfiguration.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ntype IAppSettings = { externalEndpoint: string }\n\nconst getAppConfiguration = async (ctx: Context, next: () => Promise<any>) => {\n const {\n clients: { apps },\n vtex: { account, workspace },\n } = ctx\n\n try {\n const appSettings: IAppSettings = await apps.getAppSettings(\n process.env.VTEX_APP_ID as string\n )\n\n ctx.vtex.settings = { ...ctx.vtex.settings, ...appSettings }\n\n if (!ctx.vtex.settings.externalEndpoint) {\n throw new Error(\n `No external endpoint was set. Go to https://${workspace}--${account}.myvtex.com/admin/apps/${process.env.VTEX_APP_ID}/setup/ and set your external endpoint`\n )\n }\n } catch (error) {\n ctx.vtex.logger.error({\n getAppSettingsError: {\n status: 'failed',\n content: error,\n },\n })\n\n ctx.status = 400\n ctx.body = { error: error.message }\n\n return\n }\n\n await next()\n}\n\nexport default getAppConfiguration\n\n```" } ]
code_external-promotion-provider-middleware_c8e5a7d2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/utils/getOrderFormId.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type Cookies from 'cookies'\n\nexport function getOrderFormId(cookies: Cookies) {\n const orderFormId = cookies.get('checkout.vtex.com')?.slice(7)\n\n if (!orderFormId) {\n throw new Error(\n 'No checkout.vtex.com cookie containing the orderformId was sent'\n )\n }\n\n return orderFormId\n}\n\n```" } ]
code_external-promotion-provider-middleware_841c4cee
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/utils/applyApportionment.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n ExternalPromotionsRequestProtocol,\n Item,\n} from '../typings/protocol/request'\nimport type {\n ExternalPromotionsResponseProtocol,\n Variation,\n ExternalPromotion,\n} from '../typings/protocol/response'\n\nexport function getFlattenedExternalPromotions(itemVariations: Variation[]) {\n return itemVariations.reduce<ExternalPromotion[]>(\n (memo, variation) => memo.concat(variation.externalPromotions),\n []\n )\n}\n\n// this function is important for cases where the SKU has split indexes\nfunction getItemQuantityAndPrice(requestItems: Item[], skuId: number) {\n const filteredItem = requestItems.filter((item: Item) => {\n return Number(item.id) === skuId\n })\n\n if (filteredItem.length > 1) {\n throw new Error(`Multiple items with SKUID ${skuId}`)\n }\n\n const { price } = filteredItem[0].variations[0]\n\n const totalQuantity = filteredItem[0].variations.reduce(\n (summedQuantity, variation) => {\n return summedQuantity + variation.quantity\n },\n 0\n )\n\n return { price, totalQuantity }\n}\n\nexport function applyApportionment(\n parsedRequestProtocol: ExternalPromotionsRequestProtocol,\n providerResponse: ExternalPromotionsResponseProtocol\n) {\n const apportionedPayload = providerResponse.items.map((item) => {\n const skuId = item.id\n\n const flattenedExternalPromotions = getFlattenedExternalPromotions(\n item.variations\n )\n\n const discount = flattenedExternalPromotions.reduce(\n (discountSum, externalPromotion) => {\n if (externalPromotion.isPercentual) {\n return {\n percentualDiscount:\n discountSum.percentualDiscount + externalPromotion.value,\n nominalDiscount: discountSum.nominalDiscount,\n }\n }\n\n return {\n percentualDiscount: discountSum.percentualDiscount,\n nominalDiscount:\n discountSum.nominalDiscount + externalPromotion.value,\n }\n },\n {\n percentualDiscount: 0,\n nominalDiscount: 0,\n }\n )\n\n const { totalQuantity, price } = getItemQuantityAndPrice(\n parsedRequestProtocol.items,\n skuId\n )\n\n const totalPrice = price * totalQuantity\n const netTotalPrice =\n totalPrice * (1 - discount.percentualDiscount) + discount.nominalDiscount\n\n const unitPrice = Math.ceil(netTotalPrice / totalQuantity)\n\n return {\n index: item.variations[0].requestIndex,\n price: unitPrice,\n }\n })\n\n return apportionedPayload\n}\n\n```" } ]
code_external-promotion-provider-middleware_168fba1f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/utils/validateProviderResponse.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport schemas from '../schemas'\nimport type { CheckoutOrderForm } from '../typings/global'\nimport type { ExternalPromotionsResponseProtocol } from '../typings/protocol/response'\n\nasync function schemaConsistency(\n providerResponse: ExternalPromotionsResponseProtocol\n) {\n await schemas.providerResponseSchema\n .validate(providerResponse, {\n strict: true,\n abortEarly: false,\n })\n .catch((err) => {\n throw new Error(err.errors.join('\\n\\n'))\n })\n}\n\nfunction indexConsistency(\n orderForm: CheckoutOrderForm,\n providerResponse: ExternalPromotionsResponseProtocol\n) {\n const { items: orderFormItems } = orderForm\n const { items } = providerResponse\n\n items.forEach((item) => {\n const { id, variations } = item\n\n variations.forEach((variation) => {\n const { requestIndex } = variation\n\n if (Number(orderFormItems[requestIndex]?.id) !== id) {\n throw new Error(\n `RequestIndex from response does not match orderForm's original index for skuId ${id}`\n )\n }\n })\n })\n}\n\nexport default { schemaConsistency, indexConsistency }\n\n```" } ]
code_external-promotion-provider-middleware_62cab0aa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/utils/parseOrderFormToProtocol.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n CheckoutOrderForm,\n Attachment,\n AttachmentOffering,\n PriceTag,\n} from '../typings/global'\nimport type { ExternalPromotionsRequestProtocol } from '../typings/protocol/request'\n\ninterface INonVariableFields {\n id: string\n productId?: string\n refId?: string\n ean?: string\n name?: string\n skuName?: string\n modalType?: any\n productCategoryIds?: string\n productCategories?: { [key: string]: string }\n availability?: string\n measurementUnit?: string\n}\n\ninterface IVariableFields {\n index: number\n assemblies?: any[]\n tax?: number\n price?: number\n listPrice?: number\n manualPrice?: number | undefined\n sellingPrice?: number\n isGift?: boolean\n quantity?: number\n attachments?: Attachment[]\n attachmentOfferings?: AttachmentOffering[]\n offerings?: any[]\n priceTags?: PriceTag[]\n unitMultiplier?: number\n seller?: string\n sellerChain?: string[]\n}\n\nexport function parseOrderFormToProtocol({\n items,\n customData,\n shippingData,\n clientProfileData,\n marketingData,\n paymentData,\n totalizers,\n}: CheckoutOrderForm): ExternalPromotionsRequestProtocol {\n if (!items) {\n throw new Error('Property \"items\" is obligatory')\n }\n\n const [itemsVariableFields, itemsNonVariableFields] = items.reduce(\n (\n [variableFields, nonVariableFields]: [\n IVariableFields[],\n INonVariableFields[]\n ],\n item,\n index\n ) => {\n if (!item.id) {\n throw new Error(\n `Property \"id\" is missing in index ${index} inside Items Array (this property is obligatory)`\n )\n }\n\n nonVariableFields.push({\n id: item.id,\n productId: item.productId,\n refId: item.refId,\n ean: item.ean,\n name: item.name,\n skuName: item.skuName,\n modalType: item.modalType,\n productCategoryIds: item.productCategoryIds,\n productCategories: item.productCategories,\n availability: item.availability,\n measurementUnit: item.measurementUnit,\n })\n\n variableFields.push({\n index,\n assemblies: item.assemblies,\n tax: item.tax,\n price: item.price,\n listPrice: item.listPrice,\n manualPrice: item.manualPrice,\n sellingPrice: item.sellingPrice,\n isGift: item.isGift,\n quantity: item.quantity,\n attachments: item.attachments,\n attachmentOfferings: item.attachmentOfferings,\n offerings: item.offerings,\n priceTags: item.priceTags,\n unitMultiplier: item.unitMultiplier,\n seller: item.seller,\n sellerChain: item.sellerChain,\n })\n\n return [variableFields, nonVariableFields]\n },\n [[], []]\n )\n\n const formattedItems = itemsNonVariableFields.reduce(\n (memo: any[], itemNonVariableFields, index) => {\n if (\n index &&\n itemsNonVariableFields[index - 1]?.id === itemNonVariableFields.id\n ) {\n const compiledVariations = [\n ...memo[memo.length - 1].variations,\n itemsVariableFields[index],\n ]\n\n const newItem = {\n ...itemNonVariableFields,\n variations: compiledVariations,\n }\n\n memo.pop()\n\n return [...memo, newItem]\n }\n\n return memo.concat({\n ...itemNonVariableFields,\n variations: [itemsVariableFields[index]],\n })\n },\n []\n )\n\n const parsedOrderFormToProtocol = {\n items: formattedItems,\n customData,\n shippingData: {\n logisticsInfo: shippingData?.logisticsInfo,\n selectedAddresses: shippingData?.selectedAddresses,\n },\n clientProfileData,\n marketingData,\n paymentData: { payments: paymentData?.payments },\n totalizers,\n }\n\n return parsedOrderFormToProtocol\n}\n\n```" } ]
code_external-promotion-provider-middleware_5a21005d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/utils/index.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { parseOrderFormToProtocol } from './parseOrderFormToProtocol'\nimport { getOrderFormId } from './getOrderFormId'\nimport {\n applyApportionment,\n getFlattenedExternalPromotions,\n} from './applyApportionment'\nimport validateProviderResponse from './validateProviderResponse'\n\nexport {\n parseOrderFormToProtocol,\n getOrderFormId,\n applyApportionment,\n validateProviderResponse,\n getFlattenedExternalPromotions,\n}\n\n```" } ]
code_external-promotion-provider-middleware_c366cc19
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/schemas/providerResponse.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as yup from 'yup'\nimport mapValues from 'lodash/mapValues'\n\nexport const providerResponseSchema = yup.object().shape({\n items: yup\n .array()\n .of(\n yup.object().shape({\n id: yup.number().required(),\n variations: yup\n .array()\n .of(\n yup.object().shape({\n requestIndex: yup.number().required(),\n quantity: yup.number().required(),\n externalPromotions: yup\n .array()\n .of(\n yup.object().shape({\n identifier: yup.string(),\n isPercentual: yup.boolean().required(),\n value: yup.number().required(),\n matchedParameters: yup.lazy((obj) =>\n yup.object(\n mapValues(obj, (value, key) => {\n return yup\n .string()\n .required()\n .test(\n 'length',\n `Key ${key} inside matchedParameters must have less than (or equal) 50 characters.`,\n () => Number(key?.length) <= 50\n )\n .test(\n 'length',\n `Value ${value} in key ${key} (matchedParameters array) must have less than (or equal) 50 characters.`,\n (val) => Number(val?.length) <= 50\n )\n })\n )\n ),\n })\n )\n .required()\n .test({\n message:\n 'externalPromotions array should have at least one object.',\n test: (arr) => !!arr?.length,\n }),\n })\n )\n .required()\n .test({\n message: 'variations array should have at least one object.',\n test: (arr) => !!arr?.length,\n }),\n })\n )\n .required(),\n})\n\n```" } ]
code_external-promotion-provider-middleware_ae68216e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/schemas/index.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { providerResponseSchema } from './providerResponse'\n\nexport default { providerResponseSchema }\n\n```" } ]
code_external-promotion-provider-middleware_087e49d4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/services/customData.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { Checkout } from '@vtex/clients'\n\nimport type { CheckoutOrderForm } from '../typings/global'\nimport type { ExternalPromotionsResponseProtocol } from '../typings/protocol/response'\nimport { getFlattenedExternalPromotions } from '../utils'\n\ntype Args = {\n client: Checkout\n orderForm: CheckoutOrderForm\n externalProviderResponse: ExternalPromotionsResponseProtocol | null\n}\n\nconst setCustomData = async ({\n client,\n orderForm,\n externalProviderResponse,\n}: Args) => {\n const targetCustomAppId = 'promotion-provider-middleware'\n\n const providedExternalPromotions = externalProviderResponse?.items.map(\n (item) => {\n return {\n id: item.id,\n externalPromotions: getFlattenedExternalPromotions(item.variations),\n }\n }\n )\n\n const value = providedExternalPromotions\n ? JSON.stringify(providedExternalPromotions)\n : '[]'\n\n try {\n await client.setSingleCustomData(\n orderForm.orderFormId,\n {\n appId: targetCustomAppId,\n appFieldName: 'externalPromotions',\n value,\n },\n 'AUTH_TOKEN'\n )\n } catch (error) {\n throw new Error(`It was not possible to set customData. ${error}`)\n }\n}\n\nexport default { setCustomData }\n\n```" } ]
code_external-promotion-provider-middleware_d6990fc9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/services/orderform.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { Logger } from '@vtex/api'\nimport type { Checkout } from '@vtex/clients'\n\nimport type { CheckoutOrderForm } from '../typings/global'\n\nconst getOrderFormById = async (client: Checkout, orderFormId: string) => {\n try {\n const orderForm: CheckoutOrderForm = ((await client.orderForm(\n orderFormId\n )) as unknown) as CheckoutOrderForm\n\n return orderForm\n } catch (error) {\n throw new Error(`Error when fetching orderform. Returned error: ${error}`)\n }\n}\n\nasync function deleteAllManualPrices(\n client: Checkout,\n logger: Logger,\n orderForm: CheckoutOrderForm\n) {\n const { items, orderFormId } = orderForm\n\n if (!items.length) {\n throw new Error(\"Found no items inside orderForm's items array\")\n }\n\n const orderItems = items.map((_, index) => {\n return {\n index,\n price: null,\n }\n })\n\n try {\n const orderFormWithoutManualPrices = ((await client.updateItems(\n orderFormId,\n orderItems,\n 'AUTH_TOKEN'\n )) as unknown) as CheckoutOrderForm\n\n return orderFormWithoutManualPrices\n } catch (error) {\n logger.error({ error })\n throw new Error(\n `Error when removing all manual prices from orderform. Returned error: ${error}`\n )\n }\n}\n\nexport default { getOrderFormById, deleteAllManualPrices }\n\n```" } ]
code_external-promotion-provider-middleware_ee9b03f6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/services/orderFormConfiguration.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { App, Checkout, OrderFormConfiguration } from '@vtex/clients'\n\ntype Args = {\n client: Checkout\n configuration: OrderFormConfiguration\n}\n\nconst getCurrentConfiguration = async (client: Checkout) => {\n const currentOrderformConfiguration = await client.getOrderFormConfiguration()\n const isAppAlreadySet = currentOrderformConfiguration.apps.some(\n (app: App) => app.id === 'promotion-provider-middleware'\n )\n\n return {\n isAppAlreadySet,\n isManualPriceTrue: currentOrderformConfiguration.allowManualPrice,\n currentOrderformConfiguration,\n }\n}\n\nconst setConfiguration = async ({\n client,\n configuration,\n}: Args): Promise<void> => {\n const {\n isAppAlreadySet,\n isManualPriceTrue,\n currentOrderformConfiguration,\n } = await getCurrentConfiguration(client)\n\n if (isManualPriceTrue && isAppAlreadySet) {\n return\n }\n\n try {\n await client.setOrderFormConfiguration({\n ...currentOrderformConfiguration,\n apps: [\n ...currentOrderformConfiguration.apps,\n ...(isAppAlreadySet ? [] : configuration.apps),\n ],\n allowManualPrice: configuration.allowManualPrice,\n })\n } catch (e) {\n throw new Error('Error while setting orderform configuration')\n }\n}\n\nexport default { setConfiguration, getCurrentConfiguration }\n\n```" } ]
code_external-promotion-provider-middleware_16c9da22
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/services/index.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport customData from './customData'\nimport orderFormConfiguration from './orderFormConfiguration'\nimport orderform from './orderform'\n\nexport { customData, orderFormConfiguration, orderform }\n\n```" } ]
code_external-promotion-provider-middleware_31d44e23
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/typings/protocol/request.d.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface ExternalPromotionsRequestProtocol {\n items: Item[]\n customData: CustomData\n shippingData: ShippingData\n clientProfileData: ClientProfileData\n marketingData?: MarketingData\n paymentData: PaymentData\n totalizers: Totalizer[]\n}\n\nexport interface Totalizer {\n id: string\n name: string\n value: number\n}\n\nexport interface MarketingData {\n utmSource?: string\n utmMedium?: string\n utmCampaign?: string\n utmipage?: string\n utmiPart?: string\n utmiCampaign?: string\n coupon?: string\n marketingTags: any[]\n}\n\nexport interface ProductCategories {\n [key: string]: string\n}\nexport interface Content {\n [key: string]: any\n}\n\nexport interface Attachment {\n name: string\n content: Content\n}\n\nexport interface AttachmentOffering {\n name: string\n required: boolean\n schema: any\n}\n\nexport interface PriceTag {\n name: string\n value: number\n rawValue: number\n isPercentual: boolean\n identifier: string\n}\n\nexport interface Variation {\n index: number\n assemblies: any[]\n tax: number\n price: number\n listPrice: number\n manualPrice?: any\n sellingPrice: number\n isGift: boolean\n quantity: number\n attachments: Attachment[]\n attachmentOfferings: AttachmentOffering[]\n offerings: any[]\n priceTags: PriceTag[]\n unitMultiplier: number\n seller: string\n sellerChain: string[]\n}\n\nexport interface Item {\n id: string\n productId: string\n refId?: any\n ean: string\n name: string\n skuName: string\n modalType?: any\n productCategoryIds: string\n productCategories: ProductCategories\n availability: string\n measurementUnit: string\n variations: Variation[]\n}\n\nexport interface Fields {\n [key: string]: string\n}\n\nexport interface CustomApp {\n fields: Fields\n id: string\n major: number\n}\n\nexport interface CustomData {\n customApps: CustomApp[]\n}\n\nexport interface DeliveryId {\n courierId: string\n warehouseId: string\n dockId: string\n courierName: string\n quantity: number\n kitItemDetails: any[]\n}\n\nexport interface PickupStoreInfo {\n isPickupStore: boolean\n friendlyName?: any\n address?: any\n additionalInfo?: any\n dockId?: any\n}\n\nexport interface Sla {\n id: string\n deliveryChannel: string\n name: string\n deliveryIds: DeliveryId[]\n shippingEstimate: string\n shippingEstimateDate?: any\n lockTTL?: any\n availableDeliveryWindows: any[]\n deliveryWindow?: any\n price: number\n listPrice: number\n tax: number\n pickupStoreInfo: PickupStoreInfo\n pickupPointId?: any\n pickupDistance: number\n polygonName?: any\n transitTime: string\n}\n\nexport interface DeliveryChannel {\n id: string\n}\n\nexport interface LogisticsInfo {\n itemIndex: number\n selectedSla: string\n selectedDeliveryChannel: string\n addressId: string\n slas: Sla[]\n shipsTo: string[]\n itemId: string\n deliveryChannels: DeliveryChannel[]\n}\n\nexport interface SelectedAddress {\n addressType: string\n receiverName: string\n addressId: string\n isDisposable: boolean\n postalCode: string\n city: string\n state: string\n country: string\n street: string\n number: string\n neighborhood: string\n complement: string\n reference?: any\n geoCoordinates: any[]\n}\n\nexport interface ShippingData {\n logisticsInfo: LogisticsInfo[]\n selectedAddresses: SelectedAddress[]\n}\n\nexport interface ClientProfileData {\n email: string\n firstName: string\n lastName: string\n document: string\n documentType: string\n phone: string\n corporateName?: any\n tradeName?: any\n corporateDocument?: any\n stateInscription?: any\n corporatePhone?: any\n isCorporate: boolean\n profileCompleteOnLoading: boolean\n profileErrorOnLoading: boolean\n customerClass?: any\n}\n\nexport interface MerchantSellerPayment {\n id: string\n installments: number\n referenceValue: number\n value: number\n interestRate: number\n installmentValue: number\n}\n\nexport interface Payment {\n paymentSystem: string\n bin: string\n accountId: string\n tokenId?: any\n installments: number\n referenceValue: number\n value: number\n merchantSellerPayments: MerchantSellerPayment[]\n}\n\nexport interface PaymentData {\n payments: Payment[]\n}\n\n```" } ]
code_external-promotion-provider-middleware_fe9ce514
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/typings/protocol/response.d.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface ExternalPromotionsResponseProtocol {\n items: Item[]\n}\n\nexport interface MatchedParameters {\n [key: string]: string\n}\n\nexport interface ExternalPromotion {\n matchedParameters: MatchedParameters\n identifier: string\n isPercentual: boolean\n value: number\n}\n\nexport interface Variation {\n requestIndex: number\n quantity: number\n externalPromotions: ExternalPromotion[]\n}\n\nexport interface Item {\n id: number\n variations: Variation[]\n}\n\n```" } ]
code_external-promotion-provider-middleware_8081b0fb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/middlewares/getOrderFormById.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { getOrderFormById } from '../../../middlewares'\n\ndescribe('getOrderFormById', () => {\n it('should return error when fecthing the orderform fails', async () => {\n const ctx = {\n body: '',\n state: { orderform: {}, orderFormId: {} },\n cookies: {\n get: jest\n .fn()\n .mockReturnValueOnce('__ofid=03db3a179c7d4a9085152068b555eee1'),\n },\n vtex: { logger: { error: jest.fn() } },\n clients: { checkout: { orderForm: jest.fn().mockRejectedValueOnce('') } },\n } as any\n\n const next = jest.fn()\n\n await getOrderFormById(ctx, next)\n\n expect(ctx.body).toMatchObject({ error: 'Error when fetching orderform' })\n })\n it('should return error when deleting all manual prices fails', async () => {\n const ctx = {\n body: '',\n state: { orderform: {}, orderFormId: {} },\n cookies: {\n get: jest\n .fn()\n .mockReturnValueOnce('__ofid=03db3a179c7d4a9085152068b555eee1'),\n },\n vtex: { logger: { error: jest.fn() } },\n clients: {\n checkout: {\n orderForm: jest.fn().mockResolvedValueOnce({ items: [] }),\n updateItems: jest.fn().mockRejectedValueOnce(''),\n },\n },\n } as any\n\n const next = jest.fn()\n\n await getOrderFormById(ctx, next)\n\n expect(ctx.body).toMatchObject({\n error: 'Error when removing all manual prices from orderform',\n })\n })\n it('should not call next when an error is returned', async () => {\n const ctx = {\n body: '',\n state: { orderform: {}, orderFormId: {} },\n cookies: {\n get: jest\n .fn()\n .mockReturnValueOnce('__ofid=03db3a179c7d4a9085152068b555eee1'),\n },\n vtex: { logger: { error: jest.fn() } },\n clients: {\n checkout: {\n orderForm: jest.fn().mockResolvedValueOnce({ items: [] }),\n updateItems: jest.fn().mockRejectedValueOnce(''),\n },\n },\n } as any\n\n const next = jest.fn()\n\n await getOrderFormById(ctx, next)\n\n expect(next).not.toBeCalled()\n })\n it('should call next when no errors are returned', async () => {\n const ctx = {\n body: '',\n state: { orderform: {}, orderFormId: {} },\n cookies: {\n get: jest\n .fn()\n .mockReturnValueOnce('__ofid=03db3a179c7d4a9085152068b555eee1'),\n },\n vtex: { logger: { error: jest.fn() } },\n clients: {\n checkout: {\n orderForm: jest.fn().mockResolvedValueOnce({ items: [] }),\n updateItems: jest.fn().mockResolvedValueOnce(''),\n setSingleCustomData: jest.fn().mockResolvedValueOnce(''),\n },\n },\n } as any\n\n const next = jest.fn()\n\n await getOrderFormById(ctx, next)\n\n expect(next).toBeCalled()\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_e4f42a48
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/middlewares/setupAppConfiguration.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { setupAppConfiguration } from '../../../middlewares'\nimport { orderFormConfiguration } from '../../../services'\n\njest.mock('../../../services')\n\ndescribe('setupAppConfiguration', () => {\n const ctx = {\n state: {},\n clients: {\n apps: { getAppSettings: jest.fn() },\n },\n vtex: { logger: { error: jest.fn() } },\n } as any\n\n it('should return error when setConfiguration is rejected', async () => {\n jest\n .spyOn(orderFormConfiguration, 'setConfiguration')\n .mockImplementation()\n .mockRejectedValueOnce(new Error())\n\n const next = jest.fn()\n\n await expect(setupAppConfiguration(ctx, next)).rejects.toThrow(\n \"Couldn't set orderform configuration\"\n )\n })\n it('should call next function', async () => {\n jest.spyOn(orderFormConfiguration, 'setConfiguration').mockImplementation()\n\n const next = jest.fn()\n\n await setupAppConfiguration(ctx, next)\n expect(next).toHaveBeenCalled()\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_28b0637a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/middlewares/getAppConfiguration.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { getAppConfiguration } from '../../../middlewares'\n\ndescribe('getAppConfiguration', () => {\n const ctx = {\n body: '',\n clients: {\n apps: { getAppSettings: jest.fn() },\n },\n vtex: { logger: { error: jest.fn() }, settings: {} },\n } as any\n\n it('should insert the app settings into context', async () => {\n const spyGetAppSettings = jest.spyOn(ctx.clients.apps, 'getAppSettings')\n\n spyGetAppSettings.mockImplementation().mockResolvedValueOnce({\n externalEndpoint: 'http://localhost:3000/api',\n })\n const next = jest.fn()\n\n await getAppConfiguration(ctx, next)\n expect(spyGetAppSettings).toHaveBeenCalled()\n expect(ctx.vtex.settings.externalEndpoint).toEqual(\n 'http://localhost:3000/api'\n )\n })\n it('should return error when there is no externalProvider set', async () => {\n ctx.vtex.settings.externalEndpoint = undefined\n const spyGetAppSettingsError = jest.spyOn(\n ctx.clients.apps,\n 'getAppSettings'\n )\n\n spyGetAppSettingsError.mockImplementation().mockResolvedValueOnce({})\n\n const next = jest.fn()\n\n await getAppConfiguration(ctx, next)\n\n expect(ctx.body).toMatchObject({\n error: `No external endpoint was set. Go to https://${process.env.VTEX_WORKSPACE}--${process.env.VTEX_ACCOUNT}.myvtex.com/admin/apps/${process.env.VTEX_APP_ID}/setup/ and set your external endpoint`,\n })\n })\n it('should return error when getAppSettings is rejected', async () => {\n const spyGetAppSettingsError = jest.spyOn(\n ctx.clients.apps,\n 'getAppSettings'\n )\n\n spyGetAppSettingsError\n .mockImplementation()\n .mockRejectedValueOnce(new Error('Failed to get app settings'))\n\n const next = jest.fn()\n\n await getAppConfiguration(ctx, next)\n\n expect(ctx.body).toMatchObject({\n error: 'Failed to get app settings',\n })\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_d04b6848
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/middlewares/calculateExternalBenefits.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as cobody from 'co-body'\n\nimport { calculateExternalBenefits } from '../../../middlewares'\nimport { parseOrderFormToProtocol } from '../../../utils'\n\njest.mock('co-body')\njest.mock('../../../utils')\n\ndescribe('calculateExternalBenefits', () => {\n const mainCtx = {\n state: { orderForm: { items: [], paymentData: { payments: '' } } },\n req: {},\n clients: {\n externalProvider: {\n getBenefits: jest.fn().mockResolvedValue({ items: [] }),\n },\n },\n body: {},\n vtex: { logger: { error: jest.fn(), info: jest.fn() }, route: { id: '' } },\n } as any\n\n const next = jest.fn()\n\n jest.spyOn(cobody, 'json').mockImplementation().mockResolvedValue('')\n\n it('should be able to call parseOrderFormToProtocol function', async () => {\n await calculateExternalBenefits(mainCtx, next)\n\n expect(parseOrderFormToProtocol).toHaveBeenCalled()\n })\n\n it('should be able to call getBenefits function', async () => {\n await calculateExternalBenefits(mainCtx, next)\n\n expect(mainCtx.clients.externalProvider.getBenefits).toHaveBeenCalled()\n })\n\n it('should be able to set the response body when the route is /simulation', async () => {\n const ctx = {\n state: {\n orderForm: { items: [] },\n },\n req: {},\n clients: {\n externalProvider: {\n getBenefits: jest.fn().mockResolvedValueOnce({ items: [] }),\n },\n },\n vtex: {\n logger: { error: jest.fn(), info: jest.fn() },\n route: { id: 'simulation' },\n },\n } as any\n\n await calculateExternalBenefits(ctx, next)\n\n expect(ctx.body).toMatchObject({ items: [] })\n })\n\n it('should not call next function when the route is /simulation', async () => {\n const ctx = {\n state: {\n orderForm: { items: [{ id: 1 }] },\n },\n req: {},\n clients: {\n externalProvider: {\n getBenefits: jest.fn().mockResolvedValueOnce({ items: [] }),\n },\n },\n vtex: {\n logger: { error: jest.fn(), info: jest.fn() },\n route: { id: 'simulation' },\n },\n } as any\n\n const nextSpy = jest.fn()\n\n await calculateExternalBenefits(ctx, nextSpy)\n\n expect(nextSpy).not.toBeCalled()\n })\n\n it('should not call next function when the items is [] in externalProviderResponse', async () => {\n const ctx = {\n state: {\n orderForm: { items: [{ id: 1 }], paymentData: { payments: '' } },\n },\n req: {},\n clients: {\n externalProvider: {\n getBenefits: jest.fn().mockResolvedValueOnce({ items: [] }),\n },\n },\n vtex: {\n logger: { error: jest.fn(), info: jest.fn() },\n route: { id: '' },\n },\n } as any\n\n const nextSpy = jest.fn()\n\n await calculateExternalBenefits(ctx, nextSpy)\n\n expect(nextSpy).not.toBeCalled()\n })\n\n it('should not set the response body when the route does not match /simulation and when items array is not empty', async () => {\n const ctx = {\n state: {\n orderForm: { items: [], paymentData: { payments: '' } },\n },\n req: {},\n clients: {\n externalProvider: {\n getBenefits: jest\n .fn()\n .mockResolvedValueOnce({ items: [{ id: 1, variations: [] }] }),\n },\n },\n vtex: {\n logger: { error: jest.fn(), info: jest.fn() },\n route: { id: '' },\n },\n } as any\n\n await calculateExternalBenefits(ctx, next)\n\n expect(ctx.body).toBeUndefined()\n })\n\n it('should return 404 when getBenefits function fails', async () => {\n const ctx = {\n state: {\n orderForm: { items: [] },\n },\n req: {},\n clients: {\n externalProvider: {\n getBenefits: jest.fn().mockRejectedValueOnce(''),\n },\n },\n vtex: {\n logger: { error: jest.fn(), info: jest.fn() },\n route: { id: '' },\n },\n } as any\n\n await calculateExternalBenefits(ctx, next)\n\n expect(ctx.status).toBe(400)\n })\n it('should return 404 when parseOrderFormToProtocol function fails', async () => {\n const ctx = {\n state: {\n orderForm: undefined,\n },\n req: {},\n clients: {\n externalProvider: {\n getBenefits: jest.fn().mockRejectedValueOnce(''),\n },\n },\n vtex: {\n logger: { error: jest.fn(), info: jest.fn() },\n route: { id: '' },\n },\n } as any\n\n await calculateExternalBenefits(ctx, next)\n\n expect(ctx.status).toBe(400)\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_915db74b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/middlewares/applyManualPrices.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { applyManualPrices } from '../../../middlewares'\n\njest.mock('../../../utils')\njest.mock('../../../services')\n\ndescribe('applyManualPrices', () => {\n it('should be able to set status 204 and call next', async () => {\n const ctx = {\n status: '',\n state: {},\n clients: { checkout: { updateItems: jest.fn() } },\n }\n\n const next = jest.fn()\n\n await applyManualPrices(ctx as any, next)\n expect(next).toBeCalled()\n expect(ctx.status).toBe(204)\n })\n it('should be able to set status 400 when error is thrown', async () => {\n const ctx = {\n status: '',\n state: {},\n clients: {\n checkout: { updateItems: jest.fn().mockRejectedValueOnce('') },\n },\n vtex: { logger: { error: jest.fn() } },\n }\n\n const next = jest.fn()\n\n await applyManualPrices(ctx as any, next)\n expect(ctx.status).toBe(400)\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_101e1751
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/utils/parseOrderFormToProtocol.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable jest/no-mocks-import */\nimport { parseOrderFormToProtocol } from '../../../utils'\nimport { orderForm } from '../../../__mocks__/orderForm'\nimport { parsedProtocol } from '../../../__mocks__/parsedProtocol'\n\ndescribe('parseOrderFormToProtocol', () => {\n it('should return the protocol parsed', async () => {\n expect(parseOrderFormToProtocol(orderForm as any)).toMatchObject(\n parsedProtocol\n )\n })\n it('should be able to throw error when payload has no items array', async () => {\n expect(() => {\n parseOrderFormToProtocol({\n customData: {},\n paymentData: { payment: '' },\n } as any)\n }).toThrowError('Property \"items\" is obligatory')\n })\n it('should be able to throw error when items array has no skuId', async () => {\n expect(() => {\n parseOrderFormToProtocol({\n items: [\n { id: 33, otherfield: '' },\n { id: 23, otherfield: '' },\n { otherfield: '' },\n ],\n customData: {},\n } as any)\n }).toThrowError(\n `Property \"id\" is missing in index 2 inside Items Array (this property is obligatory)`\n )\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_7b4a7f15
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/utils/applyApportionment.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable jest/no-mocks-import */\nimport { applyApportionment } from '../../../utils'\nimport { parsedProtocol } from '../../../__mocks__/parsedProtocol'\nimport { externalProviderResponse } from '../../../__mocks__/externalProviderResponse'\n\ndescribe('applyApportionment', () => {\n it('should be able to apply the apportionment properly', () => {\n const apportionedPayload = applyApportionment(\n parsedProtocol as any,\n externalProviderResponse\n )\n\n const expectedPayload = [\n {\n index: 0,\n price: 533,\n },\n {\n index: 3,\n price: 1850,\n },\n ]\n\n expect(apportionedPayload).toMatchObject(expectedPayload)\n })\n it('should be able to throw error when skuId has two instances at the items array', () => {\n const { items } = parsedProtocol\n\n items.push({\n id: '30',\n productId: '3',\n variations: [\n {\n assemblies: [],\n tax: 0,\n price: 135714,\n listPrice: 135714,\n manualPrice: null,\n sellingPrice: 135714,\n quantity: 1,\n },\n ],\n } as any)\n\n const newParsedProtocol = { ...parsedProtocol, items: [...items] }\n\n expect(() => {\n applyApportionment(newParsedProtocol as any, externalProviderResponse)\n }).toThrowError(`Multiple items with SKUID 30`)\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_e2196118
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/utils/getOrderFormId.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { getOrderFormId } from '../../../utils'\n\ndescribe('getOrderFormId', () => {\n it('should be able to slice checkout.vtex.com cookie and store in orderFormId variable', async () => {\n const ctx = {\n state: { orderform: {}, orderFormId: {} },\n cookies: {\n get: jest\n .fn()\n .mockReturnValueOnce('__ofid=03db3a179c7d4a9085152068b555eee1'),\n },\n clients: { checkout: { orderForm: jest.fn().mockResolvedValueOnce('') } },\n } as any\n\n expect(getOrderFormId(ctx.cookies)).toBe('03db3a179c7d4a9085152068b555eee1')\n })\n it('should return error when \"checkout.vtex.com\" cookie is not in request', async () => {\n const ctx = {\n state: { orderform: {}, orderFormId: {} },\n cookies: {\n get: jest.fn().mockReturnValue(undefined),\n },\n clients: { checkout: { orderForm: jest.fn().mockResolvedValueOnce('') } },\n } as any\n\n expect(() => {\n getOrderFormId(ctx.cookies)\n }).toThrow(\n 'No checkout.vtex.com cookie containing the orderformId was sent'\n )\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_3396529c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/utils/validateProviderResponse.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable jest/no-mocks-import */\nimport { validateProviderResponse } from '../../../utils'\nimport { orderForm } from '../../../__mocks__/orderForm'\nimport { externalProviderResponse } from '../../../__mocks__/externalProviderResponse'\n\ndescribe('validateProviderResponse', () => {\n describe('validateIndexConsistency method', () => {\n it('should be able to throw error when requestIndex does not match index in orderForm', () => {\n const mockedUncorrectProviderResponse = {\n items: [\n {\n id: 33,\n variations: [\n {\n requestIndex: 2,\n quantity: 1,\n externalPromotions: [\n {\n matchedParameters: {},\n identifier: '3f0c2115-10a6-4fda-aec4-5950d8de9a6c',\n isPercentual: true,\n value: 0.1,\n },\n ],\n },\n ],\n },\n ],\n }\n\n expect(() => {\n validateProviderResponse.indexConsistency(\n orderForm as any,\n mockedUncorrectProviderResponse\n )\n }).toThrowError(\n `RequestIndex from response does not match orderForm's original index for skuId ${mockedUncorrectProviderResponse.items[0].id}`\n )\n })\n it('should be able to throw error when requestIndex does not exist in original orderForm', () => {\n const mockedUncorrectProviderResponse = {\n items: [\n {\n id: 33,\n variations: [\n {\n requestIndex: 10,\n quantity: 1,\n externalPromotions: [\n {\n matchedParameters: {},\n identifier: '3f0c2115-10a6-4fda-aec4-5950d8de9a6c',\n isPercentual: true,\n value: 0.1,\n },\n ],\n },\n ],\n },\n ],\n }\n\n expect(() => {\n validateProviderResponse.indexConsistency(\n orderForm as any,\n mockedUncorrectProviderResponse\n )\n }).toThrowError(\n `RequestIndex from response does not match orderForm's original index for skuId ${mockedUncorrectProviderResponse.items[0].id}`\n )\n })\n it('should not throw error when requestIndex matches index in orderForm', () => {\n expect(\n validateProviderResponse.indexConsistency(\n orderForm as any,\n externalProviderResponse\n )\n ).toBeUndefined()\n })\n })\n describe('validateSchema method', () => {\n it('should be able to throw error when schema does not match', async () => {\n const mockedUncorrectProviderResponse = {\n items: [\n {\n id: '33',\n variations: [\n {\n requestIndex: '2',\n quantity: 1,\n externalPromotions: [\n {\n matchedParameters: {\n requiresAuthenticationForPreAuthorizedPaymentOption:\n 'requiresAuthenticationForPreAuthorizedPaymentOption',\n },\n identifier: 123443,\n isPercentual: 'true',\n value: '0.1',\n },\n ],\n },\n ],\n },\n ],\n }\n\n const expected =\n 'items[0].id must be a `number` type, but the final value was: `\"33\"`.·items[0].variations[0].requestIndex must be a `number` type, but the final value was: `\"2\"`.·items[0].variations[0].externalPromotions[0].identifier must be a `string` type, but the final value was: `123443`.·items[0].variations[0].externalPromotions[0].isPercentual must be a `boolean` type, but the final value was: `\"true\"`.·items[0].variations[0].externalPromotions[0].value must be a `number` type, but the final value was: `\"0.1\"`.·Key requiresAuthenticationForPreAuthorizedPaymentOption inside matchedParameters must have less than (or equal) 50 characters.·Value requiresAuthenticationForPreAuthorizedPaymentOption in key requiresAuthenticationForPreAuthorizedPaymentOption (matchedParameters array) must have less than (or equal) 50 characters.'\n\n await expect(\n validateProviderResponse.schemaConsistency(\n mockedUncorrectProviderResponse as any\n )\n ).rejects.toThrowError(expected.split('·').join('\\n\\n'))\n })\n it('should not throw error when schema does matches', async () => {\n const mockedCorrectProviderResponse = {\n items: [\n {\n id: 33,\n variations: [\n {\n requestIndex: 1,\n quantity: 1,\n externalPromotions: [\n {\n matchedParameters: {\n items: 'tech genérica',\n },\n identifier: '3f0c2115-10a6-4fda-aec4-5950d8de9a6c',\n isPercentual: true,\n value: 0.1,\n },\n {\n matchedParameters: {\n items: 'tech genérica',\n },\n identifier: '3f0c2115-10a6-4fda-aec4-5950d8de9a6c',\n isPercentual: true,\n value: 0.1,\n },\n ],\n },\n ],\n },\n {\n id: 30,\n variations: [\n {\n requestIndex: 4,\n quantity: 1,\n externalPromotions: [\n {\n matchedParameters: {\n paymentData: 'tech genérica',\n },\n identifier: '3f0c2115-10a6-4fda-aec4-5950d8de9a6c',\n isPercentual: true,\n value: 0.1,\n },\n ],\n },\n {\n requestIndex: 4,\n quantity: 1,\n externalPromotions: [\n {\n matchedParameters: {\n paymentData: 'tech genérica',\n },\n identifier: '3f0c2115-10a6-4fda-aec4-5950d8de9a6c',\n isPercentual: true,\n value: 0.1,\n },\n ],\n },\n ],\n },\n ],\n }\n\n expect(\n await validateProviderResponse.schemaConsistency(\n mockedCorrectProviderResponse as any\n )\n ).toBeUndefined()\n })\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_41f9139c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/services/orderFormConfiguration.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { orderFormConfiguration } from '../../../services'\n\nconst configuration = {\n allowManualPrice: true,\n apps: [\n {\n fields: ['externalPromotions'],\n id: 'promotion-provider-middleware',\n major: 0,\n },\n ],\n}\n\nfunction orderformConfiguration(\n withExternalProvider: boolean,\n allowManualPrice = false\n) {\n const apps = [\n {\n fields: ['marketplacePaymentMethod'],\n id: 'cn-magazineluiza-integration',\n major: 1,\n },\n ]\n\n const externalPromotions = {\n fields: ['externalPromotions'],\n id: 'promotion-provider-middleware',\n major: 1,\n }\n\n return {\n allowManualPrice,\n apps: [...apps, withExternalProvider && externalPromotions],\n }\n}\n\ndescribe('orderFormConfigurationService', () => {\n describe('getOrderFormConfiguration', () => {\n it('should be able to set isAppAlreadySet as true', async () => {\n const checkout = {\n getOrderFormConfiguration: jest\n .fn()\n .mockResolvedValueOnce(orderformConfiguration(true)),\n }\n\n const {\n isAppAlreadySet,\n } = await orderFormConfiguration.getCurrentConfiguration(checkout as any)\n\n expect(isAppAlreadySet).toBe(true)\n })\n it('should be able to set isAppAlreadySet as false', async () => {\n const checkout = {\n getOrderFormConfiguration: jest\n .fn()\n .mockResolvedValueOnce(orderformConfiguration(false)),\n }\n\n const {\n isAppAlreadySet,\n } = await orderFormConfiguration.getCurrentConfiguration(checkout as any)\n\n expect(isAppAlreadySet).toBe(false)\n })\n })\n\n describe('setOrderFormConfiguration', () => {\n it('should not call setOrderFormConfiguration when isAppAlreadySet and isManualPriceTrue are true', async () => {\n const checkout = {\n setOrderFormConfiguration: jest.fn(),\n getOrderFormConfiguration: jest\n .fn()\n .mockResolvedValueOnce(orderformConfiguration(true, true)),\n }\n\n await orderFormConfiguration.setConfiguration({\n client: checkout as any,\n configuration: configuration as any,\n })\n\n expect(checkout.setOrderFormConfiguration).not.toHaveBeenCalled()\n })\n it('should call setOrderFormConfiguration when isManualPriceTrue is false', async () => {\n const checkout = {\n setOrderFormConfiguration: jest.fn(),\n getOrderFormConfiguration: jest\n .fn()\n .mockResolvedValueOnce(orderformConfiguration(true)),\n }\n\n await orderFormConfiguration.setConfiguration({\n client: checkout as any,\n configuration: configuration as any,\n })\n\n expect(checkout.setOrderFormConfiguration).toHaveBeenCalled()\n })\n it('should call setOrderFormConfiguration when isAppAlreadySet is false', async () => {\n const checkout = {\n setOrderFormConfiguration: jest.fn(),\n getOrderFormConfiguration: jest\n .fn()\n .mockResolvedValueOnce(orderformConfiguration(false, true)),\n }\n\n await orderFormConfiguration.setConfiguration({\n client: checkout as any,\n configuration: configuration as any,\n })\n\n expect(checkout.setOrderFormConfiguration).toHaveBeenCalled()\n })\n it('should call setOrderFormConfiguration when isAppAlreadySet and isManualPriceTrue are false', async () => {\n const checkout = {\n setOrderFormConfiguration: jest.fn(),\n getOrderFormConfiguration: jest\n .fn()\n .mockResolvedValueOnce(orderformConfiguration(false, false)),\n }\n\n await orderFormConfiguration.setConfiguration({\n client: checkout as any,\n configuration: configuration as any,\n })\n\n expect(checkout.setOrderFormConfiguration).toHaveBeenCalled()\n })\n it('should throw error when setOrderFormConfiguration fails', async () => {\n const checkout = {\n setOrderFormConfiguration: jest.fn().mockRejectedValueOnce({}),\n getOrderFormConfiguration: jest\n .fn()\n .mockResolvedValueOnce(orderformConfiguration(true)),\n }\n\n const { setConfiguration } = orderFormConfiguration\n\n await expect(\n setConfiguration({\n client: checkout as any,\n configuration: configuration as any,\n })\n ).rejects.toThrow('Error while setting orderform configuration')\n })\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_8b46056a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/services/orderForm.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { orderform as orderformService } from '../../../services'\n\ndescribe('orderform', () => {\n describe('getOrderFormById', () => {\n it('should be able to return the orderform', async () => {\n const ctx = {\n clients: {\n checkout: {\n orderForm: jest.fn().mockResolvedValueOnce({ items: [] }),\n },\n },\n }\n\n const orderformId = '1'\n const orderform = await orderformService.getOrderFormById(\n ctx.clients.checkout as any,\n orderformId\n )\n\n expect(orderform).toMatchObject({ items: [] })\n })\n it('should be able to throw error when orderform can not be fecthed', async () => {\n const ctx = {\n clients: {\n checkout: {\n orderForm: jest.fn().mockRejectedValueOnce(''),\n },\n },\n }\n\n const orderformId = '1'\n\n await expect(\n orderformService.getOrderFormById(\n ctx.clients.checkout as any,\n orderformId\n )\n ).rejects.toThrowError('Error when fetching orderform')\n })\n })\n describe('deleteAllManualPrices', () => {\n it('should be able to return the orderform without manual prices', async () => {\n const ctx = {\n clients: {\n checkout: {\n updateItems: jest.fn().mockResolvedValueOnce({ items: [] }),\n },\n },\n vtex: {\n logger: {\n error: (message) => console.error(message),\n },\n },\n }\n\n const currentOrderform = {\n items: [{ id: 1 }, { id: 2 }],\n orderFormId: '1',\n }\n\n const spyUpdateItems = jest.spyOn(ctx.clients.checkout, 'updateItems')\n\n const orderform = await orderformService.deleteAllManualPrices(\n ctx.clients.checkout as any,\n ctx.vtex.logger as any,\n currentOrderform as any\n )\n\n expect(spyUpdateItems).toHaveBeenCalledWith(\n currentOrderform.orderFormId,\n [\n {\n index: 0,\n price: null,\n },\n {\n index: 1,\n price: null,\n },\n ],\n 'AUTH_TOKEN'\n )\n\n expect(orderform).toMatchObject({ items: [] })\n })\n it('should be able to throw error when updateItems fails', async () => {\n const ctx = {\n clients: {\n checkout: {\n updateItems: jest.fn().mockRejectedValueOnce(''),\n },\n },\n vtex: {\n logger: {\n error: (message) => console.error(message),\n },\n },\n }\n\n const currentOrderform = { items: [], orderformId: '1' }\n\n await expect(\n orderformService.deleteAllManualPrices(\n ctx.clients.checkout as any,\n ctx.vtex.logger as any,\n currentOrderform as any\n )\n ).rejects.toThrowError(\n 'Error when removing all manual prices from orderform'\n )\n })\n })\n})\n\n```" } ]
code_external-promotion-provider-middleware_921b9f5c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of external-promotion-provider-middleware/node/__tests__/unit/services/customData.spec.ts from the external-promotion-provider-middleware VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable jest/no-mocks-import */\nimport { customData } from '../../../services'\nimport { orderForm } from '../../../__mocks__/orderForm'\nimport { externalProviderResponse } from '../../../__mocks__/externalProviderResponse'\n\ndescribe('customData', () => {\n const ctx = {\n clients: {\n checkout: {\n setSingleCustomData: jest.fn().mockResolvedValueOnce({ items: [] }),\n },\n },\n }\n\n it('should to call function setSingleCustomData with its respective params', async () => {\n await customData.setCustomData({\n client: ctx.clients.checkout,\n externalProviderResponse,\n orderForm,\n } as any)\n\n const spyOnSetSingleCustomData = jest.spyOn(\n ctx.clients.checkout,\n 'setSingleCustomData'\n )\n\n const value =\n '[{\"id\":33,\"externalPromotions\":[{\"matchedParameters\":{\"slaIds\":\"transportadora genérica\"},\"identifier\":\"3f0c2115-10a6-4fda-aec4-5950d8de9a6c\",\"isPercentual\":false,\"value\":-700},{\"matchedParameters\":{\"slaIds\":\"transportadora genérica\"},\"identifier\":\"3f0c2115-10a6-4fda-aec4-5950d8de9a6c\",\"isPercentual\":false,\"value\":-100},{\"matchedParameters\":{\"slaIds\":\"transportadora genérica\"},\"identifier\":\"3f0c2115-10a6-4fda-aec4-5950d8de9a6c\",\"isPercentual\":true,\"value\":0.2}]},{\"id\":30,\"externalPromotions\":[{\"matchedParameters\":{\"dockId\":\"2343b\"},\"identifier\":\"3f0c2115-10a6-4fda-aec4-5950d8de9a6c\",\"isPercentual\":false,\"value\":-100},{\"matchedParameters\":{\"skuName\":\"SKU 23 - Celular\"},\"identifier\":\"3f0c2115-10a6-4fda-aec4-5950d8de9a6c\",\"isPercentual\":false,\"value\":-500}]}]'\n\n expect(spyOnSetSingleCustomData).toBeCalledWith(\n orderForm.orderFormId,\n {\n appId: 'promotion-provider-middleware',\n appFieldName: 'externalPromotions',\n value,\n },\n 'AUTH_TOKEN'\n )\n })\n it('should be able to throw an error when setSingleCustomData fails', async () => {\n jest\n .spyOn(ctx.clients.checkout, 'setSingleCustomData')\n .mockImplementation()\n .mockRejectedValueOnce('')\n\n await expect(\n customData.setCustomData({\n client: ctx.clients.checkout,\n externalProviderResponse,\n orderForm,\n } as any)\n ).rejects.toThrowError('It was not possible to set customData.')\n })\n})\n\n```" } ]
code_payment-connector-aws-cdk-template_b4b73cf1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-template/test/vtex-connector.test.ts from the payment-connector-aws-cdk-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n// import * as cdk from 'aws-cdk-lib';\n// import { Template } from 'aws-cdk-lib/assertions';\n// import * as VtexConnector from '../lib/vtex-connector-stack';\n\n// example test. To run these tests, uncomment this file along with the\n// example resource in lib/vtex-connector-stack.ts\ntest('SQS Queue Created', () => {\n// const app = new cdk.App();\n// // WHEN\n// const stack = new VtexConnector.VtexConnectorStack(app, 'MyTestStack');\n// // THEN\n// const template = Template.fromStack(stack);\n\n// template.hasResourceProperties('AWS::SQS::Queue', {\n// VisibilityTimeout: 300\n// });\n});\n\n```" } ]
code_payment-connector-aws-cdk-template_4fc6a1aa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-template/test/vtex-connector.test.js from the payment-connector-aws-cdk-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n\"use strict\";\n// import * as cdk from 'aws-cdk-lib';\n// import { Template } from 'aws-cdk-lib/assertions';\n// import * as VtexConnector from '../lib/vtex-connector-stack';\n// example test. To run these tests, uncomment this file along with the\n// example resource in lib/vtex-connector-stack.ts\ntest('SQS Queue Created', () => {\n // const app = new cdk.App();\n // // WHEN\n // const stack = new VtexConnector.VtexConnectorStack(app, 'MyTestStack');\n // // THEN\n // const template = Template.fromStack(stack);\n // template.hasResourceProperties('AWS::SQS::Queue', {\n // VisibilityTimeout: 300\n // });\n});\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidnRleC1jb25uZWN0b3IudGVzdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInZ0ZXgtY29ubmVjdG9yLnRlc3QudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLHNDQUFzQztBQUN0QyxxREFBcUQ7QUFDckQsZ0VBQWdFO0FBRWhFLHVFQUF1RTtBQUN2RSxrREFBa0Q7QUFDbEQsSUFBSSxDQUFDLG1CQUFtQixFQUFFLEdBQUcsRUFBRTtJQUMvQiwrQkFBK0I7SUFDL0IsY0FBYztJQUNkLDRFQUE0RTtJQUM1RSxjQUFjO0lBQ2QsZ0RBQWdEO0lBRWhELHdEQUF3RDtJQUN4RCw2QkFBNkI7SUFDN0IsUUFBUTtBQUNSLENBQUMsQ0FBQyxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiLy8gaW1wb3J0ICogYXMgY2RrIGZyb20gJ2F3cy1jZGstbGliJztcbi8vIGltcG9ydCB7IFRlbXBsYXRlIH0gZnJvbSAnYXdzLWNkay1saWIvYXNzZXJ0aW9ucyc7XG4vLyBpbXBvcnQgKiBhcyBWdGV4Q29ubmVjdG9yIGZyb20gJy4uL2xpYi92dGV4LWNvbm5lY3Rvci1zdGFjayc7XG5cbi8vIGV4YW1wbGUgdGVzdC4gVG8gcnVuIHRoZXNlIHRlc3RzLCB1bmNvbW1lbnQgdGhpcyBmaWxlIGFsb25nIHdpdGggdGhlXG4vLyBleGFtcGxlIHJlc291cmNlIGluIGxpYi92dGV4LWNvbm5lY3Rvci1zdGFjay50c1xudGVzdCgnU1FTIFF1ZXVlIENyZWF0ZWQnLCAoKSA9PiB7XG4vLyAgIGNvbnN0IGFwcCA9IG5ldyBjZGsuQXBwKCk7XG4vLyAgICAgLy8gV0hFTlxuLy8gICBjb25zdCBzdGFjayA9IG5ldyBWdGV4Q29ubmVjdG9yLlZ0ZXhDb25uZWN0b3JTdGFjayhhcHAsICdNeVRlc3RTdGFjaycpO1xuLy8gICAgIC8vIFRIRU5cbi8vICAgY29uc3QgdGVtcGxhdGUgPSBUZW1wbGF0ZS5mcm9tU3RhY2soc3RhY2spO1xuXG4vLyAgIHRlbXBsYXRlLmhhc1Jlc291cmNlUHJvcGVydGllcygnQVdTOjpTUVM6OlF1ZXVlJywge1xuLy8gICAgIFZpc2liaWxpdHlUaW1lb3V0OiAzMDBcbi8vICAgfSk7XG59KTtcbiJdfQ==\n```" } ]
code_payment-connector-aws-cdk-template_580a24a5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-template/bin/vtex-connector.ts from the payment-connector-aws-cdk-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n#!/usr/bin/env node\nimport 'source-map-support/register';\nimport * as cdk from 'aws-cdk-lib';\nimport { VtexConnectorStack } from '../lib/vtex-connector-stack';\n\nconst app = new cdk.App();\nnew VtexConnectorStack(app, 'VtexConnectorStack', {\n /* If you don't specify 'env', this stack will be environment-agnostic.\n * Account/Region-dependent features and context lookups will not work,\n * but a single synthesized template can be deployed anywhere. */\n\n /* Uncomment the next line to specialize this stack for the AWS Account\n * and Region that are implied by the current CLI configuration. */\n // env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },\n\n /* Uncomment the next line if you know exactly what Account and Region you\n * want to deploy the stack to. */\n // env: { account: '123456789012', region: 'us-east-1' },\n\n /* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */\n});\n```" } ]
code_payment-connector-aws-cdk-template_92d93afc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-template/bin/vtex-connector.d.ts from the payment-connector-aws-cdk-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n#!/usr/bin/env node\nimport 'source-map-support/register';\n\n```" } ]
code_payment-connector-aws-cdk-template_ecae82a1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-template/bin/vtex-connector.js from the payment-connector-aws-cdk-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n#!/usr/bin/env node\n\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nrequire(\"source-map-support/register\");\nconst cdk = require(\"aws-cdk-lib\");\nconst vtex_connector_stack_1 = require(\"../lib/vtex-connector-stack\");\nconst app = new cdk.App();\nnew vtex_connector_stack_1.VtexConnectorStack(app, 'VtexConnectorStack', {\n/* If you don't specify 'env', this stack will be environment-agnostic.\n * Account/Region-dependent features and context lookups will not work,\n * but a single synthesized template can be deployed anywhere. */\n/* Uncomment the next line to specialize this stack for the AWS Account\n * and Region that are implied by the current CLI configuration. */\n// env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },\n/* Uncomment the next line if you know exactly what Account and Region you\n * want to deploy the stack to. */\n// env: { account: '123456789012', region: 'us-east-1' },\n/* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */\n});\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidnRleC1jb25uZWN0b3IuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJ2dGV4LWNvbm5lY3Rvci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFDQSx1Q0FBcUM7QUFDckMsbUNBQW1DO0FBQ25DLHNFQUFpRTtBQUVqRSxNQUFNLEdBQUcsR0FBRyxJQUFJLEdBQUcsQ0FBQyxHQUFHLEVBQUUsQ0FBQztBQUMxQixJQUFJLHlDQUFrQixDQUFDLEdBQUcsRUFBRSxvQkFBb0IsRUFBRTtBQUNoRDs7aUVBRWlFO0FBRWpFO21FQUNtRTtBQUNuRSw2RkFBNkY7QUFFN0Y7a0NBQ2tDO0FBQ2xDLHlEQUF5RDtBQUV6RCw4RkFBOEY7Q0FDL0YsQ0FBQyxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiIyEvdXNyL2Jpbi9lbnYgbm9kZVxuaW1wb3J0ICdzb3VyY2UtbWFwLXN1cHBvcnQvcmVnaXN0ZXInO1xuaW1wb3J0ICogYXMgY2RrIGZyb20gJ2F3cy1jZGstbGliJztcbmltcG9ydCB7IFZ0ZXhDb25uZWN0b3JTdGFjayB9IGZyb20gJy4uL2xpYi92dGV4LWNvbm5lY3Rvci1zdGFjayc7XG5cbmNvbnN0IGFwcCA9IG5ldyBjZGsuQXBwKCk7XG5uZXcgVnRleENvbm5lY3RvclN0YWNrKGFwcCwgJ1Z0ZXhDb25uZWN0b3JTdGFjaycsIHtcbiAgLyogSWYgeW91IGRvbid0IHNwZWNpZnkgJ2VudicsIHRoaXMgc3RhY2sgd2lsbCBiZSBlbnZpcm9ubWVudC1hZ25vc3RpYy5cbiAgICogQWNjb3VudC9SZWdpb24tZGVwZW5kZW50IGZlYXR1cmVzIGFuZCBjb250ZXh0IGxvb2t1cHMgd2lsbCBub3Qgd29yayxcbiAgICogYnV0IGEgc2luZ2xlIHN5bnRoZXNpemVkIHRlbXBsYXRlIGNhbiBiZSBkZXBsb3llZCBhbnl3aGVyZS4gKi9cblxuICAvKiBVbmNvbW1lbnQgdGhlIG5leHQgbGluZSB0byBzcGVjaWFsaXplIHRoaXMgc3RhY2sgZm9yIHRoZSBBV1MgQWNjb3VudFxuICAgKiBhbmQgUmVnaW9uIHRoYXQgYXJlIGltcGxpZWQgYnkgdGhlIGN1cnJlbnQgQ0xJIGNvbmZpZ3VyYXRpb24uICovXG4gIC8vIGVudjogeyBhY2NvdW50OiBwcm9jZXNzLmVudi5DREtfREVGQVVMVF9BQ0NPVU5ULCByZWdpb246IHByb2Nlc3MuZW52LkNES19ERUZBVUxUX1JFR0lPTiB9LFxuXG4gIC8qIFVuY29tbWVudCB0aGUgbmV4dCBsaW5lIGlmIHlvdSBrbm93IGV4YWN0bHkgd2hhdCBBY2NvdW50IGFuZCBSZWdpb24geW91XG4gICAqIHdhbnQgdG8gZGVwbG95IHRoZSBzdGFjayB0by4gKi9cbiAgLy8gZW52OiB7IGFjY291bnQ6ICcxMjM0NTY3ODkwMTInLCByZWdpb246ICd1cy1lYXN0LTEnIH0sXG5cbiAgLyogRm9yIG1vcmUgaW5mb3JtYXRpb24sIHNlZSBodHRwczovL2RvY3MuYXdzLmFtYXpvbi5jb20vY2RrL2xhdGVzdC9ndWlkZS9lbnZpcm9ubWVudHMuaHRtbCAqL1xufSk7Il19\n```" } ]
code_payment-connector-aws-cdk-template_0e78bfd1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-template/lib/vtex-frontend-stack.ts from the payment-connector-aws-cdk-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as cdk from \"aws-cdk-lib\";\nimport * as s3 from \"aws-cdk-lib/aws-s3\";\nimport * as s3deploy from \"aws-cdk-lib/aws-s3-deployment\";\nimport * as cloudFront from \"aws-cdk-lib/aws-cloudfront\";\n\nexport const configureFrontend = (scope: any) => {\n ///////////// FRONTEND\n // Add S3 Bucket\n const s3Site = new s3.Bucket(scope, `FrontEndHackathonVTEX`, {\n bucketName: `${scope.account}-vtexday-hackathon`,\n removalPolicy: cdk.RemovalPolicy.DESTROY,\n autoDeleteObjects: true,\n websiteIndexDocument: \"index.html\",\n websiteErrorDocument: \"index.html\",\n });\n\n\n // Create Origin Access Identity and have s3 grant read access\n const oai = new cloudFront.OriginAccessIdentity(\n scope,\n `frontend-hackathon-vtex-origin-access-id`,\n {}\n );\n s3Site.grantRead(oai);\n\n // Create a new CloudFront Distribution\n const distribution = new cloudFront.CloudFrontWebDistribution(\n scope,\n `myreactapp-cf-distribution`,\n {\n originConfigs: [\n {\n s3OriginSource: {\n s3BucketSource: s3Site,\n originAccessIdentity: oai,\n },\n behaviors: [\n {\n isDefaultBehavior: true,\n compress: true,\n allowedMethods: cloudFront.CloudFrontAllowedMethods.ALL,\n cachedMethods:\n cloudFront.CloudFrontAllowedCachedMethods.GET_HEAD_OPTIONS,\n forwardedValues: {\n queryString: true,\n cookies: {\n forward: \"none\",\n },\n headers: [\n \"Access-Control-Request-Headers\",\n \"Access-Control-Request-Method\",\n \"Origin\",\n ],\n },\n },\n ],\n },\n ],\n comment: `myreactapp - CloudFront Distribution`,\n viewerProtocolPolicy: cloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,\n }\n );\n\n // Setup Bucket Deployment to automatically deploy new assets and invalidate cache\n new s3deploy.BucketDeployment(\n scope,\n `frontend-hackathon-vtex-s3bucketdeployment`,\n {\n sources: [s3deploy.Source.asset(\"frontend/build\")],\n destinationBucket: s3Site,\n distribution: distribution,\n distributionPaths: [\"/*\"],\n }\n );\n\n // Final CloudFront URL\n new cdk.CfnOutput(scope, \"CloudFront URL\", {\n value: distribution.distributionDomainName,\n });\n\n const enableCorsOnBucket = (bucket: s3.IBucket) => {\n const cfnBucket = bucket.node.findChild(\"Resource\") as s3.CfnBucket;\n cfnBucket.addPropertyOverride(\"CorsConfiguration\", {\n CorsRules: [\n {\n AllowedOrigins: [\"*\"],\n AllowedMethods: [\"HEAD\", \"GET\", \"PUT\", \"POST\", \"DELETE\"],\n ExposedHeaders: [\n \"x-amz-server-side-encryption\",\n \"x-amz-request-id\",\n \"x-amz-id-2\"\n ],\n AllowedHeaders: [\"*\"]\n }\n ]\n });\n };\n enableCorsOnBucket(s3Site);\n};\n\n```" } ]
code_payment-connector-aws-cdk-template_39c0e773
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-template/lib/vtex-backend-stack.ts from the payment-connector-aws-cdk-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as cdk from \"aws-cdk-lib\";\nimport * as sqs from \"aws-cdk-lib/aws-sqs\";\nimport * as DynamoDB from \"aws-cdk-lib/aws-dynamodb\";\nimport * as Lambda from \"aws-cdk-lib/aws-lambda\";\nimport * as APIGateway from \"aws-cdk-lib/aws-apigateway\";\nimport * as path from \"path\";\nimport { DynamoEventSource } from \"aws-cdk-lib/aws-lambda-event-sources\";\nimport { SqsEventSource } from \"aws-cdk-lib/aws-lambda-event-sources\";\n\nexport const configureBackend = (scope: any) => {\n const AdquirencyAPI = \"testing-12345/v2\"\n\n /////// DynamoDB\n\n //Create a DynamoDB table called PaymentTrackTable\n const PaymentTrackTable = new DynamoDB.Table(scope, \"PaymentTrackTable\", {\n partitionKey: {\n name: \"paymentId\",\n type: DynamoDB.AttributeType.STRING,\n },\n tableName: \"PaymentTrackTable\",\n billingMode: DynamoDB.BillingMode.PAY_PER_REQUEST,\n stream: DynamoDB.StreamViewType.NEW_IMAGE,\n removalPolicy: cdk.RemovalPolicy.DESTROY,\n });\n\n /////// QUEUE\n\n //create an SQS queue called PendingPaymentQueue\n const PendingPaymentQueue = new sqs.Queue(scope, \"PendingPaymentQueue\", {\n queueName: \"PendingPaymentQueue\",\n visibilityTimeout: cdk.Duration.seconds(30),\n receiveMessageWaitTime: cdk.Duration.seconds(10),\n retentionPeriod: cdk.Duration.days(1),\n encryption: sqs.QueueEncryption.SQS_MANAGED,\n });\n\n /////// API GATEWAY\n\n //Create an API Gateway using Lambda Proxy\n const PaymentApi = new APIGateway.RestApi(scope, \"PaymentApi\", {\n restApiName: \"PaymentApi\",\n description: \"PaymentApi\",\n deployOptions: {\n stageName: \"Prod\",\n },\n defaultCorsPreflightOptions: {\n allowOrigins: APIGateway.Cors.ALL_ORIGINS,\n allowMethods: APIGateway.Cors.ALL_METHODS\n }\n });\n\n //// LAMBDAS\n\n //Create Payment Lambda function\n const Payment = new Lambda.Function(scope, \"Payment\", {\n runtime: Lambda.Runtime.PYTHON_3_9,\n code: Lambda.Code.fromAsset(\n path.join(__dirname, \"../backend-connector/Payment\"),\n {\n bundling: {\n image: Lambda.Runtime.PYTHON_3_9.bundlingImage,\n command: [\n \"bash\",\n \"-c\",\n \"pip install -r requirements.txt -t /asset-output && cp -au . /asset-output\",\n ],\n },\n }\n ),\n memorySize: 128,\n handler: \"app.lambda_handler\",\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName,\n API_URL: `https://${AdquirencyAPI}/payment`,\n },\n });\n\n //Create UserPost Lambda function\n const UserApi = new Lambda.Function(scope, \"User\", {\n runtime: Lambda.Runtime.PYTHON_3_9,\n code: Lambda.Code.fromAsset(\n path.join(__dirname, \"../backend-front/User\"),\n {\n bundling: {\n image: Lambda.Runtime.PYTHON_3_9.bundlingImage,\n command: [\n \"bash\",\n \"-c\",\n \"pip install -r requirements.txt -t /asset-output && cp -au . /asset-output\",\n ],\n },\n }\n ),\n memorySize: 128,\n handler: \"app.lambda_handler\",\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName\n },\n });\n\n //Create Manifest Lambda function\n const Manifest = new Lambda.Function(scope, \"Manifest\", {\n runtime: Lambda.Runtime.PYTHON_3_9,\n code: Lambda.Code.fromAsset(\n path.join(__dirname, \"../backend-connector/Manifest\"),\n {\n bundling: {\n image: Lambda.Runtime.PYTHON_3_9.bundlingImage,\n command: [\n \"bash\",\n \"-c\",\n \"pip install -r requirements.txt -t /asset-output && cp -au . /asset-output\",\n ],\n },\n }\n ),\n memorySize: 128,\n handler: \"app.lambda_handler\"\n });\n\n //Create Settlement Lambda function\n const Settlement = new Lambda.Function(scope, \"Settlement\", {\n runtime: Lambda.Runtime.PYTHON_3_9,\n code: Lambda.Code.fromAsset(\n path.join(__dirname, \"../backend-connector/Settlement\"),\n {\n bundling: {\n image: Lambda.Runtime.PYTHON_3_9.bundlingImage,\n command: [\n \"bash\",\n \"-c\",\n \"pip install -r requirements.txt -t /asset-output && cp -au . /asset-output\",\n ],\n },\n }\n ),\n memorySize: 128,\n handler: \"app.lambda_handler\"\n });\n\n //Create Refund Lambda function\n const Refund = new Lambda.Function(scope, \"Refund\", {\n runtime: Lambda.Runtime.PYTHON_3_9,\n code: Lambda.Code.fromAsset(\n path.join(__dirname, \"../backend-connector/Refund\"),\n {\n bundling: {\n image: Lambda.Runtime.PYTHON_3_9.bundlingImage,\n command: [\n \"bash\",\n \"-c\",\n \"pip install -r requirements.txt -t /asset-output && cp -au . /asset-output\",\n ],\n },\n }\n ),\n memorySize: 128,\n handler: \"app.lambda_handler\"\n });\n\n //Create Cancellation Lambda function\n const Cancellation = new Lambda.Function(scope, \"Cancellation\", {\n runtime: Lambda.Runtime.PYTHON_3_9,\n code: Lambda.Code.fromAsset(\n path.join(__dirname, \"../backend-connector/Cancellation\"),\n {\n bundling: {\n image: Lambda.Runtime.PYTHON_3_9.bundlingImage,\n command: [\n \"bash\",\n \"-c\",\n \"pip install -r requirements.txt -t /asset-output && cp -au . /asset-output\",\n ],\n },\n }\n ),\n memorySize: 128,\n handler: \"app.lambda_handler\"\n });\n\n //create api resource for Lambda Proxy\n const PaymentResource = PaymentApi.root.addResource(\"payments\");\n const UserApiResource = PaymentApi.root.addResource(\"user\");\n const ManifestResource = PaymentApi.root.addResource(\"manifest\");\n const SettlementResource = PaymentApi.root.addResource(\"settlements\");\n const CancellationResource = PaymentApi.root.addResource(\"cancellations\");\n const RefundResource = PaymentApi.root.addResource(\"refunds\");\n\n //create Lambda Proxy Integration\n const PaymentLambdaIntegration = new APIGateway.LambdaIntegration(\n Payment,\n {\n proxy: true,\n }\n );\n const ManifestLambdaIntegration = new APIGateway.LambdaIntegration(\n Manifest,\n {\n proxy: true,\n }\n );\n const UserApiLambdaIntegration = new APIGateway.LambdaIntegration(\n UserApi,\n {\n proxy: true,\n }\n );\n const SettlementLambdaIntegration = new APIGateway.LambdaIntegration(\n Settlement,\n {\n proxy: true,\n }\n );\n const CancellationLambdaIntegration = new APIGateway.LambdaIntegration(\n Cancellation,\n {\n proxy: true,\n }\n );\n const RefundLambdaIntegration = new APIGateway.LambdaIntegration(\n Refund,\n {\n proxy: true,\n }\n );\n\n //add Lambda Proxy Integration to apiResource\n PaymentResource.addMethod(\"POST\", PaymentLambdaIntegration);\n ManifestResource.addMethod(\"GET\", ManifestLambdaIntegration);\n UserApiResource.addMethod(\"POST\", UserApiLambdaIntegration);\n SettlementResource.addMethod(\"POST\", SettlementLambdaIntegration);\n CancellationResource.addMethod(\"POST\", CancellationLambdaIntegration);\n RefundResource.addMethod(\"POST\", RefundLambdaIntegration);\n\n //Create PendingPaymentStream Lambda function\n const PendingPaymentStream = new Lambda.Function(\n scope,\n \"PendingPaymentStream\",\n {\n runtime: Lambda.Runtime.PYTHON_3_9,\n code: Lambda.Code.fromAsset(\n path.join(__dirname, \"../backend-connector/PendingPaymentStream\"),\n {\n bundling: {\n image: Lambda.Runtime.PYTHON_3_9.bundlingImage,\n command: [\n \"bash\",\n \"-c\",\n \"pip install -r requirements.txt -t /asset-output && cp -au . /asset-output\",\n ],\n },\n }\n ),\n memorySize: 128,\n handler: \"app.lambda_handler\",\n environment: {\n TABLE_NAME: PaymentTrackTable.tableName,\n PENDING_PAYMENT_QUEUE: PendingPaymentQueue.queueName,\n },\n }\n );\n\n //Add DynamoDB Event Source for Stream with filter\n PendingPaymentStream.addEventSource(\n new DynamoEventSource(PaymentTrackTable, {\n startingPosition: Lambda.StartingPosition.TRIM_HORIZON,\n batchSize: 1,\n // onFailure: new SqsDlq(deadLetterQueue),\n retryAttempts: 10,\n filters: [\n Lambda.FilterCriteria.filter({\n eventName: Lambda.FilterRule.isEqual(\"INSERT\"),\n dynamodb: {\n NewImage: {\n status: { S: Lambda.FilterRule.isEqual(\"undefined\") },\n },\n },\n }),\n Lambda.FilterCriteria.filter({\n eventName: Lambda.FilterRule.isEqual(\"MODIFY\"),\n dynamodb: {\n NewImage: {\n status: { S: Lambda.FilterRule.isEqual(\"undefined\") },\n },\n },\n }),\n ],\n })\n );\n\n //Create ProcessPendingPayment Lambda function\n const ProcessPendingPayment = new Lambda.Function(\n scope,\n \"ProcessPendingPayment\",\n {\n runtime: Lambda.Runtime.PYTHON_3_9,\n code: Lambda.Code.fromAsset(\n path.join(__dirname, \"../backend-connector/ProcessPendingPayment\"),\n {\n bundling: {\n image: Lambda.Runtime.PYTHON_3_9.bundlingImage,\n command: [\n \"bash\",\n \"-c\",\n \"pip install -r requirements.txt -t /asset-output && cp -au . /asset-output\",\n ],\n },\n }\n ),\n memorySize: 128,\n handler: \"app.lambda_handler\",\n environment: {\n PENDING_PAYMENT_QUEUE: PendingPaymentQueue.queueName,\n API_URL: `https://${AdquirencyAPI}`,\n },\n }\n );\n\n ProcessPendingPayment.addEventSource(\n new SqsEventSource(PendingPaymentQueue, {\n batchSize: 1,\n enabled: true,\n reportBatchItemFailures: true,\n // retryAttempts: 10,\n // maxConcurrency: 2,\n })\n );\n\n /////// PERMISSIONS\n\n //Provide access to Lambdas on PaymentTrackTable\n PaymentTrackTable.grantReadWriteData(Payment);\n PaymentTrackTable.grantReadWriteData(PendingPaymentStream);\n PaymentTrackTable.grantReadWriteData(ProcessPendingPayment);\n PaymentTrackTable.grantStreamRead(PendingPaymentStream);\n\n //Provide access to PendingPaymentStream on\n PendingPaymentQueue.grantSendMessages(PendingPaymentStream);\n PendingPaymentQueue.grantConsumeMessages(ProcessPendingPayment);\n};\n\n```" } ]
code_payment-connector-aws-cdk-template_3395a220
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of payment-connector-aws-cdk-template/lib/vtex-connector-stack.ts from the payment-connector-aws-cdk-template VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as cdk from \"aws-cdk-lib\";\nimport { Construct } from \"constructs\";\nimport { configureBackend } from \"./vtex-backend-stack\";\nimport { configureFrontend } from \"./vtex-frontend-stack\";\n\nexport class VtexConnectorStack extends cdk.Stack {\n constructor(scope: Construct, id: string, props?: cdk.StackProps) {\n super(scope, id, props);\n\n configureFrontend(this);\n configureBackend(this);\n\n }\n}\n\n```" } ]
code_checkout-fullstory_4a68b7df
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of checkout-fullstory/docs/README.md from the checkout-fullstory VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/{OrganizationName}/{AppName}) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# VTEX FULLSTORY IDENTIFICATION\n\n⚠️⚠️ **This is an ongoing, unsupported, unfinished and undocumented project. We do not guarantee any results after installation, use it at your own risk.** ⚠️⚠️\n\nThis app injects the Fullstory script to the Checkout IO pages.\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\n## Configuration \n\nSimply install this app in the workspace you're interested in collecting data from.\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n----\n\n```" } ]
code_product-gifts_421183a3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/messages/ja.json from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.gift-image.title\": \"ギフト画像\",\n \"admin/editor.gift-image.description\": \"製品のギフト画像\",\n \"admin/editor.gift-image.imageLabel.title\": \"画像ラベル\",\n \"admin/editor.gift-image.imageLabel.description\": \"表示する製品の画像を指定するラベルです。\",\n \"admin/editor.gift-name.title\": \"ギフト名\",\n \"admin/editor.gift-name.description\": \"ギフトの名前です。\",\n \"admin/editor.gift-name.linkToProduct.title\": \"製品ページへのリンク\",\n \"admin/editor.gift-name.linkToProduct.description\": \"ギフト名が製品ページにもリンクするかどうかを定めます。\",\n \"admin/editor.gift-name.nameType.title\": \"表示名タイプ\",\n \"admin/editor.gift-name.nameType.description\": \"ギフトの SKU 名または製品名を表示します。\",\n \"admin/editor.product-gifts.title\": \"製品ギフト\",\n \"admin/editor.product-gifts.description\": \"現在の製品に利用できるギフトを表示します。\",\n \"admin/editor.product-gifts.maxVisibleItems.title\": \"最大表示項目\",\n \"admin/editor.product-gifts.maxVisibleItems.description\": \"同時にレンダリングされるギフトの最大数です。 (「すべて表示」を使うと、利用できるギフトを常にすべて表示します)\",\n \"admin/editor.product-gift-text.title\": \"製品ギフトテキスト\",\n \"admin/editor.product-gift-text.description\": \"利用できるギフトに関連した追加情報\",\n \"admin/editor.product-gift-text.text.title\": \"テキスト\",\n \"admin/editor.product-gift-text.text.description\": \"ギフトに関連したテキストのレンダリングに使う変数のある、翻訳可能な文字列です。フォーマットは UCI ルールを使っており、利用できる変数は以下の通りです: totalGifts、exceedingItems、visibleItems。\"\n}\n```" } ]
code_product-gifts_5f32b815
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/messages/pt.json from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.gift-image.title\": \"Imagem do presente\",\n \"admin/editor.gift-image.description\": \"Imagem do presente para ser renderizada na lista de presentes.\",\n \"admin/editor.gift-image.imageLabel.title\": \"Label da imagem\",\n \"admin/editor.gift-image.imageLabel.description\": \"Label da imagem que deve ser renderizada para o presente.\",\n \"admin/editor.gift-name.title\": \"Nome do presente\",\n \"admin/editor.gift-name.description\": \"Nome do presente\",\n \"admin/editor.gift-name.linkToProduct.title\": \"Link para página de produto\",\n \"admin/editor.gift-name.linkToProduct.description\": \"Nome do presente é um link para sua página do produto.\",\n \"admin/editor.gift-name.nameType.title\": \"Tipo de nome de exibição\",\n \"admin/editor.gift-name.nameType.description\": \"Mostrar o skuName ou produtoNome do presente.\",\n \"admin/editor.product-gifts.title\": \"Presentes\",\n \"admin/editor.product-gifts.description\": \"Mostre os presentes associados com o produto.\",\n \"admin/editor.product-gifts.maxVisibleItems.title\": \"Máximo de itens visíveis\",\n \"admin/editor.product-gifts.maxVisibleItems.description\": \"Número máximo de presentes a serem mostrados na lista. Utilize o valor \\\"Show all\\\" para mostrar sempre todos.\",\n \"admin/editor.product-gift-text.title\": \"Texto auxiliar para presentes\",\n \"admin/editor.product-gift-text.description\": \"Texto auxiliar para presentes.\",\n \"admin/editor.product-gift-text.text.title\": \"Texto\",\n \"admin/editor.product-gift-text.text.description\": \"Texto que aceita variáveis e segue o padrão UCI para formatação. As variáveis disponíveis são: totalGifts, exceedingItems and visibleItems.\"\n}\n```" } ]
code_product-gifts_b8b3e436
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/messages/en.json from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.gift-image.title\": \"Gift Image\",\n \"admin/editor.gift-image.description\": \"Product's gift image\",\n \"admin/editor.gift-image.imageLabel.title\": \"Image label\",\n \"admin/editor.gift-image.imageLabel.description\": \"Label to specify which image from the product should be displayed.\",\n \"admin/editor.gift-name.title\": \"Gift Name\",\n \"admin/editor.gift-name.description\": \"Name of the gift.\",\n \"admin/editor.gift-name.linkToProduct.title\": \"Link to product page\",\n \"admin/editor.gift-name.linkToProduct.description\": \"Whether or not the gift-name should also be a link to the product page.\",\n \"admin/editor.gift-name.nameType.title\": \"Type of display name\",\n \"admin/editor.gift-name.nameType.description\": \"Show the gift's skuName or productName.\",\n \"admin/editor.product-gifts.title\": \"Product Gifts\",\n \"admin/editor.product-gifts.description\": \"Display available gifts for the current product.\",\n \"admin/editor.product-gifts.maxVisibleItems.title\": \"Maximum visible items\",\n \"admin/editor.product-gifts.maxVisibleItems.description\": \"Maximum number of gifts that should be rendered at once. (use \\\"showAll\\\" to always show all available gifts)\",\n \"admin/editor.product-gift-text.title\": \"Product Gifts Text\",\n \"admin/editor.product-gift-text.description\": \"Additional information regarding available gifts\",\n \"admin/editor.product-gift-text.text.title\": \"Text\",\n \"admin/editor.product-gift-text.text.description\": \"A translatable string that has variables that might be used to render any text regarding the gifts. Its format uses UCI rules and the available variables are: totalGifts, exceedingItems and visibleItems.\"\n}\n```" } ]
code_product-gifts_35dfd63a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/messages/fr.json from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.gift-image.title\": \"Image du cadeau\",\n \"admin/editor.gift-image.description\": \"Image du cadeau du produit\",\n \"admin/editor.gift-image.imageLabel.title\": \"Étiquette de l’image\",\n \"admin/editor.gift-image.imageLabel.description\": \"Étiquette pour spécifier quelle image du produit doit être affichée.\",\n \"admin/editor.gift-name.title\": \"Nom du cadeau\",\n \"admin/editor.gift-name.description\": \"Nom du cadeau.\",\n \"admin/editor.gift-name.linkToProduct.title\": \"Lien vers la page produit\",\n \"admin/editor.gift-name.linkToProduct.description\": \"Si le nom du cadeau doit être un lien vers la page du produit.\",\n \"admin/editor.gift-name.nameType.title\": \"Type de nom d’affichage\",\n \"admin/editor.gift-name.nameType.description\": \"Afficher le NomDeSku du cadeau ou le NomDuProduit.\",\n \"admin/editor.product-gifts.title\": \"Cadeaux du produit\",\n \"admin/editor.product-gifts.description\": \"Afficher les cadeaux disponibles pour le produit actuel.\",\n \"admin/editor.product-gifts.maxVisibleItems.title\": \"Nombre maximum d’éléments visibles\",\n \"admin/editor.product-gifts.maxVisibleItems.description\": \"Nombre maximum de cadeaux qui doivent être rendus en même temps. (utilisez \\\"toutAfficher\\\" pour toujours afficher tous les cadeaux disponibles)\",\n \"admin/editor.product-gift-text.title\": \"Texte des cadeaux de produit\",\n \"admin/editor.product-gift-text.description\": \"Informations complémentaires sur les cadeaux disponibles\",\n \"admin/editor.product-gift-text.text.title\": \"Texte\",\n \"admin/editor.product-gift-text.text.description\": \"Une chaîne de caractères traduisible qui a des variables qui pouvant être utilisées pour rendre n’importe quel texte concernant les cadeaux. Son format utilise les règles UCI et les variables disponibles sont : TotalCadeaux, ArticlesEnSurplus et ArticlesVisibles.\"\n}\n```" } ]
code_product-gifts_d2a387b6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/messages/ko.json from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.gift-image.title\": \"선물 이미지\",\n \"admin/editor.gift-image.description\": \"제품의 선물 이미지\",\n \"admin/editor.gift-image.imageLabel.title\": \"이미지 라벨\",\n \"admin/editor.gift-image.imageLabel.description\": \"표시할 제품의 이미지를 지정하는 라벨.\",\n \"admin/editor.gift-name.title\": \"선물 이름\",\n \"admin/editor.gift-name.description\": \"선물 이름.\",\n \"admin/editor.gift-name.linkToProduct.title\": \"제품 페이지 링크\",\n \"admin/editor.gift-name.linkToProduct.description\": \"선물 이름이 제품 페이지에 대한 링크여야 하는지.\",\n \"admin/editor.gift-name.nameType.title\": \"표시 이름 유형\",\n \"admin/editor.gift-name.nameType.description\": \"선물의 skuName 또는 productName을 표시합니다.\",\n \"admin/editor.product-gifts.title\": \"제품 선물\",\n \"admin/editor.product-gifts.description\": \"현재 제품에 사용할 수 있는 선물 표시.\",\n \"admin/editor.product-gifts.maxVisibleItems.title\": \"표시되는 최대 항목 수\",\n \"admin/editor.product-gifts.maxVisibleItems.description\": \"한 번에 제공해야 하는 최대 선물 수입니다.(사용 가능한 모든 선물을 항상 표시하려면 \\\"모두 표시\\\" 사용)\",\n \"admin/editor.product-gift-text.title\": \"제품 선물 텍스트\",\n \"admin/editor.product-gift-text.description\": \"사용 가능한 선물에 대한 추가 정보\",\n \"admin/editor.product-gift-text.text.title\": \"텍스트\",\n \"admin/editor.product-gift-text.text.description\": \"선물에 관한 텍스트를 렌더링하는 데 사용할 수있는 변수가 있는 번역 가능한 문자열입니다. 형식은 UCI 규칙을 사용하며 사용 가능한 변수는 totalGifts, exceedingItems 및 visibleItems입니다.\"\n}\n```" } ]
code_product-gifts_809aabde
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/messages/th.json from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.gift-image.title\": \"รูปของขวัญ\",\n \"admin/editor.gift-image.description\": \"รูปของขวัญผลิตภัณฑ์\",\n \"admin/editor.gift-image.imageLabel.title\": \"ป้ายกำกับรูป\",\n \"admin/editor.gift-image.imageLabel.description\": \"ป้ายกำกับที่ระบุว่าควรแสดงรูปใดจากผลิตภัณฑ์\",\n \"admin/editor.gift-name.title\": \"ชื่อของขวัญ\",\n \"admin/editor.gift-name.description\": \"ชื่อของของขวัญ\",\n \"admin/editor.gift-name.linkToProduct.title\": \"เชื่อมโยงไปหน้าผลิตภัณฑ์\",\n \"admin/editor.gift-name.linkToProduct.description\": \"ชื่อของขวัญควรเป็นลิงก์เชื่อมโยงไปหน้าผลิตภัณฑ์หรือไม่\",\n \"admin/editor.gift-name.nameType.title\": \"ประเภทชื่อการแสดง\",\n \"admin/editor.gift-name.nameType.description\": \"แสดงชื่อ skuName หรือ productName ของของขวัญ\",\n \"admin/editor.product-gifts.title\": \"ของขวัญผลิตภัณฑ์\",\n \"admin/editor.product-gifts.description\": \"แสดงของขวัญที่มีสำหรับผลิตภัณฑ์ปัจจุบัน\",\n \"admin/editor.product-gifts.maxVisibleItems.title\": \"จำนวนสูงสุดของรายการสินค้าที่มองเห็นได้\",\n \"admin/editor.product-gifts.maxVisibleItems.description\": \"จำนวนสูงสุดของของขวัญที่จะแสดงทันที (ใช้ \\\"showAll\\\" เสมอเพื่อแสดงของขวัญทั้งหมดที่มี)\",\n \"admin/editor.product-gift-text.title\": \"ข้อความของขวัญผลิตภัณฑ์\",\n \"admin/editor.product-gift-text.description\": \"ข้อมูลเพิ่มเติมเกี่ยวกับของขวัญที่มี\",\n \"admin/editor.product-gift-text.text.title\": \"ข้อความ\",\n \"admin/editor.product-gift-text.text.description\": \"ข้อความที่แปลได้ซึ่งมีตัวแปรที่อาจใช้แสดงข้อความใด ๆ ที่เกี่ยวกับของขวัญ รูปแบบที่ใช้เป็นกฎ UCI และตัวแปรที่มีคือ: totalGifts, exceedingItems และ visibleItems\"\n}\n```" } ]
code_product-gifts_e5b2a95d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/messages/es.json from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.gift-image.title\": \"Imagen del regalo\",\n \"admin/editor.gift-image.description\": \"Imagen de regalo del producto\",\n \"admin/editor.gift-image.imageLabel.title\": \"Etiqueta de imagen\",\n \"admin/editor.gift-image.imageLabel.description\": \"Etiqueta para especificar qué imagen del producto debe mostrarse.\",\n \"admin/editor.gift-name.title\": \"Nombre del regalo\",\n \"admin/editor.gift-name.description\": \"Nombre del regalo.\",\n \"admin/editor.gift-name.linkToProduct.title\": \"Link a la página de producto\",\n \"admin/editor.gift-name.linkToProduct.description\": \"Si el nombre del regalo también debe ser un link a la página de producto.\",\n \"admin/editor.gift-name.nameType.title\": \"Tipo de nombre mostrado\",\n \"admin/editor.gift-name.nameType.description\": \"Mostrar el skuName o productName del regalo.\",\n \"admin/editor.product-gifts.title\": \"Regalos de productos\",\n \"admin/editor.product-gifts.description\": \"Mostrar regalos disponibles para el producto actual.\",\n \"admin/editor.product-gifts.maxVisibleItems.title\": \"Máximo de ítems visibles\",\n \"admin/editor.product-gifts.maxVisibleItems.description\": \"Número máximo de regalos que se deben renderizar a la vez. (Utiliza \\\"showAll\\\" para mostrar siempre todos los regalos disponibles.)\",\n \"admin/editor.product-gift-text.title\": \"Texto de regalos del producto\",\n \"admin/editor.product-gift-text.description\": \"Información adicional sobre regalos disponibles.\",\n \"admin/editor.product-gift-text.text.title\": \"Texto\",\n \"admin/editor.product-gift-text.text.description\": \"Una cadena traducible que tiene variables que podrían usarse para renderizar cualquier texto relacionado con los regalos. Su formato utiliza reglas UCI y las variables disponibles son: totalGifts, exceedingItems y visibleItems.\"\n}\n```" } ]
code_product-gifts_49dabc27
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/docs/README.md from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/product-gifts) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Product Gifts\n\nThe Product Gifts app provides blocks responsible for displaying, in the Product Description block, all gifts available for a given product.\n\n:information_source: *A product's gift is configured in a [Buy&Win promotion](https://help.vtex.com/tutorial/buy-and-win--tutorials_322)*\n\n![product-gift](https://user-images.githubusercontent.com/52087100/75782082-20a08380-5d3d-11ea-9ae1-60873e03f1ac.png)\n\n## Configuration\n\n1. Add the `product-gifts` app to your theme's dependencies in the `manifest.json`. For example:\n\n```json\n\"dependencies\": {\n \"vtex.product-gifts\": \"0.x\"\n}\n```\n\nNow, you are able to use all blocks exported by the `product-gifts` app. Check out the full list below:\n\n| Block name | Description |\n| -------------- | ----------------------------------------------- |\n| `product-gifts`| ![mandatory](https://img.shields.io/badge/-Mandatory-red) Renders a default Product Gifts block implementation. | \n| `gift-text` | ![mandatory](https://img.shields.io/badge/-Mandatory-red) Reads Catalog data regarding the product's gifts and provides it to its children. |\n| `product-gift-list` | Renders the available gifts in a list format. It also provides context for its 3 children listed below. |\n| `gift-name` | Renders the product's gift name. |\n| `gift-image` | Renders the product's gift image.|\n| `gift-description` | Renders the gift's description provided by the `product-gift-list` block. |\n\n2. Add the `product-gifts` block to your `store.product` template:\n\n```jsonc\n\"store.product\": {\n \"children\": [\n // (...)\n \"product-gifts\",\n ]\n}\n```\n\nWhen added to the `store.product` template but not declared with any children or prop, the Product Gifts block is rendered even so.\n\nFor the rendering, it uses the following block implementation behind the scenes:\n\n```json\n{\n \"product-gifts\": {\n \"props\": {\n \"maxVisibleItems\": {\n \"desktop\": 2,\n \"mobile\": 1\n }\n },\n \"children\": [\"flex-layout.row#product-gifts-text\", \"product-gift-list\"]\n },\n\n \"flex-layout.row#product-gifts-text\": {\n \"props\": {\n \"verticalAlign\": \"middle\",\n \"colSizing\": \"auto\",\n \"preserveLayoutOnMobile\": true\n },\n \"children\": [\n \"rich-text#product-gifts\",\n \"flex-layout.col#product-gifts-text\"\n ]\n },\n \"flex-layout.col#product-gifts-text\": {\n \"children\": [\"gift-text\"],\n \"props\": {\n \"verticalAlign\": \"middle\"\n }\n },\n \"rich-text#product-gifts\": {\n \"props\": {\n \"text\": \"**+ GIFT**\"\n }\n },\n \"gift-text\": {\n \"props\": {\n \"text\": \"{exceedingItems, plural, =0{ } one {+ # gift} other {+ # gifts}}\"\n }\n },\n \"product-gift-list\": {\n \"children\": [\"flex-layout.row#gift\"]\n },\n \"flex-layout.row#gift\": {\n \"props\": {\n \"fullWidth\": true\n },\n \"children\": [\"flex-layout.col#gift-name-description\", \"gift-image\"]\n },\n \"flex-layout.col#gift-name-description\": {\n \"props\": {\n \"verticalAlign\": \"middle\",\n \"rowGap\": 3\n },\n \"children\": [\"gift-name\", \"gift-description\"]\n }\n}\n```\n\n### Advanced configuration\n\nIf desired, you can change the Product Gifts default implementation by explicitly declaring the code showed above in your `store.product` template.\n\nAs a result, you will be able to configure the Product Gifts behavior by using all available props for each block:\n\n- **`product-gifts`**\n\n![product-gifts](https://user-images.githubusercontent.com/27777263/75771051-ee385b80-5d27-11ea-8600-5ea7f47ff64c.png)\n\n| Prop name | Type | Description | Default value |\n| ----------------- | --------------------------- | ------------------------------------------------------ | ------------- |\n| `maxVisibleItems` | `number` &#124; `\"showAll\"` | Maximum number of gifts that will be displayed at once | `\"showAll\"` |\n\n- **`gift-text`**\n\n![gift-text](https://user-images.githubusercontent.com/27777263/75767717-01e0c380-5d22-11ea-8054-4440438a5441.png)\n\n| Prop name | Type | Description | Default value |\n| --------- | -------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |\n| `text` | `String` | A translatable string (according to [ICU pattern](https://formatjs.io/guides/message-syntax/)) that has variables that might be used to render any desired text regarding the gifts. | `\"{exceedingItems, plural, =0{ } one {+ # gift} other {+ # gifts}}\"` |\n\nYou can configure the string received by the `text` prop using the following variables:\n\n| Variable name | Description |\n| ---------------- | ---------------------------------------------------------------------------------------------- |\n| `exceedingItems` | Number of items that were not rendered because of the `maxVisibleItems` prop of `product-gifts`. |\n| `totalGifts` | Total number of gifts available. |\n| `visibleItems` | Number of items that are being rendered. |\n\n- **`gift-name`**\n\n![gift-name](https://user-images.githubusercontent.com/27777263/75767722-03aa8700-5d22-11ea-8150-2cbe2a7bb37a.png)\n\n| Prop name | Type | Description | Default value |\n| ------------------- | --------- | ------------------------------------------------------------------------- | ------------- |\n| `linkToProductPage` | `Boolean` | Whether or not the `gift-name` block should be a link to the gift's product page. | `false` |\n| `nameType` | `enum` | Name type to be displayed alongside the gift. Possible values are: `productName` (displays the gift's product name) and `skuName` (displays the gift's SKU name). | `skuName` |\n\n- **`gift-image`** \n\n![gift-image](https://user-images.githubusercontent.com/27777263/75767721-02795a00-5d22-11ea-8f51-fe80664b7f68.png)\n\n| Prop name | Type | Description | Default value |\n| ------------ | ------------------------ | ----------------------------------------------- | ------------- |\n| `maxWidth` | `Number` &#124; `String` | Gift image maximum width. | `125` |\n| `maxHeight` | `Number` &#124; `String` | Gift image maximum height. | `125` |\n| `minWidth` | `Number` &#124; `String` | Gift image minimum width. | `125` |\n| `minHeight` | `Number` &#124; `String` | Gift image minimum height. | `125` |\n| `imageLabel` | `String` | The label of the image that should be rendered. | `undefined` |\n\n:information_source: *If no image label is defined, the* `gift-image` *block will use the first available image from the product's SKU.*\n\n## Customization\n\nIn order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).\n\nThereafter, you should add a single column table with the available CSS handles for that block:\n\n| CSS Handles |\n| ------------------------ |\n| giftDescription |\n| giftListItem |\n| giftNameLink |\n| giftNameText |\n| productGiftListContainer |\n| productGiftText |\n| productGiftsContainer |\n\n```" } ]
code_product-gifts_6c240f6e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/react/ProductGiftDescription.tsx from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { useGift } from './components/ProductGift'\n\nconst CSS_HANDLES = ['giftDescription'] as const\n\nconst ProductGiftDescription: FC = () => {\n const handles = useCssHandles(CSS_HANDLES)\n const gift = useGift()\n\n return (\n <span className={`${handles.giftDescription} t-small c-muted-1`}>\n {gift?.description}\n </span>\n )\n}\n\nexport default ProductGiftDescription\n\n```" } ]
code_product-gifts_aa1ad989
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/react/ProductGiftImage.tsx from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { defineMessages } from 'react-intl'\nimport { Image } from 'vtex.store-image'\n\nimport { useGift } from './components/ProductGift'\n\ninterface Props {\n maxWidth?: string | number\n maxHeight?: string | number\n minWidth?: string | number\n minHeight?: string | number\n imageLabel?: string\n}\n\nconst DEFAULT_IMAGE_DIMENSIONS = 125\n\nconst ProductGiftImage: StoreFunctionComponent<Props> = ({\n maxWidth = DEFAULT_IMAGE_DIMENSIONS,\n maxHeight = DEFAULT_IMAGE_DIMENSIONS,\n minWidth = DEFAULT_IMAGE_DIMENSIONS,\n minHeight = DEFAULT_IMAGE_DIMENSIONS,\n imageLabel,\n}) => {\n const gift = useGift()\n const productImage =\n gift.images.find(image => image.imageLabel === imageLabel) ?? gift.images[0]\n\n return (\n <Image\n maxWidth={maxWidth}\n maxHeight={maxHeight}\n minWidth={minWidth}\n minHeight={minHeight}\n src={productImage.imageUrl}\n alt={gift.productName}\n title={gift.skuName}\n />\n )\n}\n\nconst messages = defineMessages({\n title: {\n id: 'admin/editor.gift-image.title',\n defaultMessage: '',\n },\n description: {\n id: 'admin/editor.gift-image.description',\n defaultMessage: '',\n },\n imageLabel: {\n id: 'admin/editor.gift-image.imageLabel.title',\n defaultMessage: '',\n },\n imageLabelDescription: {\n id: 'admin/editor.gift-image.imageLabel.description',\n defaultMessage: '',\n },\n})\n\nProductGiftImage.schema = {\n title: messages.title.id,\n description: messages.description.id,\n type: 'object',\n properties: {\n imageLabel: {\n default: '',\n title: messages.imageLabel.id,\n description: messages.imageLabelDescription.id,\n type: 'string',\n },\n },\n}\n\nexport default ProductGiftImage\n\n```" } ]
code_product-gifts_f544fbf8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/react/ProductGiftList.tsx from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { useProductGiftsState } from './ProductGifts'\nimport ProductGift from './components/ProductGift'\n\nconst CSS_HANDLES = ['productGiftListContainer'] as const\n\nconst ProductGiftList: FC = ({ children }) => {\n const { gifts, maxVisibleItems } = useProductGiftsState()\n const handles = useCssHandles(CSS_HANDLES)\n const itemsToShow =\n maxVisibleItems === 'showAll' ? gifts.length : maxVisibleItems\n\n return (\n <div className={handles.productGiftListContainer}>\n {gifts.slice(0, itemsToShow).map((gift, idx) => (\n <ProductGift key={gift.skuName} giftIndex={idx}>\n {children}\n </ProductGift>\n ))}\n </div>\n )\n}\n\nexport default ProductGiftList\n\n```" } ]
code_product-gifts_98edfb28
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/react/GiftText.tsx from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo } from 'react'\nimport { defineMessages } from 'react-intl'\nimport { IOMessage } from 'vtex.native-types'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { useProductGiftsState } from './ProductGifts'\n\ninterface Props {\n text?: string\n}\n\nconst CSS_HANDLES = ['productGiftText'] as const\n\nconst GiftText: StoreFunctionComponent<Props> = ({ text }) => {\n const { gifts, maxVisibleItems } = useProductGiftsState()\n const handles = useCssHandles(CSS_HANDLES)\n const resolvedMaxVisibleItems =\n maxVisibleItems === 'showAll' ? gifts.length : maxVisibleItems\n\n const values = useMemo(\n () => ({\n totalGifts: gifts.length,\n exceedingItems:\n gifts.length - resolvedMaxVisibleItems > 0\n ? gifts.length - resolvedMaxVisibleItems\n : 0,\n visibleItems:\n resolvedMaxVisibleItems > gifts.length\n ? gifts.length\n : resolvedMaxVisibleItems,\n }),\n [gifts.length, resolvedMaxVisibleItems]\n )\n\n return (\n <span className={handles.productGiftText}>\n <IOMessage id={text} values={values} />\n </span>\n )\n}\n\n/**\n * These messages are used in contentSchema.json and need to be defined for the messages\n * builder to pick them up. If these are not here, CMS will render their IDs.\n */\nconst messages = defineMessages({\n title: {\n id: 'admin/editor.product-gift-text.title',\n defaultMessage: '',\n },\n description: {\n id: 'admin/editor.product-gift-text.description',\n defaultMessage: '',\n },\n text: {\n id: 'admin/editor.product-gift-text.text.title',\n defaultMessage: '',\n },\n textDescription: {\n id: 'admin/editor.product-gift-text.text.description',\n defaultMessage: '',\n },\n})\n\nGiftText.schema = {\n title: messages.title.id,\n description: messages.description.id,\n}\n\nexport default GiftText\n\n```" } ]
code_product-gifts_02081eda
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/react/package.json from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"lint\": \"tsc --noEmit && eslint --quiet --fix --ext ts,tsx .\",\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.8.6\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.8.6\",\n \"react-intl\": \"^3.11.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^24.9.0\",\n \"@types/node\": \"^13.1.8\",\n \"@types/react\": \"^16.9.19\",\n \"@vtex/test-tools\": \"^3.0.1\",\n \"@vtex/tsconfig\": \"^0.2.0\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.5.8\",\n \"prettier\": \"^1.18.2\",\n \"typescript\": \"3.9.7\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.flex-layout\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.flex-layout@0.17.0/public/@types/vtex.flex-layout\",\n \"vtex.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.9/public/@types/vtex.product-context\",\n \"vtex.product-gifts\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-gifts@0.2.1/public/@types/vtex.product-gifts\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.128.4/public/@types/vtex.render-runtime\",\n \"vtex.responsive-values\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.responsive-values@0.4.2/public/@types/vtex.responsive-values\",\n \"vtex.rich-text\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.rich-text@0.14.0/public/@types/vtex.rich-text\",\n \"vtex.search-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-graphql@0.43.0/public/@types/vtex.search-graphql\",\n \"vtex.store-image\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-image@0.11.0/public/@types/vtex.store-image\",\n \"waait\": \"^1.0.5\"\n },\n \"version\": \"0.4.0\"\n}\n\n```" } ]
code_product-gifts_cb6b4a83
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/react/ProductGifts.tsx from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { createContext, useContext, useMemo } from 'react'\nimport { defineMessages } from 'react-intl'\nimport { useQuery } from 'react-apollo'\nimport {\n useResponsiveValue,\n MaybeResponsiveInput,\n} from 'vtex.responsive-values'\nimport { useCssHandles } from 'vtex.css-handles'\nimport useProduct from 'vtex.product-context/useProduct'\n\nimport ProductGiftsQuery from './graphql/product.graphql'\n\ninterface Props {\n maxVisibleItems?: MaybeResponsiveInput<number | 'showAll'>\n}\n\ninterface State {\n gifts: Gift[]\n maxVisibleItems: number | 'showAll'\n}\n\nconst GiftsStateContext = createContext<State>({\n gifts: [],\n maxVisibleItems: 0,\n})\n\nconst CSS_HANDLES = ['productGiftsContainer'] as const\n\nconst ProductGifts: StoreFunctionComponent<Props> = ({\n children,\n maxVisibleItems = 'showAll',\n}) => {\n const productContext: Maybe<ProductContextState> = useProduct()\n const { data, loading, error } = useQuery<ProductGiftsQueryResponse>(\n ProductGiftsQuery,\n {\n variables: {\n identifier: { field: 'id', value: productContext?.product?.productId },\n },\n skip: productContext?.product?.productId == null,\n }\n )\n const selectedItemId = productContext?.selectedItem?.itemId\n const handles = useCssHandles(CSS_HANDLES)\n const staticMaxVisibleItems = useResponsiveValue<number | 'showAll'>(\n maxVisibleItems\n )\n\n const selectedItemFromProductQuery = data?.product.items.find(\n item => item.itemId === selectedItemId\n )\n const sellers = selectedItemFromProductQuery?.sellers ?? []\n\n const gifts = sellers.reduce(\n (acc: Gift[], curr) => acc.concat(curr.commertialOffer.gifts ?? []),\n []\n )\n\n const state = useMemo(\n () => ({ gifts, maxVisibleItems: staticMaxVisibleItems }),\n [gifts, staticMaxVisibleItems]\n )\n\n if (!productContext) {\n console.error(\n 'Could not find a ProductContext value. Make sure this component is being used inside a ProductContextProvider.'\n )\n }\n\n if (error) {\n console.error(error)\n }\n\n if (loading || state.gifts.length === 0) {\n return null\n }\n\n return (\n <GiftsStateContext.Provider value={state}>\n <div className={handles.productGiftsContainer}>{children}</div>\n </GiftsStateContext.Provider>\n )\n}\n\nconst messages = defineMessages({\n title: {\n id: 'admin/editor.product-gifts.title',\n defaultMessage: '',\n },\n description: {\n id: 'admin/editor.product-gifts.description',\n defaultMessage: '',\n },\n maxVisibleItems: {\n id: 'admin/editor.product-gifts.maxVisibleItems.title',\n defaultMessage: '',\n },\n maxVisibleItemsDescription: {\n id: 'admin/editor.product-gifts.maxVisibleItems.description',\n defaultMessage: '',\n },\n})\n\nProductGifts.schema = {\n title: messages.title.id,\n description: messages.description.id,\n type: 'object',\n properties: {\n maxVisibleItems: {\n default: 'showAll',\n title: messages.maxVisibleItems.id,\n description: messages.maxVisibleItemsDescription.id,\n type: 'string',\n },\n },\n}\n\nexport function useProductGiftsState() {\n const context = useContext(GiftsStateContext)\n if (context === undefined) {\n throw new Error(\n 'useProductGiftsState must be used within a ProductGiftsContextProvider'\n )\n }\n return context\n}\n\nexport default ProductGifts\n\n```" } ]
code_product-gifts_cd739c12
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/react/ProductGiftName.tsx from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { defineMessages } from 'react-intl'\nimport { Link } from 'vtex.render-runtime'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { useGift } from './components/ProductGift'\n\ninterface Props {\n linkToProductPage: boolean\n nameType: 'skuName' | 'productName'\n}\n\nconst CSS_HANDLES = ['giftNameLink', 'giftNameText'] as const\n\nconst ProductGiftName: StoreFunctionComponent<Props> = ({\n linkToProductPage = false,\n nameType = 'skuName',\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n const gift = useGift()\n\n return linkToProductPage ? (\n // No need for this rule since <Link> already creates an anchor\n // with href attribute.\n // eslint-disable-next-line jsx-a11y/anchor-is-valid\n <Link\n className={`${handles.giftNameLink} c-on-base link`}\n to={`/${gift.linkText}/p`}\n >\n <span className={`${handles.giftNameText}`}>\n {nameType === 'skuName' ? gift.skuName : gift.productName}\n </span>\n </Link>\n ) : (\n <span className={`${handles.giftNameText} c-on-base`}>\n {nameType === 'skuName' ? gift.skuName : gift.productName}\n </span>\n )\n}\n\nconst messages = defineMessages({\n title: {\n id: 'admin/editor.gift-name.title',\n defaultMessage: '',\n },\n description: {\n id: 'admin/editor.gift-name.description',\n defaultMessage: '',\n },\n linkToProduct: {\n id: 'admin/editor.gift-name.linkToProduct.title',\n defaultMessage: '',\n },\n linkToProductDescription: {\n id: 'admin/editor.gift-name.linkToProduct.description',\n defaultMessage: '',\n },\n nameType: {\n id: 'admin/editor.gift-name.nameType.title',\n defaultMessage: '',\n },\n nameTypeDescription: {\n id: 'admin/editor.gift-name.nameType.description',\n defaultMessage: '',\n },\n})\n\nProductGiftName.schema = {\n title: messages.title.id,\n description: messages.description.id,\n type: 'object',\n properties: {\n linkToProduct: {\n default: false,\n title: messages.linkToProduct.id,\n description: messages.linkToProductDescription.id,\n type: 'boolean',\n },\n nameType: {\n title: messages.nameType.id,\n description: messages.nameType.id,\n type: 'string',\n enum: [\n 'skuName',\n 'productName'\n ],\n enumNames: [\n 'skuName',\n 'productName'\n ],\n default: 'skuName'\n },\n },\n}\n\nexport default ProductGiftName\n\n```" } ]
code_product-gifts_18bc8923
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/store/contentSchemas.json from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"definitions\": {\n \"GiftText\": {\n \"type\": \"object\",\n \"properties\": {\n \"text\": {\n \"$ref\": \"app:vtex.native-types#/definitions/text\",\n \"title\": \"admin/editor.product-gift-text.text.title\",\n \"description\": \"admin/editor.product-gift-text.text.description\"\n }\n }\n }\n }\n}\n\n```" } ]
code_product-gifts_0781f3c6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/store/blocks.jsonc from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"product-gifts\": {\n \"props\": {\n \"maxVisibleItems\": {\n \"desktop\": 2,\n \"mobile\": 1\n }\n },\n \"children\": [\"flex-layout.row#product-gifts-text\", \"product-gift-list\"]\n },\n\n \"flex-layout.row#product-gifts-text\": {\n \"props\": {\n \"verticalAlign\": \"middle\",\n \"colSizing\": \"auto\",\n \"preserveLayoutOnMobile\": true\n },\n \"children\": [\n \"rich-text#product-gifts\",\n \"flex-layout.col#product-gifts-text\"\n ]\n },\n \"flex-layout.col#product-gifts-text\": {\n \"children\": [\"gift-text\"],\n \"props\": {\n \"verticalAlign\": \"middle\"\n }\n },\n \"rich-text#product-gifts\": {\n \"props\": {\n \"text\": \"**+ GIFT**\"\n }\n },\n \"gift-text\": {\n \"props\": {\n \"text\": \"{exceedingItems, plural, =0{ } one {+ # gift} other {+ # gifts}}\"\n }\n },\n \"product-gift-list\": {\n \"children\": [\"flex-layout.row#gift\"]\n },\n \"flex-layout.row#gift\": {\n \"props\": {\n \"fullWidth\": true\n },\n \"children\": [\"flex-layout.col#gift-name-description\", \"gift-image\"]\n },\n \"flex-layout.col#gift-name-description\": {\n \"props\": {\n \"verticalAlign\": \"middle\",\n \"rowGap\": 3\n },\n \"children\": [\"gift-name\", \"gift-description\"]\n }\n}\n\n```" } ]
code_product-gifts_fb8dde13
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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-gifts/store/interfaces.json from the product-gifts VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"product-gifts\": {\n \"component\": \"ProductGifts\",\n \"render\": \"client\",\n \"composition\": \"children\"\n },\n \"product-gift-list\": {\n \"component\": \"ProductGiftList\",\n \"composition\": \"children\"\n },\n \"gift-name\": {\n \"component\": \"ProductGiftName\"\n },\n \"gift-image\": {\n \"component\": \"ProductGiftImage\"\n },\n \"gift-text\": {\n \"component\": \"GiftText\",\n \"content\": {\n \"$ref\": \"#/definitions/GiftText\"\n }\n },\n \"gift-description\": {\n \"component\": \"ProductGiftDescription\"\n }\n}\n\n```" } ]