[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/checkout-ui-custom/src/_scss/_components/_RTL.scss from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```scss
.RTL-checkout {

  select {
    direction: rtl;
  }

	.cart-template-holder {
			order: 2;
	}

	body .main-header .header-link {
			left: initial;
			right: 0;
	}

	body .main-header .checkout-steps {
			margin-left: initial;
			margin-right: auto;
	}

	.main-header .logo {
			order: 2;
	}

	.summary-template-holder tr {
		.info {
			order:2;
			text-align: right !important;
		}
	}

	.orderform-template-holder #client-profile-data form.client-pre-email .link-box-edit,
	.orderform-template-holder #client-profile-data .step.client-profile-data .link-box-edit,
	.orderform-template-holder #shipping-data .link-box-edit,
	.orderform-template-holder #payment-data .link-box-edit {
    right: initial;
    left: 0;
	}

	.summary-template-holder tbody td.monetary,
	.summary-template-holder tfoot tr td.monetary {
			margin-right: auto;
			margin-left: initial !important;
			text-align: left !important;
	}

	.summary-template-holder {
		.summary-coupon p.coupon-fields span {
			flex-direction: row-reverse;
			input {
				margin: 0 0 0 10px;
			}
		}
	}

	.table.cart-items tbody tr .v-custom-product-item-wrap,
	.table.cart-items tbody tr,
	.table.cart-items thead tr,
	.table.cart-items thead tr th.product{
			flex-direction: row-reverse;
			text-align:right;
	}

	.table.cart-items tbody tr td.product-name {
			text-align: right;
	}

	.orderform-template .orderform-template-holder {
			order: 2;
			padding: 0 0 0 20px;
	}

	.orderform-template .cart-template.mini-cart .summary-totalizers tfoot tr td.monetary {
			text-align: left !important;
	}

	br {
		width: 100%;
		height: 1px;
		content: " " !important;
		display: block !important;
		clear:both;
	}

  .table.cart-items td.quantity {
    direction: rtl;
  }

  .checkout-steps_items {
      direction: rtl;
      .text:before {
        margin: 0 0 0 7px;
      }
  }

  .srp-toggle__wrapper {
    direction: rtl;
    .vtex-shipping-preview-0-x-framePickup {
      left: 0;
    }
    .vtex-shipping-preview-0-x-frameDelivery {
        left: 50%;
    }
  }

  .srp-delivery-header.mb3 {
      direction: rtl;
      display: flex;
  }

  .srp-delivery-current-many .flex {direction: rtl;text-align: right;}

	//profile

	.step {
		direction: rtl;
	}

	.step .accordion-toggle > span:before,
	.step .accordion-toggle:before {
		margin-right: 0 !important;
		margin-left: 10px !important;
	}

	fieldset.box-client-info-pf {
		display: flex;
		flex-wrap: wrap;
	}

	.orderform-template-holder .step .form-step fieldset p, .orderform-template-holder .step .form-step fieldset div {
		width: 100%;
	}

	p.client-first-name, p.client-different-document, p.client-document, p.client-company-ie, p.client-company-postal-code, p.client-document-type, p.payment-card-due-date {
		margin-left: 10px;
		margin-right: 0;
	}

	p.client-document, p.client-phone, p.client-company-document, p.client-company-ie, p.client-company-postal-code, p.client-company-phone, p.payment-card-due-month, p.payment-card-lash, p.payment-card-due-year {
		float: right;
	}

	input.success:not([invalid="true"]) {
		background-position: left top;
	}

	.vtexIdUI .vtexIdUI-page {
    direction: rtl;
	}

	.vtexIdUI .modal-header .close {
			left: -1px;
			right: initial;
	}

	.vtexIdUI .pull-left {
			float: right;
	}

	.orderform-template-holder .step .box-info p {
			display: flex;
			flex-wrap: wrap;
			width: 100%;
	}

	//shipping

	.vtex-omnishipping-1-x-leanShippingIcon.shp-option-icon,
	.vtex-omnishipping-1-x-addressItemIcon {
			margin: 0 0 0 10px;
	}

	.vtex-omnishipping-1-x-leanShippingText {
			padding-right: 10px;
	}

	.address-summary {
		/* direction: unset; */
		display: flex;
		flex-wrap: wrap;
	}

	br.line1-delimiter {
			width: 100%;
			height: 1px;
			content: " " !important;
			display: block !important;
			clear:both;
	}

	//payment

	.orderform-template-holder #payment-data .v-custom-payment-item-wrap .payment-group-item#payment-group-AffirmPaymentGroup:after,
	.orderform-template-holder #payment-data .v-custom-payment-item-wrap .payment-group-item#payment-group-payPalPaymentGroup:after {
			right: initial;
			left: 10px;
	}

	.orderform-template-holder #payment-data .v-custom-payment-item-wrap .payment-group-item-text {margin-left: auto;margin-right: inherit;}

	.orderform-template-holder #payment-data .v-custom-payment-item-wrap .payment-group-item-text:before {
			margin-right: initial;
			margin-left: 10px;
	}

	.orderform-template-holder #payment-data p.link.link-gift-card a {
    text-align: right;
	}

	//summary

	.orderform-template .custom-cart-template-wrap .summary-cart-template-holder {
    direction: rtl;
	}

	.pull-right {
			float: left !important;
	}

	.orderform-template .cart-template.mini-cart .item .price {
			margin-right:auto;
			direction: initial;
	}

	.orderform-template .cart-template.mini-cart .item .url {
			float: right;
			margin: 0 0 0 6px;
	}

	.orderform-template .cart-template.mini-cart .item .fn {
			text-align: right;
			float: right;
	}

	.orderform-template .cart-template.mini-cart h2 {
			text-align: right;
	}

	.orderform-template .cart-template.mini-cart #go-to-cart-button {
			left: 7px;
			right: initial;
	}

	.vtex-omnishipping-1-x-SummaryItemInfo {
			border: none;
			border-left: 1px solid #eee;
			padding: 0 0 0 6px;
	}

	// login modal

	.vtexIdUI {
		.vtexIdUI-page {
			direction: rtl;
		}

		.modal-header .close {
				left: -1px;
				right: initial;
		}
		.pull-left {
				float: right;
		}
	}

	//payment

	#app-container {
    direction: rtl;

		.PaymentCardDueDate.clearfix {
			display: flex;
		}

		label.FormFieldLabel {
				margin: 0 0 0 10px;
		}

		.PaymentCardCVV {
				display: flex;
		}

		p.AddressToggle {
				display: flex;
		}

		.AddressToggle input {
				margin: 3px 0 0 5px;
		}
	}

	@media (max-width: 998px) {
    &.body-cart-vertical {
      .summary-template-holder {
        order: 2;
      }
    }
	}

  @media (max-width: 768px) {
    .orderform-template .cart-template.mini-cart {
      order: 2;
    }
  }

  @media (max-width: 690px) {

    .table.cart-items td.product-image a {
      margin-right: 0;
      margin-left: 20px;
    }
    .full-cart .cart table tbody tr td.product-image,
    .full-cart .cart table tbody tr td.bundle-item-image {
      left:initial;
      right:0;
    }

    .table.cart-items td.product-name,
    .table.cart-items td.quantity {
      margin-left:0 !important;
      margin-right:90px !important;
    }

    .table.cart-items td.quantity {
      float: right;
    }

    .full-cart .cart table tbody tr td.product-name a,
    .full-cart .cart table tbody tr td.bundle-item-name span {
      padding: 0 0 0 20px;
    }

    .full-cart .cart table tbody tr td.product-price {
      float: left;
    }

    .full-cart .cart table tbody tr td.item-remove {
      left: 0;
      right: initial;
    }
  }
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/checkout-ui-custom/src/_scss/_components/_header.scss from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```scss
// _global.scss

body {
  .main-header {
    padding:12px 0;
    text-align: center;
    border-bottom: 1px solid $muted4;
    position:relative;
    background-color: #FFF;
    margin-bottom:40px;

    &, > .container {
      display:flex;
      align-items: center;
      @media (max-width:$mobileWidth) {
        justify-content: center;
      }
    }
    > .container {
      &:before,
      &:after {display: none;}
    }

    .header-link {
      position:absolute;
      left:0px;
      top: calc(100% + 18px);
      display: none;
      a {
        height:20px;
        font-size:11px;
        line-height: 115%;
        padding-left:0px;
        color:$muted2;
        display: flex;
        align-items: center;

        &:before {
          display:block;
          float:left;
          width:10px;
          height: 10px;

          -webkit-mask:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE5LjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPg0KPHN2ZyB2ZXJzaW9uPSIxLjEiIGlkPSJDYXBhXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB2aWV3Qm94PSIwIDAgNDQzLjUyIDQ0My41MiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNDQzLjUyIDQ0My41MjsiIHhtbDpzcGFjZT0icHJlc2VydmUiPg0KPGc+DQoJPGc+DQoJCTxwYXRoIGQ9Ik0xNDMuNDkyLDIyMS44NjNMMzM2LjIyNiwyOS4xMjljNi42NjMtNi42NjQsNi42NjMtMTcuNDY4LDAtMjQuMTMyYy02LjY2NS02LjY2Mi0xNy40NjgtNi42NjItMjQuMTMyLDBsLTIwNC44LDIwNC44DQoJCQljLTYuNjYyLDYuNjY0LTYuNjYyLDE3LjQ2OCwwLDI0LjEzMmwyMDQuOCwyMDQuOGM2Ljc4LDYuNTQ4LDE3LjU4NCw2LjM2LDI0LjEzMi0wLjQyYzYuMzg3LTYuNjE0LDYuMzg3LTE3LjA5OSwwLTIzLjcxMg0KCQkJTDE0My40OTIsMjIxLjg2M3oiLz4NCgk8L2c+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8L3N2Zz4NCg==) no-repeat 50% 50%;
          mask:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE5LjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPg0KPHN2ZyB2ZXJzaW9uPSIxLjEiIGlkPSJDYXBhXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB2aWV3Qm94PSIwIDAgNDQzLjUyIDQ0My41MiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNDQzLjUyIDQ0My41MjsiIHhtbDpzcGFjZT0icHJlc2VydmUiPg0KPGc+DQoJPGc+DQoJCTxwYXRoIGQ9Ik0xNDMuNDkyLDIyMS44NjNMMzM2LjIyNiwyOS4xMjljNi42NjMtNi42NjQsNi42NjMtMTcuNDY4LDAtMjQuMTMyYy02LjY2NS02LjY2Mi0xNy40NjgtNi42NjItMjQuMTMyLDBsLTIwNC44LDIwNC44DQoJCQljLTYuNjYyLDYuNjY0LTYuNjYyLDE3LjQ2OCwwLDI0LjEzMmwyMDQuOCwyMDQuOGM2Ljc4LDYuNTQ4LDE3LjU4NCw2LjM2LDI0LjEzMi0wLjQyYzYuMzg3LTYuNjE0LDYuMzg3LTE3LjA5OSwwLTIzLjcxMg0KCQkJTDE0My40OTIsMjIxLjg2M3oiLz4NCgk8L2c+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8L3N2Zz4NCg==) no-repeat 50% 50%;
          -webkit-mask-size: cover;
          mask-size: cover;
          background-color: $muted2;
          content:"";
        }

        &.back-cart-link {display:none;}
      }
      @media (max-width:$mobileWidth) {
        top:50%;
        transform: translateY(-50%);
        a {
          max-width: 80px;
          &:before {
            width: 17px;
            height: 17px;
          }
        }
      }
    }

    .logo {
      max-width: calc(100% - 180px);

      svg.vtex-logo {
        height:50px;
      }
    }
    .logo,
    .logo img {
      display: inline-block;
      font-size:24px;
      border:none;
      line-height: 39px;

    }

    .checkout-steps {
      max-width: 540px;
      margin-left: auto;
      padding-right: 10px;
    }

  }

  &:not(.body-cart) {
    .main-header {
      @media (max-width: $mobileWidth) {
        padding:4px 0;
        margin-bottom: 10px;

        .v-custom-mhide {display: none !important;}

        &, > .container {
          background:none;
          border:none;
          justify-content: center;
        }

        .logo {

          cursor: default;
          pointer-events: none;
          font-weight: bold;

          svg,
          img {display: none !important;}
          &:before {
            content:"checkout";
            text-transform: uppercase;
          }

          &, &:hover {
            color:$muted1;
            font-size: 14px;
          }
        }

        .header-link {display: block;}
        a.buy-more-link {display:none;}
        a.back-cart-link {
          display:block !important;
          font-size: 0;
          &:before {
            background: $muted1;
          }
        }
      }
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/checkout-ui-custom/src/_scss/_components/_card-flags.scss from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```scss
.payment-group-item-cards {
  .card-flag {
    width: 32px !important;
    background-size: auto 20px;
    min-width: auto;
    height: 20px;
  }

  .card-flag.Visa {
    background-position: 0 0;
  }
  .card-flag.Mastercard {
    background-position: -32px 0;
  }
  .card-flag.Diners {
    background-position: -64px 0;
  }
  .card-flag.Amex,
  .card-flag.American {
    background-position: -96px 0;
  }
  .card-flag.Hipercard {
    background-position: -128px 0;
  }
  .card-flag.Discover {
    background-position: -160px 0;
  }
  .card-flag.Aura {
    background-position: -192px 0;
  }
  .card-flag.Banricompras {
    background-position: -224px 0;
  }
  .card-flag.Elo {
    background-position: -256px 0;
  }
  .card-flag.JCB {
    background-position: -288px 0;
  }
  .card-flag.Cabal {
    background-position: -320px 0;
  }
  .card-flag.Maestro {
    background-position: -352px 0;
  }
  .card-flag.Credz {
    background-position: -384px 0;
  }
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/public/metadata/messages/es-AR.json from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "Personalizador del Checkout",
  "headline": "Una forma sencilla de personalizar el checkout de su tienda por el administrador.",
  "overview": "El app Checkout UI Custom es responsable por personalizar el Checkout de su tienda por la interfaz de administrador. Con algunos campos es posible cambiar la fuente y los colores, cambiar la visualización de los medios de pago y la apariencia de la fecha de entrega, y aún ofrecer posibilidades de personalización si es necesario. Toda la interfaz de usuario se diseñó primero en mobile-first.",
  "features": [
    "Cambio de exposición de métodos de pago",
    "Fecha de envío simplificada",
    "Mostrar precio unitario del producto",
    "Mostrar campo 'notas'",
    "Cambiar estilos de texto",
    "Cambiar estilos de blocks",
    "Cambiar colores",
    "Área CSS avanzada",
    "Área avanzada de JavaScript",
    "Histórico de cambios"
  ],
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/public/metadata/messages/pt-BR.json from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "Customizador do Checkout",
  "headline": "Personalize a interface do checkout da sua loja com facilidade pelo admin.",
  "overview": "O aplicativo Checkout UI Custom é responsável por personalizar a UI do Checkout de sua loja por meio da interface do administrador. Com alguns campos é possível mudar a fonte e cores, alterar a exibição dos meios de pagamentos e a aparência da data de entrega, e ainda fornece possibilidades para customizações se necessário. Toda a UI foi pensada em mobile-first, para facilitar o ato da compra.",
  "features": [
    "Alteração na exibição de métodos de pagamento",
    "Data de envio simplificada",
    "Mostrar preço unitário do item",
    "Mostrar campo 'notas'",
    "Alterar estilos de texto",
    "Alterar estilos de blocos",
    "Paleta de cores",
    "Área CSS avançada",
    "Área de Javascript avançado",
    "Histórico de alterações"
  ],
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/public/metadata/messages/en-US.json from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "Checkout Customizer",
  "headline": "Easily customize your store's checkout interface by the admin.",
  "overview": "The Checkout UI Custom app is responsible for customizing your store's Checkout UI through the admin's interface. With some fields its possible to change the font and colors, change the display of the means of payment and the appearance of the delivery date, and still provide possibilities for customizations if necessary. The entire UI was designed in mobile-first, to facilitate the purchase flow.",
  "features": [
    "Change payment methods exhibition",
    "Simplified shipping date",
    "Show item's unit price",
    "Show 'notes' field",
    "Change Text styles",
    "Change blocks styles",
    "Change colors",
    "Advanced CSS area",
    "Advanced Javascript area",
    "Changes tracking"
  ],
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/node/clients/server-settings.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { InstanceOptions, IOContext } from '@vtex/api'
import { AppClient } from '@vtex/api'

export class SaveVB extends AppClient {
  constructor(ctx: IOContext, options?: InstanceOptions) {
    super(`vtex.checkout-ui-settings-server@0.x`, ctx, options)
  }

  public saveVB = async (data: any) => {
    await this.http
      .post('/_v/checkout-ui-custom/savevb', data, {
        headers: { 'content-type': 'application/json' },
      })
      .catch(err => {
        throw new Error(err)
      })
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/node/clients/LMClient.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { InstanceOptions, IOContext } from '@vtex/api'
import { ExternalClient } from '@vtex/api'

export default class LMClient extends ExternalClient {
  constructor(ctx: IOContext, options?: InstanceOptions) {
    super(`http://${ctx.account}.vtexcommercestable.com.br/`, ctx, {
      ...options,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        VtexIdclientAutCookie: ctx.authToken,
      },
    })
  }

  public getUserAdminPermissions = async (account: string, userId: string) => {
    return this.get(
      `/api/license-manager/pvt/accounts/${encodeURI(
        account
      )}/logins/${encodeURI(userId)}/granted`
    ).then((res: any) => {
      return res
    })
  }

  public getUserRolePermissions = async (account: string,userId: string) => {
    return this.get(
      `/api/license-manager/pvt/users/${encodeURI(userId)}/resources?an=${account}`
    ).then((res: any) => {
      return res
    })
  }

  public getAccount = async () => {
    return this.get<GetAccountResponse>(`/api/license-manager/account`).then(
      (res) => {
        return res
      }
    )
  }

  protected get = <T>(url: string) => {
    return this.http.get<T>(url)
  }
}

interface GetAccountResponse {
  isActive: boolean
  id: string
  name: string
  accountName: string
  lv: unknown
  isOperating: boolean
  defaultUrl: unknown
  district: unknown
  country: unknown
  complement: unknown
  compunknownName: string
  cnpj: string
  haveParentAccount: boolean
  parentAccountId: unknown
  parentAccountName: unknown
  city: unknown
  address: unknown
  logo: unknown
  hasLogo: boolean
  number: unknown
  postalCode: unknown
  state: unknown
  telephone: string
  tradingName: string
  licenses: unknown[]
  sponsor: {
    name: string
    email: string
    phone: string
  }
  contact: {
    name: string
    email: string
    phone: string
  }
  operationDate: unknown
  inactivationDate: unknown
  creationDate: string
  hosts: unknown[]
  sites: unknown[]
  appKeys: unknown[]
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/node/clients/index.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { IOClients } from '@vtex/api'

import { SaveVB } from './server-settings'
import LMClient from './LMClient'
import IdentityClient from './IdentityClient'

// Extend the default IOClients implementation with our own custom clients.
export class Clients extends IOClients {

  public get lm() {
    return this.getOrSet('lm', LMClient)
  }
  public get identity() {
    return this.getOrSet('identity', IdentityClient)
  }
  public get server() {
    return this.getOrSet('server', SaveVB)
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/node/clients/IdentityClient.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { InstanceOptions, IOContext } from '@vtex/api'
import { JanusClient } from '@vtex/api'

export default class IdentityClient extends JanusClient {
  constructor(ctx: IOContext, options?: InstanceOptions) {
    super(ctx, {
      ...options,
      headers: {
        ...options?.headers,
      },
    })
  }

  public async validateToken({ token }: { token: string }): Promise<any> {
    return this.http.post('/api/vtexid/credential/validate', { token })
  }

  public async getToken({
    appkey,
    apptoken,
  }: {
    appkey: string
    apptoken: string
  }): Promise<any> {
    return this.http.post('/api/vtexid/apptoken/login', { appkey, apptoken })
  }
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/node/middlewares/holidays.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable no-console */

import axios from 'axios'

export async function holidays(ctx: Context) {
  const {
    clients: {},
    vtex: { authToken },
  } = ctx

  const account = ctx.headers['x-vtex-account']

  // const { consultantId } = await json(req)

  const holidaysUrl = `http://${account}.vtexcommercestable.com.br/api/logistics/pvt/configuration/holidays`

  const { data: _holidays } = await axios.get(holidaysUrl, {
    headers: {
      'VtexIdclientAutCookie': authToken,
      'X-Vtex-Use-Https': 'true'
    },
  })

  ctx.set('Content-Type', 'application/json')
  ctx.set('Cache-Control', 'no-cache, no-store')

  let result = _holidays;
  if(!holidays) result = "no holidays"

  ctx.response.status = 200
  ctx.response.body = result
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/node/middlewares/getCountryRules.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { AddressRules } from '@vtex/address-form'

interface PromiseType {
  success: boolean
  errorMessage: string
  data: typeof AddressRules | undefined
}

export async function getCountryRules(
  ctx: Context,
  next: () => Promise<PromiseType>
) {
  const {
    vtex: { logger },
  } = ctx

  const { countryCode } = ctx.vtex.route.params

  if (!countryCode) {
    throw new Error(`Error getting request`)
  }

  const parsedCountryCode =
    countryCode !== 'default'
      ? (countryCode as string).toUpperCase()
      : countryCode

  try {
    const { default: rules } = await import(
      `@vtex/address-form/lib/country/${parsedCountryCode}`
    )

    ctx.status = 200
    ctx.set('Cache-Control', 'no-cache')
    ctx.body = {
      success: true,
      errorMessage: '',
      data: rules,
    }
  } catch (error) {
    ctx.status = 404
    ctx.set('Cache-Control', 'no-cache')
    ctx.body = {
      success: false,
      errorMessage: 'Country not found',
      data: {},
    }

    logger.error({
      message: 'getCountryRules-error',
      error,
    })
  }

  return next()
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/node/graphql/helper.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const validateAdminToken = async (
    context: Context,
    adminUserAuthToken: string
  ): Promise<{
    hasAdminToken: boolean
    hasValidAdminToken: boolean
    hasCurrentValidAdminToken: boolean
    hasValidAdminRole: any
  }> => {
    const {
      clients: { identity, lm },
      vtex: { account, logger },
    } = context

    // check if has admin token and if it is valid
    const hasAdminToken = !!adminUserAuthToken
    let hasValidAdminToken = false
    let hasValidAdminRole = false
    let userRoles = []
    // this is used to check if the token is valid by current standards
    let hasCurrentValidAdminToken = false

    if (hasAdminToken) {

      try {

        const authUser = await identity.validateToken({
            token: adminUserAuthToken,
        })
        // we set this flag to true if the token is valid by current standards
        // in the future we should remove this line
        hasCurrentValidAdminToken = true

        if (authUser?.audience === 'admin' && authUser?.account === account) {
          hasValidAdminToken = await lm.getUserAdminPermissions(
            account,
            authUser.id
          )

          userRoles = await lm.getUserRolePermissions(
            account,
            authUser.id
          )

          hasValidAdminRole = userRoles.filter( (role : any) => role.resourceKey == "SaveOrderFormConfiguration").length ? true : false;

        }
      } catch (err) {
        // noop so we leave hasValidAdminToken as false
        logger.warn({
          message: 'Error validating admin token',
          err,
        })
      }
    }

    return { hasAdminToken, hasValidAdminToken, hasCurrentValidAdminToken, hasValidAdminRole }
  }
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/node/graphql/authcheck.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { ForbiddenError } from '@vtex/api'
import { validateAdminToken } from './helper'

export const authCheck = async (ctx: Context, app: string) => {
  const {
    vtex: { logger },
  } = ctx

    const version = app.split(`@`)[1]

    const cookie = ctx.headers?.cookie

    const vtexCredentials: any = cookie
      ? cookie
          .split('; ')
          .find((cookie: string) => cookie.startsWith('VtexIdclientAutCookie='))
          ?.split('=')[1] ?? ''
      : '';

    if (version <= `0.18.9`) {
      logger.warn({
        message: 'Error: Invalid version',
      })
      throw new ForbiddenError('Unauthorized version')
    }

    if (!vtexCredentials.trim()) {
      logger.warn({
        message: 'CheckAdminAccess: Invalid token',
      })
      throw new ForbiddenError('Unauthorized Access')
    }

    if (vtexCredentials) {
      const permission = await validateAdminToken(ctx, vtexCredentials)

      if (
        !permission.hasAdminToken ||
        !permission.hasValidAdminToken ||
        !permission.hasCurrentValidAdminToken ||
        !permission.hasValidAdminRole
      ) {
        logger.warn({
          message: 'CheckAdminAccess: Invalid store token',
        })
        throw new ForbiddenError('Unauthorized Access Token')
      }
    }

}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/node/graphql/index.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable @typescript-eslint/no-explicit-any */
import { promises as fs } from 'fs'
import * as path from 'path'

import { method } from '@vtex/api'

import { getCountryRules } from '../middlewares/getCountryRules'
import { holidays } from '../middlewares/holidays'

import { authCheck } from './authcheck'
import { validateAdminToken } from './helper'

const SCHEMA_VERSION = 'v0.1.3'
const DATA_ENTITY = 'checkoutcustom'

const routes = {
  getProfile: () =>
    `http://${process.env.VTEX_ACCOUNT}.vtexcommercestable.com.br/no-cache/profileSystem/getProfile`,
  baseUrl: () =>
    `http://${process.env.VTEX_ACCOUNT}.vtexcommercestable.com.br/api`,
  configEntity: () => `${routes.baseUrl()}/dataentities/${DATA_ENTITY}`,
  listConfig: () =>
    `${routes.configEntity()}/search?_schema=${SCHEMA_VERSION}&_fields=id,email,workspace,creationDate,appVersion&_sort=creationDate DESC`,
  getConfig: (id: string) =>
    `${routes.configEntity()}/documents/${id}?_fields=id,email,cartName,items,creationDate,subtotal,discounts,shipping,total,customData,address`,
  saveSchema: () => `${routes.configEntity()}/schemas/${SCHEMA_VERSION}`,
}

const getAppId = (): string => {
  return process.env.VTEX_APP_ID ?? ''
}

const schema = {
  properties: {
    email: {
      type: 'string',
      title: 'Email',
    },
    workspace: {
      type: 'string',
      title: 'Workspace',
    },
    creationDate: {
      type: 'string',
      title: 'Creation Date',
    },
    appVersion: {
      type: 'string',
      title: 'App Version',
    },
    layout: {
      type: ['null', 'object'],
      title: 'Layout',
    },
    colors: {
      type: ['null', 'object'],
      title: 'Colors',
    },
    javascript: {
      type: ['null', 'string'],
      title: 'Custom Javascript',
    },
    css: {
      type: ['null', 'string'],
      title: 'Custom CSS',
    },
    javascriptActive: {
      type: 'boolean',
      title: 'Activate custom Javascript',
    },
    cssActive: {
      type: 'boolean',
      title: 'Activate custom CSS',
    },
    javascriptBuild: {
      type: ['null', 'string'],
      title: 'Javascript Build',
    },
    cssBuild: {
      type: ['null', 'string'],
      title: 'CSS Build',
    },
  },
  'v-indexed': ['email', 'workspace', 'creationDate', 'appVersion'],
  'v-default-fields': ['email', 'workspace', 'creationDate', 'appVersion'],
  'v-cache': false,
}

const replacer = (template: string, keys: any) => {
  return template.replace(/"?{{\w+}}"?/g, (key: string) => {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore: Object is possibly 'null'.
    return keys[key.match(/\w+/)[0]] || 'false'
  })
}

export const resolvers = {
  Routes: {
    apiGetCountryRules: method({
      GET: [getCountryRules],
    }),
    getHolidays: method({
      GET: [holidays],
    }),
  },
  Mutation: {
    saveChanges: async (_: any, params: any, ctx: Context) => {
      const {
        clients: { masterdata, server },
        vtex: {  }
      } = ctx

      const app: string = getAppId()
      //authorization check
      await authCheck(ctx, app)

      const keys = { ...params.layout, ...params.colors }
      const cssTemplate = await fs.readFile(
        path.join(__dirname, '../templates/checkout6-custom.css'),
        {
          encoding: 'utf-8',
        }
      )

      const cssBuild =
        replacer(cssTemplate, keys) + String(params.cssActive ? params.css : '')

      const jsTemplate = await fs.readFile(
        path.join(__dirname, '../templates/checkout6-custom.js'),
        {
          encoding: 'utf-8',
        }
      )

      const javascriptBuild =
        replacer(jsTemplate, keys) +
        String(params.javascriptActive ? params.javascript : '')

      const creationDate = String(new Date().getTime())
      const appVersion = process.env.VTEX_APP_VERSION

      const data = await masterdata.createDocument({
        dataEntity: DATA_ENTITY,
        fields: {
          ...params,
          javascriptBuild,
          cssBuild,
          creationDate,
          appVersion,
        },
        schema: SCHEMA_VERSION,
      })

      server.saveVB({
        workspace: params.workspace,
        field: 'cssBuild',
        file: cssBuild,
      })

      server.saveVB({
        workspace: params.workspace,
        field: 'javascriptBuild',
        file: javascriptBuild,
      })

      return JSON.stringify(data)
    },
  },
  Query: {
    getSetupConfig: async (_: any, __: any, ctx: Context) => {
      const {
        clients: { masterdata, apps },
      } = ctx

      const app: string = getAppId()
      const settings = await apps.getAppSettings(app)

      if (
        !settings.adminSetup ||
        !settings.adminSetup?.hasSchema ||
        settings.adminSetup?.schemaVersion !== SCHEMA_VERSION
      ) {
        if (!settings.adminSetup) {
          settings.adminSetup = {}
        }

        try {
          await masterdata
            .createOrUpdateSchema({
              dataEntity: DATA_ENTITY,
              schemaName: SCHEMA_VERSION,
              schemaBody: schema,
            })
            .then(() => {
              settings.adminSetup.hasSchema = true
              settings.adminSetup.schemaVersion = SCHEMA_VERSION
            })
            .catch((e: any) => {
              settings.adminSetup.hasSchema = false
              // eslint-disable-next-line vtex/prefer-early-return
              if (e.response.status === 304) {
                settings.adminSetup.hasSchema = true
                settings.adminSetup.schemaVersion = SCHEMA_VERSION
              }
            })
        } catch (e) {
          settings.adminSetup.hasSchema = false
        }

        await apps.saveAppSettings(app, settings)
      }

      settings.adminSetup.appVersion = process.env.VTEX_APP_VERSION

      return settings
    },
    getHistory: async (_: any, __: any, ctx: any) => {
      const {
        clients: { masterdata },
      } = ctx

      const app: string = getAppId()
      //authorization check
      await authCheck(ctx, app)

      const data = await masterdata.searchDocuments({
        dataEntity: DATA_ENTITY,
        schema: SCHEMA_VERSION,
        fields: ['id', 'email', 'workspace', 'creationDate', 'appVersion'],
        sort: 'creationDate DESC',
        pagination: {
          page: 1,
          pageSize: 30,
        },
      })

      return data
    },
    getPermissions: async (_: any, __: any, ctx: any) => {

      const cookie = ctx.headers?.cookie

      const vtexCredentials: any = cookie
        ? cookie
            .split('; ')
            .find((cookie: string) => cookie.startsWith('VtexIdclientAutCookie='))
            ?.split('=')[1] ?? ''
        : '';

      const permission = await validateAdminToken(ctx, vtexCredentials)

      return {
        access: permission.hasValidAdminRole
      }
    },
    getById: async (_: any, params: any, ctx: any) => {
      const {
        clients: { masterdata },
      } = ctx

      const app: string = getAppId()
      //authorization check
      await authCheck(ctx, app)

      const data = await masterdata.getDocument({
        dataEntity: DATA_ENTITY,
        fields: [
          'css',
          'javascript',
          'layout',
          'colors',
          'javascriptActive',
          'cssActive',
        ],
        id: params.id,
      })

      return data
    },
    getLast: async (_: any, params: any, ctx: any) => {
      const {
        clients: { masterdata },
      } = ctx

      const app: string = getAppId()
      //authorization check
      await authCheck(ctx, app)

      const last = await masterdata
        .searchDocuments({
          dataEntity: DATA_ENTITY,
          schema: SCHEMA_VERSION,
          fields: ['id'],
          where: `workspace=${params.workspace}`,
          sort: 'creationDate DESC',
          pagination: {
            page: 1,
            pageSize: 1,
          },
        })
        .then((res: any) => res)

      if (!last.length) return {}

      const data = await masterdata.getDocument({
        dataEntity: DATA_ENTITY,
        id: last[0].id,
        fields: [
          'id',
          'email',
          'workspace',
          'creationDate',
          'appVersion',
          'layout',
          'javascript',
          'css',
          'colors',
          'javascriptActive',
          'cssActive',
        ],
      })

      return data ?? {}
    },
  },
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/mutations/saveConfiguration.gql from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation saveConfiguration(
  $email: String
  $workspace: String
  $layout: CustomFields
  $javascript: String
  $css: String
  $javascriptActive: Boolean
  $cssActive: Boolean
  $colors: CustomFields
) {
  saveChanges(
    email: $email
    workspace: $workspace
    layout: $layout
    javascript: $javascript
    css: $css
    javascriptActive: $javascriptActive
    cssActive: $cssActive
    colors: $colors
  )
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/typings/storefront.d.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable @typescript-eslint/ban-types */
import type { FunctionComponent } from 'react'

declare global {
  interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {
    getSchema?(props: P): object
    schema?: object
  }

  interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {
    getSchema?(props: P): object
    schema: object
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/typings/graphql.d.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.graphql' {
  import type { DocumentNode } from 'graphql'

  const value: DocumentNode
  export default value
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/typings/vtex.styleguide.d.ts from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.styleguide' {
  export const PageHeader
  export const Alert
  export const Modal
  export const Box
  export const Card
  export const Dropdown
  export const Spinner
  export const Table
  export const Button
  export const IconWarning
  export const IconCheck
  export const Input
  export const InputSearch
  export const IconCaretDown
  export const IconCaretUp
  export const IconArrowDown
  export const IconArrowBack
  export const IconArrowUp
  export const IconClose
  export const IconExternalLink
  export const IconSearch
  export const IconSuccess
  export const IconCopy
  export const IconCog
  export const Tooltip
  export const ToastConsumer
  export const ToastProvider
  export const withToast
  export const ButtonWithIcon
  export const Pagination
  export const Collapsible
  export const Textarea
  export const NumericStepper
  export const EmptyState
  export const Tab
  export const Tag
  export const Layout
  export const Tabs
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/queries/getHistory.gql from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```graphql
query GetHistory {
  getHistory {
    id
    email
    workspace
    creationDate
    appVersion
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/queries/getConfig.gql from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```graphql
query GetConfig {
  getSetupConfig {
    adminSetup {
      hasSchema
      schemaVersion
      appVersion
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/queries/getPermissions.gql from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getUserPermissions {
  getPermissions {
    access
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/queries/getById.gql from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```graphql
query GetById($id: String) {
  getById(id: $id) {
    css
    javascript
    layout
    colors
    javascriptActive
    cssActive
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/queries/getLast.gql from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```graphql
query GetLast($workspace: String) {
  getLast(workspace: $workspace) {
    css
    javascript
    layout
    colors
    javascriptActive
    cssActive
    appVersion
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/components/Colors.tsx from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { FC } from 'react'
import React, { useState } from 'react'
import type { WrappedComponentProps } from 'react-intl'
import { injectIntl } from 'react-intl'
import PropTypes from 'prop-types'
import { ColorPicker } from 'vtex.styleguide'

const Colors: FC<WrappedComponentProps & any> = ({
  initialState,
  onChange,
  intl,
}) => {
  const [state, setState] = useState<any>({
    ...initialState,
    history: [],
  })

  const handleChange = (color: any, picker: string) => {
    const { history } = state

    history.push(color)

    setState({
      ...state,
      history,
      [picker]: color.hex,
    })

    onChange({
      ...initialState,
      [picker]: color.hex,
    })
  }

  return (
    <div className="w-100 pa4">
      <div className="w-50 mb-4">
        <ColorPicker
          color={{ hex: state.base }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.base',
          })}
          onChange={(color: any) => {
            handleChange(color, 'base')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.baseInverted }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.baseInverted',
          })}
          onChange={(color: any) => {
            handleChange(color, 'baseInverted')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.actionPrimary }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.actionPrimary',
          })}
          onChange={(color: any) => {
            handleChange(color, 'actionPrimary')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.actionPrimaryDarken }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.actionPrimaryDarken',
          })}
          onChange={(color: any) => {
            handleChange(color, 'actionPrimaryDarken')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.actionSecondary }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.actionSecondary',
          })}
          onChange={(color: any) => {
            handleChange(color, 'actionSecondary')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.emphasis }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.emphasis',
          })}
          onChange={(color: any) => {
            handleChange(color, 'emphasis')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.disabled }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.disabled',
          })}
          onChange={(color: any) => {
            handleChange(color, 'disabled')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.success }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.success',
          })}
          onChange={(color: any) => {
            handleChange(color, 'success')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.successDarken }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.successDarken',
          })}
          onChange={(color: any) => {
            handleChange(color, 'successDarken')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.successFaded }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.successFaded',
          })}
          onChange={(color: any) => {
            handleChange(color, 'successFaded')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.danger }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.danger',
          })}
          onChange={(color: any) => {
            handleChange(color, 'danger')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.dangerFaded }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.dangerFaded',
          })}
          onChange={(color: any) => {
            handleChange(color, 'dangerFaded')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.warning }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.warning',
          })}
          onChange={(color: any) => {
            handleChange(color, 'warning')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.warningFaded }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.warningFaded',
          })}
          onChange={(color: any) => {
            handleChange(color, 'warningFaded')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.muted1 }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.muted1',
          })}
          onChange={(color: any) => {
            handleChange(color, 'muted1')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.muted2 }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.muted2',
          })}
          onChange={(color: any) => {
            handleChange(color, 'muted2')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.muted3 }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.muted3',
          })}
          onChange={(color: any) => {
            handleChange(color, 'muted3')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.muted4 }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.muted4',
          })}
          onChange={(color: any) => {
            handleChange(color, 'muted4')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.muted5 }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.muted5',
          })}
          onChange={(color: any) => {
            handleChange(color, 'muted5')
          }}
        />
      </div>

      <div className="w-50">
        <ColorPicker
          color={{ hex: state.muted6 }}
          colorHistory={state.history}
          label={intl.formatMessage({
            id: 'admin/checkout-ui.color.muted6',
          })}
          onChange={(color: any) => {
            handleChange(color, 'muted6')
          }}
        />
      </div>
    </div>
  )
}

Colors.propTypes = {
  onChange: PropTypes.func,
  initialState: PropTypes.any,
  intl: PropTypes.any,
}

export default injectIntl(Colors)

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/components/Javascript.tsx from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { FC } from 'react'
import React, { useState } from 'react'
import type { WrappedComponentProps } from 'react-intl'
import { defineMessages, injectIntl } from 'react-intl'
import PropTypes from 'prop-types'
import { Textarea, Toggle } from 'vtex.styleguide'

import Editor from '@monaco-editor/react'

const messages = defineMessages({
  label: {
    id: 'admin/checkout-ui.tab.javascript.label',
    defaultMessage: 'Custom Javascript',
  },
  helper: {
    id: 'admin/checkout-ui.tab.javascript.helper',
    defaultMessage: '// Changes here may impact your sales',
  },
  active: {
    id: 'admin/checkout-ui.toggle.active',
    defaultMessage: 'Active',
  },
})

const Javascript: FC<WrappedComponentProps & any> = ({
  initialState,
  onChange,
  intl,
}) => {
  const [state, setState] = useState<any>({
    value: initialState.value,
    active: initialState.active,
    theme:  true // true for "vs-dark" and false for "vs-light"
  })

  const handleChange = (key: string, value: any) => {
    const newState = { ...state, [key]: value }

    onChange(newState)
    setState(newState)
  }

  const parseText = (text: string) => {
    if (text === null) return ''
    const newText = text.replace(/\\n/g, String.fromCharCode(13))

    return newText
  }

  const handleChangeToggle = (value: any, key: string) => {
    const newState = {
      ...state,
      [key]: value
    }
    setState(newState)
    onChange(newState)
  }

  return (
    <div className="w-100 pa4">

      <div className="flex justify-between items-center">
        <p>{intl.formatMessage(messages.label)}</p>
        <div className="dib">
          <Toggle
            label={state.theme ? "Dark Theme" : "Light Theme"}
            checked={state.theme}
            onChange={() => {
              handleChangeToggle(
                !state.theme,
                'theme'
              )
            }}
          />
        </div>
      </div>

      <Editor
        height="90vh"
        defaultLanguage="javascript"
        defaultValue={intl.formatMessage(messages.helper)}
        theme={state.theme ? "vs-dark" : "vs-light" }
        value={parseText(state.value)}
        onChange={(e: any) => handleChange('value', e)}
      />

      <div className="dn">
        <Textarea
          size="large"
          rows={30}
          value={parseText(state.value)}
          onChange={(e: any) => handleChange('value', e.target.value)}
          label={intl.formatMessage(messages.label)}
          helpText={intl.formatMessage(messages.helper)}
        />
      </div>

      <div className="mt6 dib">
        <Toggle
          label={intl.formatMessage(messages.active)}
          size="large"
          checked={state.active}
          onChange={(e: any) => handleChange('active', e.currentTarget.checked)}
        />
      </div>
    </div>
  )
}

Javascript.propTypes = {
  onChange: PropTypes.func,
  initialState: PropTypes.any,
  intl: PropTypes.any,
}

export default injectIntl(Javascript)

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/components/History.tsx from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { FC } from 'react'
import React from 'react'
import type { WrappedComponentProps } from 'react-intl'
import { injectIntl, defineMessages, FormattedMessage } from 'react-intl'
import { useQuery, useLazyQuery } from 'react-apollo'
import PropTypes from 'prop-types'
import { Table, Button } from 'vtex.styleguide'

import query from '../queries/getHistory.gql'
import GET_BY_ID from '../queries/getById.gql'

const messages = defineMessages({
  email: {
    id: 'admin/checkout-ui.history.label.email',
    defaultMessage: 'Email',
  },
  workspace: {
    id: 'admin/checkout-ui.history.label.workspace',
    defaultMessage: 'Workspace',
  },
  version: {
    id: 'admin/checkout-ui.history.label.version',
    defaultMessage: 'App version',
  },
  date: {
    id: 'admin/checkout-ui.history.label.date',
    defaultMessage: 'Creation date',
  },
  load: {
    id: 'admin/checkout-ui.history.button.load',
    defaultMessage: 'Load',
  },
})

const History: FC<any & WrappedComponentProps> = ({
  intl,
  onChange,
  initialState,
}: any) => {
  const { loading, data } = useQuery(query)

  const [getConfig, { loading: loadingConfig }] = useLazyQuery(GET_BY_ID, {
    onCompleted: (res: any) => {
      onChange(res.getById)
    },
  })

  const load = (id: string) => {
    getConfig({
      variables: {
        id,
      },
    })
  }

  const customSchema = {
    properties: {
      email: {
        title: intl.formatMessage(messages.email),
        width: 300,
      },
      workspace: {
        title: intl.formatMessage(messages.workspace),
        width: 200,
      },
      appVersion: {
        title: intl.formatMessage(messages.version),
        width: 100,
      },
      creationDate: {
        title: intl.formatMessage(messages.date),
        width: 200,
        // eslint-disable-next-line react/display-name
        cellRenderer: ({ cellData }: any) => {
          const datetime = new Date(parseInt(cellData, 10))

          return (
            <span>
              {intl.formatDate(datetime, {
                day: 'numeric',
                month: 'numeric',
                year: 'numeric',
              })}{' '}
              {intl.formatTime(datetime, {
                hour: 'numeric',
                minute: 'numeric',
                second: 'numeric',
              })}
            </span>
          )
        },
      },
      id: {
        title: ' ',
        width: 200,
        // eslint-disable-next-line react/display-name
        cellRenderer: ({ rowData }: any) => {
          return (
            <Button
              variation="tertiary"
              size="small"
              disabled={loadingConfig}
              onClick={() => {
                load(rowData.id)
              }}
            >
              {intl.formatMessage(messages.load)}
            </Button>
          )
        },
      },
    },
  }

  const items = data?.getHistory || []

  return (
    <div className="w-100 pt6">
      <span>
        <FormattedMessage id="admin/checkout-ui.history.help.appversion" />{' '}
        {initialState}
      </span>
      <Table
        fullWidth
        loading={loading}
        schema={customSchema}
        items={items}
        indexColumnLabel="#"
      />
    </div>
  )
}

History.propTypes = {
  onChange: PropTypes.func,
  initialState: PropTypes.any,
}

export default injectIntl(History)

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/components/Layout.tsx from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react/prop-types */
import type { FC } from 'react'
import React, { useState } from 'react'
import type { WrappedComponentProps } from 'react-intl'
import { injectIntl, FormattedMessage } from 'react-intl'
import PropTypes from 'prop-types'
import { Toggle, Slider, Input, Card, Divider } from 'vtex.styleguide'

import TabsOn from '../images/payments-tabs-on.png'
import TabsOff from '../images/payments-tabs-off.png'
import PriceOn from '../images/cart-quantity-price-on.png'
import PriceOff from '../images/cart-quantity-price-off.png'
import ShippingOff from '../images/shipping-date-number.png'
import ShippingOn from '../images/shipping-date-text.png'
import NotesOn from '../images/notes-field-on.png'
import NotesOff from '../images/notes-field-off.png'
import EmailStepOn from '../images/email-step-on.png'
import EmailStepOff from '../images/email-step-off.png'
import CustomAddresFormOn from '../images/usaddressform-on.png'
import CustomAddresFormOff from '../images/usaddressform-off.png'

const images: any = {
  tabsOn: TabsOn,
  tabsOff: TabsOff,
  shippingOn: ShippingOn,
  shippingOff: ShippingOff,
  priceOn: PriceOn,
  priceOff: PriceOff,
  notesOn: NotesOn,
  notesOff: NotesOff,
  emailStepOn: EmailStepOn,
  emailStepOff: EmailStepOff,
  customAddresFormOn: CustomAddresFormOn,
  customAddresFormOff: CustomAddresFormOff,
}

const LayoutSettings: FC<WrappedComponentProps & any> = ({
  initialState,
  onChange,
  intl,
}) => {
  const [state, setState] = useState<any>({
    ...initialState,
    currentPreview: initialState.accordionPayments ? TabsOff : TabsOn,
  })

  const changePreview = (item: string) => {
    const currentPreview = images[item]

    setState({
      ...state,
      currentPreview,
    })
  }

  const handleChange = (value: any, key: string, image?: string) => {
    const currentPreview = image ? images[image] : state.currentPreview
    const newState = {
      ...state,
      [key]: value,
      currentPreview,
    }

    setState(newState)
    onChange(newState)
  }

  return (
    <div className="w-100 pa4">
      <div className="w-100 cf cb">
        <div className="w-50 fl pr7">
          <div
            className="mt6 db flex items-center"
            onMouseEnter={() => {
              changePreview(state.accordionPayments ? 'tabsOff' : 'tabsOn')
            }}
          >
            <Toggle
              label={intl.formatMessage({
                id: 'admin/checkout-ui.layout.accordionPayments.label',
              })}
              size="large"
              helpText={intl.formatMessage({
                id: 'admin/checkout-ui.layout.accordionPayments.help',
              })}
              checked={state.accordionPayments}
              onChange={(e: any) => {
                handleChange(
                  !state.accordionPayments,
                  'accordionPayments',
                  e.currentTarget.checked ? 'tabsOff' : 'tabsOn'
                )
              }}
            />
          </div>
          <br />

          <div
            className="mt6 db flex items-center"
            onMouseEnter={() => {
              changePreview(
                state.deliveryDateFormat ? 'shippingOn' : 'shippingOff'
              )
            }}
          >
            <Toggle
              label={intl.formatMessage({
                id: 'admin/checkout-ui.layout.deliveryDateFormat.label',
              })}
              size="large"
              helpText={intl.formatMessage({
                id: 'admin/checkout-ui.layout.deliveryDateFormat.help',
              })}
              checked={state.deliveryDateFormat}
              onChange={(e: any) =>
                handleChange(
                  !state.deliveryDateFormat,
                  'deliveryDateFormat',
                  e.currentTarget.checked ? 'shippingOn' : 'shippingOff'
                )
              }
            />
          </div>
          <br />

          <div
            className="mt6 db flex items-center"
            onMouseEnter={() => {
              changePreview(
                state.showCartQuantityPrice ? 'priceOn' : 'priceOff'
              )
            }}
          >
            <Toggle
              label={intl.formatMessage({
                id: 'admin/checkout-ui.layout.showCartQuantityPrice.label',
              })}
              size="large"
              helpText={intl.formatMessage({
                id: 'admin/checkout-ui.layout.showCartQuantityPrice.help',
              })}
              checked={state.showCartQuantityPrice}
              onChange={(e: any) =>
                handleChange(
                  !state.showCartQuantityPrice,
                  'showCartQuantityPrice',
                  e.currentTarget.checked ? 'priceOn' : 'priceOff'
                )
              }
            />
          </div>
          <br />
          <div
            className="mt6 db flex items-center"
            onMouseEnter={() => {
              changePreview(state.showNoteField ? 'notesOn' : 'notesOff')
            }}
          >
            <Toggle
              label={intl.formatMessage({
                id: 'admin/checkout-ui.layout.showNoteField.label',
              })}
              size="large"
              checked={state.showNoteField}
              onChange={(e: any) =>
                handleChange(
                  !state.showNoteField,
                  'showNoteField',
                  e.currentTarget.checked ? 'notesOn' : 'notesOff'
                )
              }
            />
          </div>
          <br />
          <div
            className="mt6 db flex items-center"
            onMouseEnter={() => {
              changePreview(
                state.hideEmailStep ? 'emailStepOff' : 'emailStepOn'
              )
            }}
          >
            <Toggle
              label={intl.formatMessage({
                id: 'admin/checkout-ui.layout.hideEmailStep.label',
              })}
              size="large"
              checked={state.hideEmailStep}
              onChange={(e: any) =>
                handleChange(
                  !state.hideEmailStep,
                  'hideEmailStep',
                  e.currentTarget.checked ? 'emailStepOn' : 'emailStepOff'
                )
              }
            />
          </div>
          <br />
          <div
            className="mt6 db flex items-center"
            onMouseEnter={() => {
              changePreview(
                state.customAddressForm
                  ? 'customAddresFormOn'
                  : 'customAddresFormOff'
              )
            }}
          >
            <Toggle
              label={intl.formatMessage({
                id: 'admin/checkout-ui.layout.customAddressForm.label',
              })}
              size="large"
              checked={state.customAddressForm}
              onChange={(e: any) =>
                handleChange(
                  !state.customAddressForm,
                  'customAddressForm',
                  e.currentTarget.checked
                    ? 'customAddresFormOn'
                    : 'customAddresFormOff'
                )
              }
            />
            <p
              style={{
                display: 'inline-block',
                background: '#f71963',
                margin: '0 0 0 10px',
                padding: '5px',
                borderRadius: '10px',
                color: '#FFF',
                float: 'left',
                fontSize: '13px',
              }}
            >
              BETA
            </p>
          </div>
        </div>
        <div className="w-50 fr">
          <Card noPadding>
            <h3 className="pl6 pr6 pt6">
              <FormattedMessage id="admin/checkout-ui.layout.preview.title" />
            </h3>
            <img
              alt={intl.formatMessage({
                id: 'admin/checkout-ui.layout.preview.title',
              })}
              style={{ maxHeight: '260px', display: 'block', margin: '0 auto' }}
              src={state.currentPreview}
            />
          </Card>
        </div>
      </div>

      <div className="mv6">
        <Divider orientation="horizontal" />
      </div>

      <div className="w-100 cf cb">
        <div className="w-50 fl pr7">
          <div className="mt6 flex">
            <div className="flex flex-column items-left w-50">
              <div className="flex-col">
                <span>
                  <FormattedMessage id="admin/checkout-ui.layout.fontSize.label" />
                </span>
              </div>
              <div className="flex-col">
                <Slider
                  onChange={(value: any) => {
                    handleChange(`${value[0]}px`, 'fontSize')
                  }}
                  min={10}
                  max={30}
                  step={1}
                  defaultValues={[state.fontSize.replace('px', '')]}
                  alwaysShowCurrentValue={false}
                  formatValue={(a: number) => `${a}px`}
                />
              </div>
            </div>
          </div>

          <div className="mt6 flex">
            <div className="flex flex-column items-left w-50">
              <div className="flex-col">
                <span>
                  <FormattedMessage id="admin/checkout-ui.layout.borderRadius.label" />
                </span>
              </div>
              <div className="flex-col">
                <Slider
                  onChange={(value: any) => {
                    handleChange(`${value[0]}px`, 'borderRadius')
                  }}
                  min={0}
                  max={50}
                  step={1}
                  defaultValues={[state.borderRadius.replace('px', '')]}
                  alwaysShowCurrentValue={false}
                  formatValue={(a: number) => `${a}px`}
                />
              </div>
            </div>
          </div>

          <div className="mt6 flex">
            <div className="flex flex-column items-left w-50">
              <div className="flex-col">
                <span>
                  <FormattedMessage id="admin/checkout-ui.layout.btnBorderRadius.label" />
                </span>
              </div>
              <div className="flex-col">
                <Slider
                  onChange={(value: any) => {
                    handleChange(`${value[0]}px`, 'btnBorderRadius')
                  }}
                  min={0}
                  max={50}
                  step={1}
                  defaultValues={[state.btnBorderRadius.replace('px', '')]}
                  alwaysShowCurrentValue={false}
                  formatValue={(a: number) => `${a}px`}
                />
              </div>
            </div>
          </div>

          <div className="mt6 flex">
            <div className="flex flex-column items-left w-50">
              <div className="flex-col">
                <span>
                  <FormattedMessage id="admin/checkout-ui.layout.inputHeight.label" />
                </span>
              </div>
              <div className="flex-col">
                <Slider
                  onChange={(value: any) => {
                    handleChange(`${value[0]}px`, 'inputHeight')
                  }}
                  min={0}
                  max={50}
                  step={1}
                  defaultValues={[state.inputHeight.replace('px', '')]}
                  alwaysShowCurrentValue={false}
                  formatValue={(a: number) => `${a}px`}
                />
              </div>
            </div>
          </div>
        </div>

        <div className="w-50 fr">
          <div
            className="summary-template-holder"
            style={{
              boxShadow: 'rgba(61, 62, 64, 0.3) 0px 3px 9px 0px',
              padding: '20px',
              borderRadius: `${state.borderRadius}`,
              border: state.bordersContainers,
              fontFamily: state.fontFamily,
            }}
          >
            <h3>
              <FormattedMessage id="admin/checkout-ui.layout.preview.title" />
            </h3>

            <p
              style={{
                fontFamily: state.fontFamily,
                fontSize: `${state.fontSize}`,
              }}
            >
              <FormattedMessage id="admin/checkout-ui.layout.preview.sample" />
            </p>

            <p className="coupon-fields">
              <span className="flex">
                <input
                  className="w-80"
                  type="text"
                  placeholder="Coupon Code"
                  style={{
                    height: `${state.inputHeight}`,
                    borderRadius: `${state.borderRadius}`,
                    border: `1px solid #cacbcc`,
                    fontSize: `${state.fontSize}`,
                    padding: '0 10px',
                  }}
                />
                <button
                  className="bg-action-primary c-on-action-primary w-20 ml3"
                  style={{
                    borderRadius: `${state.btnBorderRadius}`,
                    height: `${state.inputHeight}`,
                    border: `none`,
                    padding: `5px 12px`,
                    fontSize: `${state.fontSize}`,
                  }}
                  type="submit"
                >
                  <FormattedMessage id="admin/checkout-ui.layout.preview.button" />
                </button>
              </span>
            </p>
            <div
              className=""
              style={{
                fontFamily: state.fontFamily,
                fontSize: `${state.fontSize}`,
              }}
            >
              <div className="Items flex justify-around">
                <div className="w-50 tl">Subtotal</div>
                <div className="w-50 tr">$ 64.35</div>
              </div>
              <div className="srp-summary-result flex justify-around">
                <div className="w-50 tl">Shipping</div>
                <div className="w-50 tr">$ 3.00</div>
              </div>
              <div
                className="flex justify-around"
                style={{
                  fontSize: '18px',
                  fontWeight: 'bold',
                  padding: '14px 0',
                  margin: '14px 0',
                  borderTop: '1px solid #cbcbcb',
                }}
              >
                <div className="w-50 tl">Total</div>
                <div className="w-50 tr">$ 67.35</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="mv7">
        <Divider orientation="horizontal" />
      </div>

      <div className="w-100 cf cb">
        <div className="w-100 flex justify-between">
          <div className="w-30">
            <Input
              label={intl.formatMessage({
                id: 'admin/checkout-ui.layout.maxWrapper.label',
              })}
              value={state.maxWrapper}
              placeholder="980px, 90%, etc."
              onChange={(e: any) => {
                handleChange(e.target.value, 'maxWrapper')
              }}
            />
          </div>

          <div className="w-30">
            <Input
              label={intl.formatMessage({
                id: 'admin/checkout-ui.layout.bordersContainers.label',
              })}
              value={state.bordersContainers}
              placeholder="2px solid #eee"
              onChange={(e: any) => {
                handleChange(e.target.value, 'bordersContainers')
              }}
            />
          </div>

          <div className="w-30">
            <Input
              label={intl.formatMessage({
                id: 'admin/checkout-ui.layout.fontFamily.label',
              })}
              value={state.fontFamily}
              placeholder="'Roboto', sans-serif"
              onChange={(e: any) => {
                handleChange(e.target.value, 'fontFamily')
              }}
            />
          </div>
        </div>
      </div>
    </div>
  )
}

LayoutSettings.propTypes = {
  onChange: PropTypes.func,
  initialState: PropTypes.any,
}

export default injectIntl(LayoutSettings)

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-ui-custom/react/components/Css.tsx from the checkout-ui-custom VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState } from 'react'
import type { WrappedComponentProps } from 'react-intl'
import { defineMessages, injectIntl } from 'react-intl'
import PropTypes from 'prop-types'
import { Textarea, Toggle } from 'vtex.styleguide'

import Editor from '@monaco-editor/react'

const messages = defineMessages({
  label: {
    id: 'admin/checkout-ui.tab.css.label',
    defaultMessage: 'Custom CSS',
  },
  helper: {
    id: 'admin/checkout-ui.tab.css.helper',
    defaultMessage: '/* Changes here may impact your sales */',
  },
  active: {
    id: 'admin/checkout-ui.toggle.active',
    defaultMessage: 'Active',
  },
})

const Css: StorefrontFunctionComponent<WrappedComponentProps & any> = ({
  initialState,
  onChange,
  intl,
}) => {
  const [state, setState] = useState<any>({
    value: initialState.value,
    active: initialState.active,
    theme:  true // true for "vs-dark" and false for "vs-light"
  })

  const handleChange = (key: string, value: any) => {
    const newState = { ...state, [key]: value }

    onChange(newState)
    setState(newState)
  }

  const parseText = (text: string) => {
    if (text === null) return ''
    const newText = text.replace(/\\n/g, String.fromCharCode(13))

    return newText
  }

  const handleChangeToggle = (value: any, key: string) => {
    const newState = {
      ...state,
      [key]: value
    }
    setState(newState)
    onChange(newState)
  }

  return (
    <div className="w-100 pa4">

      <div className="flex justify-between items-center">
        <p>{intl.formatMessage(messages.label)}</p>
        <div className="dib">
          <Toggle
            label={state.theme ? "Dark Theme" : "Light Theme"}
            checked={state.theme}
            onChange={() => {
              handleChangeToggle(
                !state.theme,
                'theme'
              )
            }}
          />
        </div>
      </div>

      <Editor
        height="90vh"
        defaultLanguage="css"
        defaultValue={intl.formatMessage(messages.helper)}
        theme={state.theme ? "vs-dark" : "vs-light" }
        value={parseText(state.value)}
        onChange={(e: any) => handleChange('value', e)}
      />

      <div className="dn">
        <Textarea
          size="large"
          rows={30}
          value={parseText(state.value)}
          onChange={(e: any) => handleChange('value', e.target.value)}
          label={intl.formatMessage(messages.label)}
          helpText={intl.formatMessage(messages.helper)}
        />
      </div>

      <div className="mt6 dib">
        <Toggle
          label={intl.formatMessage(messages.active)}
          size="large"
          checked={state.active}
          onChange={(e: any) => handleChange('active', e.currentTarget.checked)}
        />
      </div>
    </div>
  )
}

Css.propTypes = {
  onChange: PropTypes.func,
  initialState: PropTypes.any,
  intl: PropTypes.any,
}

export default injectIntl(Css)

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of tradetracker/docs/README.md from the tradetracker VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Tradetracker

VTEX Tradetracker first-party app

## How to install

Open the VTEX App Store and install this app on your store.

Now, open the app settings on your admin and fill in the Tradetracker options.

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of tradetracker/react/index.tsx from the tradetracker VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { PixelMessage } from "./typings/events";
import { canUseDOM } from "vtex.render-runtime";

function handleMessages(e: PixelMessage) {
  const {
    ttConversionOptions = [],
    __tradetracker: {
      tradeTrackerCampaignID: campaignID,
      tradeTrackerProductID: productID,
      tradeTrackerDescrMerchant: descrMerchant,
      tradeTrackerDescrAffiliate: descrAffiliate
    }
  } = window;
  switch (e.data.eventName) {
    case "vtex:orderPlaced": {
      const {
        transactionId: transactionID,
        currency,
        transactionTotal: transactionAmount,
        visitorContactInfo: [email]
      } = e.data;
      ttConversionOptions.push({
        type: "sales",
        quantity: "1",
        email,
        currency,
        campaignID,
        productID,
        transactionID,
        transactionAmount,
        descrMerchant,
        descrAffiliate
      });
      const tradeTrackerScriptTag = document.createElement("script");
      tradeTrackerScriptTag.type = "text/javascript";
      tradeTrackerScriptTag.async = true;
      tradeTrackerScriptTag.src = "//tm.tradetracker.net/conversion?s=" + encodeURIComponent(campaignID) + "&t=m";
      const scriptTags = document.getElementsByTagName("script");
      if (scriptTags && scriptTags.length) {
        const lastScriptTag = scriptTags[scriptTags.length - 1];
        if (lastScriptTag && lastScriptTag.parentNode) {
          lastScriptTag.parentNode.insertBefore(tradeTrackerScriptTag, lastScriptTag);
        }
      }
      break;
    }
  }
}

if (canUseDOM) {
  window.addEventListener("message", handleMessages);
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of tradetracker/react/package.json from the tradetracker VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "vtex.tradetracker",
  "version": "0.0.0",
  "scripts": {
    "lint": "tsc --noEmit --pretty && tslint -c tslint.json './**/*.ts'"
  },
  "devDependencies": {
    "@types/node": "^10.12.18",
    "tslint": "^5.11.0",
    "tslint-config-vtex": "^2.0.0",
    "tslint-eslint-rules": "^5.4.0",
    "typescript": "3.5.2"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of tradetracker/store/interfaces.json from the tradetracker VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "pixel.tradetracker": {
    "component": "index"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of tradetracker/react/typings/events.d.ts from the tradetracker VTEX app.

[Assistant]
Here's the implementation:

```typescript
export interface PixelMessage extends MessageEvent {
  data:
    | ProductViewData
    | ProductClickData
    | OrderPlacedData
    | PageViewData
    | PageInfoData
    | ProductImpressionData
    | AddToCartData
    | RemoveToCartData
    | CategoryViewData
    | DepartmentViewData;
}

export interface EventData {
  event: string;
  eventName: string;
  currency: string;
}

export interface PageViewData extends EventData {
  event: "pageView";
  eventName: "vtex:pageView";
  pageTitle: string;
  pageUrl: string;
  referrer: string;
}

export interface PageInfoData extends EventData {
  event: "pageInfo";
  eventName: "vtex:pageInfo";
  eventType: string;
  accountName: string;
  pageCategory: string;
  pageDepartment: string;
  pageFacets: string[];
  pageTitle: string;
  pageUrl: string;
}

export interface CategoryViewData extends EventData {
  event: "categoryView";
  eventName: "vtex:categoryView";
  products: Product[];
}

export interface DepartmentViewData extends EventData {
  event: "departmentView";
  eventName: "vtex:departmentView";
  products: Product[];
}

export interface AddToCartData extends EventData {
  event: "addToCart";
  eventName: "vtex:addToCart";
  items: AddToCartProduct[];
}

export interface RemoveToCartData extends EventData {
  event: "removeFromCart";
  eventName: "vtex:removeFromCart";
  items: any[];
}

export interface OrderPlacedData extends Order, EventData {
  event: "orderPlaced";
  eventName: "vtex:orderPlaced";
}

export interface ProductViewData extends EventData {
  event: "productView";
  eventName: "vtex:productView";
  product: Product;
}

export interface ProductClickData extends EventData {
  event: "productClick";
  eventName: "vtex:productClick";
  product: Product;
}

export interface ProductImpressionData extends EventData {
  event: "productImpression";
  eventName: "vtex:productImpression";
  product: Product;
  position: number;
  list: string;
}

export interface Order {
  currency: string;
  accountName: string;
  orderGroup: string;
  salesChannel: string;
  coupon: string;
  visitorType: string;
  visitorContactInfo: string[];
  transactionId: string;
  transactionDate: string;
  transactionAffiliation: string;
  transactionTotal: number;
  transactionShipping: number;
  transactionTax: number;
  transactionCurrency: string;
  transactionPaymentType: PaymentType[];
  transactionShippingMethod: ShippingMethod[];
  transactionProducts: ProductOrder[];
  transactionPayment: {
    id: string;
  };
}

interface PaymentType {
  group: string;
  paymentSystemName: string;
  installments: number;
  value: number;
}

interface ShippingMethod {
  itemId: string;
  selectedSla: string;
}

interface ProductOrder {
  id: string;
  name: string;
  sku: string;
  skuRefId: string;
  skuName: string;
  brand: string;
  brandId: string;
  seller: string;
  sellerId: string;
  category: string;
  categoryId: string;
  categoryTree: string[];
  categoryIdTree: string[];
  originalPrice: number;
  price: number;
  sellingPrice: number;
  tax: number;
  quantity: number;
  components: any[];
  measurementUnit: string;
  unitMultiplier: number;
}

export interface Product {
  brand: string;
  categoryId?: string; // inconsistency
  categories: string[];
  productId: string;
  productName: string;
  selectedSku?: string; // inconsistency
  items: Item[];
  sku: Item;
  [key: string]: any;
}

interface Item {
  itemId: string;
  name: string;
  seller?: Seller;
  [key: string]: any;
}

interface Seller {
  commertialOffer: CommertialOffer;
  AvailableQuantity: number;
  [key: string]: any;
}

interface CommertialOffer {
  Price: number;
  [key: string]: any;
}

interface AddToCartProduct {
  brand: string;
  name: string;
  price: number;
  quantity: number;
  skuId: string;
  variant: string;
  category: string;
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of tradetracker/react/typings/vtex.render-runtime.d.ts from the tradetracker VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.render-runtime' {
  export const canUseDOM: boolean
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of tradetracker/react/typings/global.d.ts from the tradetracker VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare function fbq(s: string, t: string, o?: any): void;

interface Event extends Event {
  data: any;
}

interface Window extends Window {
  ttConversionOptions: TradeTrackerEvent[];
  __tradetracker: {
    tradeTrackerCampaignID: string;
    tradeTrackerProductID: string;
    tradeTrackerDescrMerchant: string;
    tradeTrackerDescrAffiliate: string;
  };
}

interface TradeTrackerEvent {
  type: "sales";
  quantity: string;
  email: string;
  currency: string;
  campaignID: string;
  productID: string;
  transactionID: string;
  transactionAmount: number;
  descrMerchant: string;
  descrAffiliate: string;
}

interface TradeTrackerEventItemProduct {
  id: string;
  name: string;
  price: string;
  department: string;
  category: string;
  subcategory: string;
  brand: string;
}

interface TradeTrackerEventItemKeyword {
  keyword: string;
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of countries-data/scripts/jsconfig.json from the countries-data VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": ["es2018"],
    "checkJs": true
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of countries-data/scripts/create-country-app.js from the countries-data VTEX app.

[Assistant]
Here's the implementation:

```javascript
#!/usr/bin/env node

/* eslint-disable no-console */

const fsp = require('fs').promises
const path = require('path')

const packagesDir = path.resolve(__dirname, '..', 'packages')

const SERVICE_APP_NAME = 'vtex.country-data-settings'

const CHANGELOG_TEMPLATE = `
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
`.trim()

/**
 * @param {string} [country] - Country
 */
const getManifestTemplate = (country) =>
  `
{
  "vendor": "vtex",
  "name": "country-data-${country}",
  "version": "0.0.0",
  "builders": {
    ${JSON.stringify(SERVICE_APP_NAME)}: "0.x"
  },
  "$schema": "https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema"
}
`.trim()

const printHelp = () => {
  const [, scriptName] = process.argv
  const formattedAppName = path.relative(process.cwd(), scriptName)

  console.log(
    `
Usage: ./${formattedAppName} [...countries]

This script creates the boilerplate for a country configuration app inside packages/[country]/.

Examples:

  The command:

    ./${formattedAppName} bra

  Creates the "bra" directory in "packages/"

  The command:

    ./${formattedAppName} usa bol arg

  Creates the "usa", "bol" and "arg" directories in "packages/"
`
  )
}

const main = async () => {
  const [, , ...countries] = process.argv

  if (!countries.length) {
    printHelp()
    return
  }

  await Promise.all(
    countries.map(async (country) => {
      try {
        const manifest = getManifestTemplate(country)

        const appDir = path.join(packagesDir, country)

        try {
          await fsp.access(path.join(appDir, 'manifest.json'))

          console.log(`App for country "${country}" already exists.`)

          return
        } catch {
          // ignored
        }

        await fsp.mkdir(appDir)

        // create manifest.json file
        await fsp.writeFile(path.join(appDir, 'manifest.json'), manifest)

        await fsp.mkdir(path.join(appDir, SERVICE_APP_NAME))

        // create basic configuration.json file
        await fsp.writeFile(
          path.join(appDir, SERVICE_APP_NAME, 'configuration.json'),
          '{}'
        )

        // create CHANGELOG.md file
        await fsp.writeFile(
          path.join(appDir, 'CHANGELOG.md'),
          CHANGELOG_TEMPLATE
        )

        console.log(`Successfully bootstrapped app for country "${country}"`)
      } catch (err) {
        console.error(
          `An unexpected error occured when bootstrapping app for country "${country}"`
        )
        console.error(err)
      }
    })
  )
}

main()

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of countries-data/packages/usa/manifest.json from the countries-data VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "vendor": "vtex",
  "name": "country-data-usa",
  "version": "0.1.2",
  "builders": {
    "vtex.country-data-settings": "0.x"
  },
  "$schema": "https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of countries-data/packages/bra/manifest.json from the countries-data VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "vendor": "vtex",
  "name": "country-data-bra",
  "version": "0.2.1",
  "title": "Brazil Data for Places Components",
  "builders": {
    "vtex.country-data-settings": "0.x"
  },
  "$schema": "https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of countries-data/packages/bol/manifest.json from the countries-data VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "vendor": "vtex",
  "name": "country-data-bol",
  "version": "0.1.0",
  "builders": {
    "vtex.country-data-settings": "0.x"
  },
  "$schema": "https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of countries-data/packages/arg/manifest.json from the countries-data VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "vendor": "vtex",
  "name": "country-data-arg",
  "version": "0.1.0",
  "builders": {
    "vtex.country-data-settings": "0.x"
  },
  "$schema": "https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema"
}

```