[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 avatax-br-admin/react/queries/getDocks.gql from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getDocks{
  getDocks @context(provider: "vtex.avatax-br-service@1.x"){
    name
    id
  }
}

```


[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 avatax-br-admin/react/queries/delete.gql from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation deleteEstablishment($documentId: ID){
  establishmentDelete(documentId: $documentId) @context(provider: "vtex.avatax-br-service@1.x")
}

```


[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 avatax-br-admin/react/queries/verifyPing.gql from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
query verifyPing($clientId: String, $clientSecret: String, $sandbox: Boolean) {
  verifyPing(
    clientId: $clientId
    clientSecret: $clientSecret
    sandbox: $sandbox
  ) @context(provider: "vtex.avatax-br-service@1.x")
}

```


[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 avatax-br-admin/react/queries/getSettings.gql from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getSettings {
  getSettings @context(provider: "vtex.avatax-br-service@1.x") {
    useAvalaraSandboxEnv
    clientIdValue
    clientSecretValue
  }
}

```


[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 avatax-br-admin/react/queries/setTaxConfiguration.gql from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation setTaxConfigurationMutation($operation: String){
  setTaxConfiguration(operation: $operation) @context(provider: "vtex.avatax-br-service@1.x"){
     minimumQuantityAccumulatedForItems
    decimalDigitsPrecision
    minimumValueAccumulated
    allowMultipleDeliveries
    allowManualPrice
    maxIntOfWhiteLabelSellers
    maskFirstPurchaseData
    recaptchaValidation
  }
}

```


[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 avatax-br-admin/react/queries/getAddress.gql from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation getAddress($zipCode: String) {
  getAddress(zipCode: $zipCode)
    @context(provider: "vtex.avatax-br-service@1.x") {
    postalCode
    city
    state
    street
    number
    neighborhood
    complement
    reference
    geoCoordinates
  }
}

```


[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 avatax-br-admin/react/utils/definedMessages.ts from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { defineMessages } from 'react-intl'

export const stock = defineMessages({
  info: { id: 'avatax-admin.info' },
  place: { id: 'avatax-admin.place' },
})

export const authentication = defineMessages({
  authentication: {
    id: 'avatax-admin.authentication',
  },
  clientId: {
    id: 'avatax-admin.client.id',
  },
  clientSecret: {
    id: 'avatax-admin.client.secret',
  },
  change: {
    id: 'avatax-admin.change',
  },
  save: {
    id: 'avatax-admin.save',
  },
})

export const currentStock = defineMessages({
  id: {
    id: 'avatax-admin.id',
  },
  dockName: {
    id: 'avatax-admin.dock.name',
  },
  edit: {
    id: 'avatax-admin.edit',
  },
  delete: {
    id: 'avatax-admin.delete',
  },
  loading: {
    id: 'avatax-admin.loading',
  },
})

export const modal = defineMessages({
  save: {
    id: 'avatax-admin.save',
  },
  data: {
    id: 'avatax-admin.data',
  },
  cancel: {
    id: 'avatax-admin.cancel',
  },
  edit: {
    id: 'avatax-admin.edit.stock',
  },
})

export const ping = defineMessages({
  verify: {
    id: 'avatax-admin.verify',
  },
  true: {
    id: 'avatax-admin.verify.true',
  },
  false: {
    id: 'avatax-admin.verify.false',
  },
  verifyButton: {
    id: 'avatax-admin.verify.button',
  },
})

export const sandbox = defineMessages({
  environment: {
    id: 'avatax-admin.environment',
  },
  sandbox: {
    id: 'avatax-admin.sandbox',
  },
  production: {
    id: 'avatax-admin.production',
  },
  use: {
    id: 'avatax-admin.use.sandbox',
  },
})

export const toggle = defineMessages({
  loading: {
    id: 'avatax-admin.loading',
  },
  status: {
    id: 'avatax-admin.status',
  },
  activate: {
    id: 'avatax-admin.activate',
  },
  deactivate: {
    id: 'avatax-admin.deactivate',
  },
})

export const buttonAdd = defineMessages({
  add: {
    id: 'avatax-admin.add',
  },
  dataSave: {
    id: 'avatax-admin.data.save',
  },
})

export const buttonSave = defineMessages({
  save: {
    id: 'avatax-admin.save',
  },
})

export const provider = defineMessages({
  number: {
    id: 'avatax-admin.number',
  },
  cnpj: {
    id: 'avatax-admin.cnpj',
  },
  zipcode: {
    id: 'avatax-admin.zipcode',
  },
  cnpjLength: {
    id: 'avatax-admin.cnpj.length',
  },
  empty: {
    id: 'avatax-admin.empty',
  },
})

export const avatax = defineMessages({
  avatax: {
    id: 'avatax-admin.avatax',
  },
  avalara: {
    id: 'avatax-admin.avalara',
  },
  configuration: {
    id: 'avatax-admin.configuration',
  },
  addStock: {
    id: 'avatax-admin.add.stock',
  },
  fields: {
    id: 'avatax-admin.fields',
  },
  currentStock: {
    id: 'avatax-admin.current.stock',
  },
})

export const values = defineMessages({
  dockIdPlaceholder: {
    id: 'avatax-admin.dock.id.placeholder',
  },
  dockIdLabel: {
    id: 'avatax-admin.dock.id.label',
  },
  dockNamePlaceholder: {
    id: 'avatax-admin.dock.name.placeholder',
  },
  dockNameLabel: {
    id: 'avatax-admin.dock.name.label',
  },
  icmsOptionsTrue: {
    id: 'avatax-admin.icms.option.true',
  },
  icmsOptionsFalse: {
    id: 'avatax-admin.icms.option.false',
  },
  icmsLabel: {
    id: 'avatax-admin.icms.label',
  },
  activityLabel: {
    id: 'avatax-admin.activity.label',
  },
  activitySecurity: {
    id: 'avatax-admin.activity.security',
  },
  activityWholesale: {
    id: 'avatax-admin.activity.wholesale',
  },
  activityWarehouseGeneral: {
    id: 'avatax-admin.activity.warehouse.general',
  },
  activityAudiovisual: {
    id: 'avatax-admin.activity.audiovisual',
  },
  activityDistributionCenter: {
    id: 'avatax-admin.activity.distribution',
  },
  activityConstruction: {
    id: 'avatax-admin.activity.construction',
  },
  activityFinalConsumer: {
    id: 'avatax-admin.activity.consumer',
  },
  activityCoops: {
    id: 'avatax-admin.activity.coops',
  },
  activityFarmCoop: {
    id: 'avatax-admin.activity.farm.coop',
  },
  activityWarehouseBonded: {
    id: 'avatax-admin.activity.warehouse.bonded',
  },
  activityWarehouseStock: {
    id: 'avatax-admin.activity.warehouse.stock',
  },
  activityDistributor: {
    id: 'avatax-admin.activity.distributor',
  },
  activityDistributorWater: {
    id: 'avatax-admin.activity.distributor.water',
  },
  activityDistributorFuel: {
    id: 'avatax-admin.activity.distributor.fuel',
  },
  activityDistributorEletricity: {
    id: 'avatax-admin.activity.distributor.eletricity',
  },
  activityDistributorPharma: {
    id: 'avatax-admin.activity.distributor.pharma',
  },
  activityNonProfitEntity: {
    id: 'avatax-admin.activity.entity',
  },
  activityExtractor: {
    id: 'avatax-admin.activity.extractor',
  },
  activityArmed: {
    id: 'avatax-admin.activity.armed',
  },
  activityMeal: {
    id: 'avatax-admin.activity.meal',
  },
  activityEnergyGeneration: {
    id: 'avatax-admin.activity.generation',
  },
  activityImporter: {
    id: 'avatax-admin.activity.importer',
  },
  activityIndustry: {
    id: 'avatax-admin.activity.industry',
  },
  activityFilm: {
    id: 'avatax-admin.activity.film',
  },
  activityItaipu: {
    id: 'avatax-admin.activity.itaipu',
  },
  activityAuctioneer: {
    id: 'avatax-admin.activity.auctioneer',
  },
  activityPublicAgency: {
    id: 'avatax-admin.activity.agency',
  },
  activityRural: {
    id: 'avatax-admin.activity.rural',
  },
  activityBroadcasting: {
    id: 'avatax-admin.activity.broadcasting',
  },
  activityService: {
    id: 'avatax-admin.activity.service',
  },
  activityTelco: {
    id: 'avatax-admin.activity.telco',
  },
  activityMaritime: {
    id: 'avatax-admin.activity.maritime',
  },
  activityReligious: {
    id: 'avatax-admin.activity.religious',
  },
  activityTransporter: {
    id: 'avatax-admin.activity.transporter',
  },
  activityRetail: {
    id: 'avatax-admin.activity.retail',
  },
  taxRegimeLabel: {
    id: 'avatax-admin.tax.regime.label',
  },
  taxRegimeIndividual: {
    id: 'avatax-admin.tax.regime.individual',
  },
  taxRegimeProfitEstimated: {
    id: 'avatax-admin.tax.regime.profit.estimated',
  },
  taxRegimeProfitReal: {
    id: 'avatax-admin.tax.regime.profit.real',
  },
  taxRegimeSimplified: {
    id: 'avatax-admin.tax.regime.simplified',
  },
  taxRegimeSimplifiedGrossthreshold: {
    id: 'avatax-admin.tax.regime.simplified.grossthreshold',
  },
  taxRegimeSimplifiedEntrepreneur: {
    id: 'avatax-admin.tax.regime.simplified.entrepreneur',
  },
  taxRegimeNotApplicable: {
    id: 'avatax-admin.tax.regime.not.applicable',
  },
  entityTypeLabel: {
    id: 'avatax-admin.entity.type.label',
  },
  entityTypeMixedCapital: {
    id: 'avatax-admin.entity.type.mixed.capital',
  },
  entityTypeGovernment: {
    id: 'avatax-admin.entity.type.government',
  },
  entityTypeForeign: {
    id: 'avatax-admin.entity.type.foreign',
  },
  entityTypeFederal: {
    id: 'avatax-admin.entity.type.federal',
  },
  entityTypeIndividual: {
    id: 'avatax-admin.entity.type.individual',
  },
  entityTypeCity: {
    id: 'avatax-admin.entity.type.city',
  },
  entityTypeBusiness: {
    id: 'avatax-admin.entity.type.business',
  },
  stateTaxIdPlaceholder: {
    id: 'avatax-admin.state.tax.id.placeholder',
  },
  stateTaxIdLabel: {
    id: 'avatax-admin.state.tax.id.label',
  },
  streetPlaceholder: {
    id: 'avatax-admin.street.placeholder',
  },
  streetLabel: {
    id: 'avatax-admin.street.label',
  },
  neighborhoodPlaceholder: {
    id: 'avatax-admin.neighborhood.placeholder',
  },
  neighborhoodLabel: {
    id: 'avatax-admin.neighborhood.label',
  },
  zipCodePlaceholder: {
    id: 'avatax-admin.zipCode.placeholder',
  },
  zipCodeLabel: {
    id: 'avatax-admin.zipCode.label',
  },
  cityPlaceholder: {
    id: 'avatax-admin.city.placeholder',
  },
  cityLabel: {
    id: 'avatax-admin.city.label',
  },
  statePlaceholder: {
    id: 'avatax-admin.state.placeholder',
  },
  stateLabel: {
    id: 'avatax-admin.state.label',
  },
  streetNumberPlaceholder: {
    id: 'avatax-admin.street.number.placeholder',
  },
  streetNumberLabel: {
    id: 'avatax-admin.street.number.label',
  },
  complementPlaceholder: {
    id: 'avatax-admin.complement.placeholder',
  },
  complementLabel: {
    id: 'avatax-admin.complement.label',
  },
  phonePlaceholder: {
    id: 'avatax-admin.phone.placeholder',
  },
  phoneLabel: {
    id: 'avatax-admin.phone.label',
  },
  cnpjPlaceholder: {
    id: 'avatax-admin.cnpj.placeholder',
  },
  cnpjLabel: {
    id: 'avatax-admin.cnpj.label',
  },
  suframaPlaceholder: {
    id: 'avatax-admin.suframa.placeholder',
  },
  suframaLabel: {
    id: 'avatax-admin.suframa.label',
  },
})

export const logMessages = defineMessages({
  formCaption: {
    id: 'avatax-admin.logs-caption',
  },
  detailsCaption: {
    id: 'avatax-admin.logs-details-caption',
  },
  refreshButton: {
    id: 'avatax-admin.logs-refresh-button',
  },
  downloadButton: {
    id: 'avatax-admin.logs-download-button',
  },
  detailsButton: {
    id: 'avatax-admin.logs-details-button',
  },
  downloadRequestButton: {
    id: 'avatax-admin.logs-download-request-button',
  },
  orderFilterPlaceholder: {
    id: 'avatax-admin.logs-order-input-placeholder',
  },
  tableNoResults: {
    id: 'avatax-admin.logs-no-result',
  },
  tableFieldsCaption: {
    id: 'avatax-admin.logs-table-fields-caption',
  },
  tableColumnsShowAll: {
    id: 'avatax-admin.logs-table-show-all',
  },
  tableColumnsHideAll: {
    id: 'avatax-admin.logs-table-hide-all',
  },
  tableShowRows: {
    id: 'avatax-admin.logs-table-show-rows',
  },
  tableRowsOf: {
    id: 'avatax-admin.logs-table-rows-of',
  },
})

export const logTableSchemaMessages = defineMessages({
  details: {
    id: 'avatax-admin.logs-schema-details',
  },
  createdIn: {
    id: 'avatax-admin.logs-schema-createdIn',
  },
  client: {
    id: 'avatax-admin.logs-schema-client',
  },
  dockName: {
    id: 'avatax-admin.logs-schema-dockName',
  },
  city: {
    id: 'avatax-admin.logs-schema-city',
  },
  state: {
    id: 'avatax-admin.logs-schema-state',
  },
  activitySector: {
    id: 'avatax-admin.logs-schema-activitySector',
  },
  numberOfProducts: {
    id: 'avatax-admin.logs-schema-numberOfProducts',
  },
  productsTotal: {
    id: 'avatax-admin.logs-schema-productsTotal',
  },
  freightTotal: {
    id: 'avatax-admin.logs-schema-freightTotal',
  },
  includedTaxes: {
    id: 'avatax-admin.logs-schema-includedTaxes',
  },
  includedTaxesTotal: {
    id: 'avatax-admin.logs-schema-includedTaxesTotal',
  },
  addedTaxes: {
    id: 'avatax-admin.logs-schema-addedTaxes',
  },
  addedTaxesTotal: {
    id: 'avatax-admin.logs-schema-addedTaxesTotal',
  },
})

```


[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 avatax-br-admin/react/utils/omitTypename.ts from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const omitTypename = (key: string, value: unknown) => {
  return key === '__typename' ? undefined : 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 avatax-br-admin/react/hooks/setPagination.ts from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { ChangeEvent, useState } from 'react'

const INITIAL_PAGE_NUMBER = 1
const INITIAL_PER_PAGE = 5

function usePagination<T extends PaginationContext>(context: T) {
  const [pageNumber, setPageNumber] = useState(INITIAL_PAGE_NUMBER)
  const [perPage, setPerPage] = useState(INITIAL_PER_PAGE)
  const [total, setTotal] = useState(context.pagination?.total ?? 0)

  const resetPagination = () => {
    setPageNumber(INITIAL_PAGE_NUMBER)
    setPerPage(INITIAL_PER_PAGE)
  }

  const handleNext = async () => {
    const page = pageNumber + 1

    await context.setPage(page, perPage)
    setPageNumber(page)
  }

  const handlePrev = async () => {
    if (pageNumber <= 0) return
    const page = pageNumber - 1

    await context.setPage(page, perPage)
    setPageNumber(page)
  }

  const handlePerPageChange = async (e: ChangeEvent<HTMLInputElement>) => {
    const newPerPage = parseInt(e.target.value, 10)
    const result = await context.setPage(pageNumber, newPerPage)

    setPerPage(newPerPage)
    if (result) {
      setTotal(result.pagination.total)
    }
  }

  const from = perPage * (pageNumber - 1)
  const to = perPage * pageNumber

  return {
    pageNumber,
    perPage,
    resetPagination,
    total,
    setTotal: (nr: number) => setTotal(nr),
    pagination: {
      onNextClick: handleNext,
      onPrevClick: handlePrev,
      currentItemFrom: from,
      currentItemTo: to,
      onRowsChange: handlePerPageChange,
    },
  }
}

export default usePagination

```


[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 avatax-br-admin/react/utils/constants/activitySector.ts from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { MessageDescriptor } from 'react-intl'

import { values } from '../definedMessages'

export const activitySectors: { [key: string]: MessageDescriptor } = {
  armedForces: values.activityArmed,
  auctioneer: values.activityAuctioneer,
  audiovisualIndustry: values.activityAudiovisual,
  bondedWarehouse: values.activityWarehouseBonded,
  broadcastingIndustry: values.activityBroadcasting,
  construction: values.activityConstruction,
  coops: values.activityCoops,
  distributor: values.activityDistributor,
  distributionCenter: values.activityDistributionCenter,
  electricityDistributor: values.activityDistributorEletricity,
  energyGeneration: values.activityEnergyGeneration,
  extractor: values.activityExtractor,
  farmCoop: values.activityFarmCoop,
  filmIndustry: values.activityFilm,
  finalConsumer: values.activityFinalConsumer,
  fuelDistributor: values.activityDistributorFuel,
  generalWarehouse: values.activityWarehouseGeneral,
  importer: values.activityImporter,
  industry: values.activityIndustry,
  itaipubiNacional: values.activityItaipu,
  maritimeService: values.activityMaritime,
  mealSupplier: values.activityMeal,
  nonProfitEntity: values.activityNonProfitEntity,
  pharmaDistributor: values.activityDistributorPharma,
  publicAgency: values.activityPublicAgency,
  religiousEstablishment: values.activityReligious,
  retail: values.activityRetail,
  ruralProducer: values.activityRural,
  securityPublicAgency: values.activitySecurity,
  service: values.activityService,
  stockWarehouse: values.activityWarehouseStock,
  telco: values.activityTelco,
  transporter: values.activityTransporter,
  waterDistributor: values.activityDistributorWater,
  wholesale: values.activityWholesale,
}

```


[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 avatax-br-admin/react/components/Common/settings.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC } from 'react'

import Authentication from './authentication'
import { DividerArea } from './divider'
import Ping from './ping'
import Sandbox from './sandbox'
import ToggleArea from './toggle'

const Settings: FC = () => {
  return (
    <>
      <DividerArea />
      <ToggleArea />
      <DividerArea />
      <Sandbox />
      <DividerArea />
      <Authentication />
      <DividerArea />
      <Ping />
    </>
  )
}

export default Settings

```


[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 avatax-br-admin/react/components/Common/editArea.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { useIntl } from 'react-intl'
import React, { FC, useContext } from 'react'

import { DividerArea } from './divider'
import EstablishmentDropdown from '../Establishment/EstablishmentDropdown'
import EstablishmentInput from '../Establishment/EstablishmentInput'
import Values from './values'
import { stock } from '../../utils/definedMessages'
import EstablishmentContext from '../../context/EstablishmentContext'

const EditArea: FC = () => {
  const intl = useIntl()
  const allValues: Values = Values()
  const provider = useContext(EstablishmentContext)

  return (
    <>
      <div className="flex flex-column flex-row-ns">
        <div className="w-100">
          <h3 className="t-heading-3">{intl.formatMessage(stock.info)}</h3>

          <EstablishmentDropdown {...allValues.dockName} />
          <EstablishmentInput {...allValues.dockId} />

          <EstablishmentDropdown {...allValues.activitySector} />
          <EstablishmentDropdown {...allValues.icmsTaxPayer} />
          <EstablishmentDropdown {...allValues.taxRegime} />

          <EstablishmentDropdown {...allValues.entityType} />

          {provider.establishment.icmsTaxPayer === true && (
            <EstablishmentInput {...allValues.stateTaxId} />
          )}

          <DividerArea />

          <h3 className="t-heading-3">{intl.formatMessage(stock.place)}</h3>

          <EstablishmentInput {...allValues.zipCode} />
          <EstablishmentInput {...allValues.street} />
          <EstablishmentInput {...allValues.neighborhood} />
          <EstablishmentInput {...allValues.city} />
          <EstablishmentInput {...allValues.state} />
          <EstablishmentInput {...allValues.streetNumber} />
          <EstablishmentInput {...allValues.complement} />
          <EstablishmentInput {...allValues.phone} />
          <EstablishmentInput {...allValues.cnpj} />
          <EstablishmentInput {...allValues.suframa} />
        </div>
      </div>
    </>
  )
}

export default EditArea

```


[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 avatax-br-admin/react/components/Common/values.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { useQuery } from 'react-apollo'
import { MessageDescriptor, useIntl } from 'react-intl'

import { activitySectors } from '../../utils/constants/activitySector'
import { values } from '../../utils/definedMessages'
import getDocks from '../../queries/getDocks.gql'

export const dockIdValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'dockId',
    placeholder: formatMessage(values.dockIdPlaceholder),
    label: formatMessage(values.dockIdLabel),
  }
}

export const dockNameValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'dockName',
    placeholder: formatMessage(values.dockNamePlaceholder),
    label: formatMessage(values.dockNameLabel),
    options: [],
  }
}

export const activitySectorValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'activitySector',
    label: 'Setor de atividade',
    options: Object.entries(activitySectors)
      .map((obj) => {
        const [key, value] = obj

        return { value: key, label: formatMessage(value) }
      })
      .sort((a, b) => (a.label < b.label ? -1 : 1)),
  }
}

export const icmsTaxPayerValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'icmsTaxPayer',
    label: formatMessage(values.icmsLabel),
    options: [
      {
        value: true,
        label: formatMessage(values.icmsOptionsTrue),
      },
      {
        value: false,
        label: formatMessage(values.icmsOptionsFalse),
      },
    ],
  }
}

export const taxRegimeValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'taxRegime',
    label: formatMessage(values.taxRegimeLabel),
    options: [
      {
        value: 'individual',
        label: formatMessage(values.taxRegimeIndividual),
      },
      {
        value: 'estimatedProfit',
        label: formatMessage(values.taxRegimeProfitEstimated),
      },
      {
        value: 'realProfit',
        label: formatMessage(values.taxRegimeProfitReal),
      },
      {
        value: 'simplified',
        label: formatMessage(values.taxRegimeSimplified),
      },
      {
        value: 'simplifiedOverGrossthreshold',
        label: formatMessage(values.taxRegimeSimplifiedGrossthreshold),
      },
      {
        value: 'simplifiedEntrepreneur',
        label: formatMessage(values.taxRegimeSimplifiedEntrepreneur),
      },
      {
        value: 'notApplicable',
        label: formatMessage(values.taxRegimeNotApplicable),
      },
    ],
  }
}

export const entityTypeValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'entityType',
    label: formatMessage(values.entityTypeLabel),
    options: [
      {
        value: 'mixedCapital',
        label: formatMessage(values.entityTypeMixedCapital),
      },
      {
        value: 'stateGovernment',
        label: formatMessage(values.entityTypeGovernment),
      },
      {
        value: 'foreign',
        label: formatMessage(values.entityTypeForeign),
      },
      {
        value: 'federalGovernment',
        label: formatMessage(values.entityTypeFederal),
      },
      {
        value: 'individual',
        label: formatMessage(values.entityTypeIndividual),
      },
      {
        value: 'cityGovernment',
        label: formatMessage(values.entityTypeCity),
      },
      {
        value: 'business',
        label: formatMessage(values.entityTypeBusiness),
      },
    ],
  }
}

export const stateTaxIdValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'stateTaxId',
    placeholder: formatMessage(values.stateTaxIdPlaceholder),
    label: formatMessage(values.stateTaxIdLabel),
  }
}

export const streetValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'street',
    placeholder: formatMessage(values.streetPlaceholder),
    label: formatMessage(values.streetLabel),
  }
}

export const neighborhoodValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'neighborhood',
    placeholder: formatMessage(values.neighborhoodPlaceholder),
    label: formatMessage(values.neighborhoodLabel),
  }
}

export const zipCodeValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'zipCode',
    placeholder: formatMessage(values.zipCodePlaceholder),
    label: formatMessage(values.zipCodeLabel),
    type: 'number',
  }
}

export const cityValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'city',
    placeholder: formatMessage(values.cityPlaceholder),
    label: formatMessage(values.cityLabel),
  }
}

export const stateValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'state',
    placeholder: formatMessage(values.statePlaceholder),
    label: formatMessage(values.stateLabel),
    maxLength: 2,
  }
}

export const streetNumberValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'streetNumber',
    placeholder: formatMessage(values.streetNumberPlaceholder),
    label: formatMessage(values.streetNumberLabel),
    type: 'number',
  }
}

export const complementValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'complement',
    placeholder: formatMessage(values.complementPlaceholder),
    label: formatMessage(values.complementLabel),
  }
}

export const phoneValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'phone',
    placeholder: formatMessage(values.phonePlaceholder),
    label: formatMessage(values.phoneLabel),
  }
}

export const cnpjValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'cnpj',
    placeholder: formatMessage(values.cnpjPlaceholder),
    label: formatMessage(values.cnpjLabel),
    type: 'number',
  }
}

export const suframaValues = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    name: 'suframa',
    placeholder: formatMessage(values.suframaPlaceholder),
    label: formatMessage(values.suframaLabel),
  }
}

function Values() {
  const intl = useIntl()

  const dockId: {
    name: string
    placeholder: string
    label: string
  } = dockIdValues(intl.formatMessage)

  const dockName: {
    name: string
    placeholder: string
    label: string
    options: Array<{ value: string; label: string }>
  } = dockNameValues(intl.formatMessage)

  const icmsTaxPayer: {
    name: string
    label: string
    options: Array<{ value: boolean; label: string }>
  } = icmsTaxPayerValues(intl.formatMessage)

  const activitySector: {
    name: string
    label: string
    options: Array<{ value: string; label: string }>
  } = activitySectorValues(intl.formatMessage)

  const taxRegime: {
    name: string
    label: string
    options: Array<{ value: string; label: string }>
  } = taxRegimeValues(intl.formatMessage)

  const entityType: {
    name: string
    label: string
    options: Array<{ value: string; label: string }>
  } = entityTypeValues(intl.formatMessage)

  const stateTaxId: {
    name: string
    placeholder: string
    label: string
  } = stateTaxIdValues(intl.formatMessage)

  const street: {
    name: string
    placeholder: string
    label: string
  } = streetValues(intl.formatMessage)

  const neighborhood: {
    name: string
    placeholder: string
    label: string
  } = neighborhoodValues(intl.formatMessage)

  const zipCode: {
    name: string
    placeholder: string
    label: string
  } = zipCodeValues(intl.formatMessage)

  const city: {
    name: string
    placeholder: string
    label: string
  } = cityValues(intl.formatMessage)

  const state: {
    name: string
    placeholder: string
    label: string
  } = stateValues(intl.formatMessage)

  const streetNumber: {
    name: string
    placeholder: string
    label: string
  } = streetNumberValues(intl.formatMessage)

  const complement: {
    name: string
    placeholder: string
    label: string
  } = complementValues(intl.formatMessage)

  const phone: {
    name: string
    placeholder: string
    label: string
  } = phoneValues(intl.formatMessage)

  const cnpj: {
    name: string
    placeholder: string
    label: string
  } = cnpjValues(intl.formatMessage)

  const suframa: {
    name: string
    placeholder: string
    label: string
  } = suframaValues(intl.formatMessage)

  const { data: docks } = useQuery<GetDocks>(getDocks)

  const valueDocks = docks?.getDocks

  if (dockName.options.length === 0) {
    valueDocks?.forEach((element) => {
      dockName.options.push({
        value: element.name,
        label: element.name,
      })
    })
  }

  const allValues: Values = {
    dockId,
    dockName,
    icmsTaxPayer,
    activitySector,
    taxRegime,
    entityType,
    stateTaxId,
    street,
    neighborhood,
    zipCode,
    city,
    state,
    streetNumber,
    complement,
    phone,
    cnpj,
    suframa,
  }

  return allValues
}

export default Values

```


[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 avatax-br-admin/react/components/Common/authentication.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, SyntheticEvent, useContext } from 'react'
import { useIntl } from 'react-intl'
import { Input, InputPassword, Button } from 'vtex.styleguide'

import EstablishmentContext from '../../context/EstablishmentContext'
import { authentication } from '../../utils/definedMessages'

const Authentication: FC = () => {
  const provider = useContext(EstablishmentContext)

  const intl = useIntl()

  return (
    <>
      <div className="w-40">
        {' '}
        {intl.formatMessage(authentication.authentication)}
        <br />
        <br />
      </div>
      <div className="flex justify-center">
        <div className="flex flex-column w-100">
          <div className="mb5">
            <Input
              label={intl.formatMessage(authentication.clientId)}
              value={provider.settings.clientId}
              size="regular"
              readOnly={!provider.change}
              onChange={(event: any) => {
                provider.updateSettings({ clientId: event.target.value })
              }}
            />
          </div>
          <div className="mb5">
            <InputPassword
              label={intl.formatMessage(authentication.clientSecret)}
              value={provider.settings.clientSecret}
              size="regular"
              readOnly={!provider.change}
              onChange={(event: any) => {
                provider.updateSettings({ clientSecret: event.target.value })
              }}
            />
          </div>
        </div>
        <div className="flex flex-column  w-100 ">
          <span className="mt9 ml8">
            <Button
              onClick={(e: SyntheticEvent) => {
                e.preventDefault()
                provider.changeSettings()
              }}
            >
              {!provider.change
                ? intl.formatMessage(authentication.change)
                : intl.formatMessage(authentication.save)}
            </Button>
          </span>
        </div>
      </div>
    </>
  )
}

export default Authentication

```


[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 avatax-br-admin/react/components/Common/CurrentStock.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, useContext } from 'react'
import { useIntl } from 'react-intl'
import { Table } from 'vtex.styleguide'

import EstablishmentContext from '../../context/EstablishmentContext'
import { currentStock } from '../../utils/definedMessages'

const CurrentStock: FC = () => {
  const context = useContext(EstablishmentContext)

  const intl = useIntl()
  const defaultSchema = {
    properties: {
      id: {
        title: intl.formatMessage(currentStock.id),
      },
      dockName: {
        title: intl.formatMessage(currentStock.dockName),
      },
    },
  }

  const lineActions = [
    {
      label: () => intl.formatMessage(currentStock.edit),
      onClick: (data: { rowData: Establishment }) =>
        context.update(data.rowData),
    },
    {
      label: () => intl.formatMessage(currentStock.delete),
      isDangerous: true,
      onClick: (data: { rowData: Establishment }) =>
        context.deleteEstablishments(data.rowData.id),
    },
  ]

  if (context.loading)
    return <div>{intl.formatMessage(currentStock.loading)}</div>

  return (
    <>
      <div className="mb5">
        <Table
          fullWidth
          schema={defaultSchema}
          items={context.establishmentList}
          lineActions={lineActions}
        />
      </div>
    </>
  )
}

export default CurrentStock

```


[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 avatax-br-admin/react/components/Common/AddStock.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, useContext } from 'react'
import { useIntl } from 'react-intl'

import EstablishmentButtonAdd from '../Establishment/EstablishmentButtonAdd'
import { DividerArea } from './divider'
import EstablishmentDropdown from '../Establishment/EstablishmentDropdown'
import EstablishmentInput from '../Establishment/EstablishmentInput'
import Values from './values'
import { stock } from '../../utils/definedMessages'
import EstablishmentContext from '../../context/EstablishmentContext'

const AddStock: FC = () => {
  const intl = useIntl()
  const allValues: Values = Values()
  const provider = useContext(EstablishmentContext)

  return (
    <>
      <DividerArea />
      <h3 className="t-heading-3">{intl.formatMessage(stock.info)}</h3>

      <EstablishmentDropdown {...allValues.dockName} />
      <EstablishmentInput {...allValues.dockId} />

      <EstablishmentDropdown {...allValues.activitySector} />
      <EstablishmentDropdown {...allValues.icmsTaxPayer} />
      <EstablishmentDropdown {...allValues.taxRegime} />
      <EstablishmentDropdown {...allValues.entityType} />

      {provider.establishment.icmsTaxPayer === true && (
        <EstablishmentInput {...allValues.stateTaxId} />
      )}

      <DividerArea />

      <h3 className="t-heading-3">{intl.formatMessage(stock.place)}</h3>

      <EstablishmentInput {...allValues.zipCode} />
      <EstablishmentInput {...allValues.street} />
      <EstablishmentInput {...allValues.neighborhood} />
      <EstablishmentInput {...allValues.city} />
      <EstablishmentInput {...allValues.state} />

      <EstablishmentInput {...allValues.streetNumber} />
      <EstablishmentInput {...allValues.complement} />
      <EstablishmentInput {...allValues.phone} />
      <EstablishmentInput {...allValues.cnpj} />
      <EstablishmentInput {...allValues.suframa} />
      <EstablishmentButtonAdd />
    </>
  )
}

export default AddStock

```


[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 avatax-br-admin/react/components/Common/divider.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { Divider } from 'vtex.styleguide'

export const DividerArea = () => {
  return (
    <div className="mv6">
      <Divider orientation="horizontal" />
    </div>
  )
}

```


[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 avatax-br-admin/react/components/Common/ping.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, SyntheticEvent, useContext } from 'react'
import { useIntl } from 'react-intl'
import { Button } from 'vtex.styleguide'

import EstablishmentContext from '../../context/EstablishmentContext'
import { ping } from '../../utils/definedMessages'

const Ping: FC = () => {
  const provider = useContext(EstablishmentContext)

  const intl = useIntl()

  return (
    <>
      <div className="mt2 dib inline-flex">
        {intl.formatMessage(ping.verify)}
        <span
          className={
            provider.ping === 1
              ? 'active-c-success c-success ml2'
              : ' c-danger active-c-danger ml2'
          }
        >
          {provider.ping === 0
            ? ''
            : provider.ping === 1
            ? intl.formatMessage(ping.true)
            : intl.formatMessage(ping.false)}
        </span>
        <br />
        <br />
      </div>
      <div className="mb3">
        <Button
          onClick={(e: SyntheticEvent) => {
            e.preventDefault()
            provider.verifyPing()
          }}
        >
          {intl.formatMessage(ping.verifyButton)}
        </Button>
      </div>
    </>
  )
}

export default Ping

```


[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 avatax-br-admin/react/components/Common/sandbox.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, useContext } from 'react'
import { useIntl } from 'react-intl'
import { Checkbox } from 'vtex.styleguide'

import EstablishmentContext from '../../context/EstablishmentContext'
import { sandbox } from '../../utils/definedMessages'

const Sandbox: FC = () => {
  const provider = useContext(EstablishmentContext)

  const intl = useIntl()

  return (
    <>
      <div className="mt2 dib inline-flex">
        {intl.formatMessage(sandbox.environment)}

        <span
          className={
            provider.settings.sandbox
              ? 'c-warning active-c-warning ml2'
              : ' c-danger active-c-danger ml2'
          }
        >
          {provider.settings.sandbox
            ? intl.formatMessage(sandbox.sandbox)
            : intl.formatMessage(sandbox.production)}
        </span>
        <br />
        <br />
      </div>
      <div className="mb3">
        <Checkbox
          checked={provider.settings.sandbox}
          id="option-0"
          label={intl.formatMessage(sandbox.use)}
          name="default-checkbox-group"
          onChange={() =>
            provider.updateSettingsSandbox({
              sandbox: !provider.settings.sandbox,
            })
          }
          value="option-0"
        />
      </div>
    </>
  )
}

export default Sandbox

```


[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 avatax-br-admin/react/components/Common/toggle.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, useEffect, useState } from 'react'
import { useMutation, useQuery } from 'react-apollo'
import { Toggle } from 'vtex.styleguide'
import { useIntl } from 'react-intl'

import setTaxConfigurationMutation from '../../queries/setTaxConfiguration.gql'
import getTaxConfiguration from '../../queries/getTaxConfiguration.gql'
import { toggle } from '../../utils/definedMessages'

const ToggleArea: FC = () => {
  const intl = useIntl()

  const [initialState, setState] = useState(Boolean)

  const { data, loading } = useQuery<GetTaxConfiguration>(getTaxConfiguration)

  const [taxConfiguration] = useMutation<SetTaxConfiguration>(
    setTaxConfigurationMutation
  )

  useEffect(() => {
    setState(
      (data?.getTaxConfiguration?.url ?? '')
        .replace('master--', '')
        .includes(window.location.origin) ?? false
    )
  }, [data])

  if (loading)
    return <div className="dib">{intl.formatMessage(toggle.loading)}</div>

  const activateDeactivate = async () => {
    const operations = initialState ? 'deactivate' : 'activate'

    await taxConfiguration({ variables: { operation: operations } })

    setState(!initialState)
  }

  return (
    <>
      {intl.formatMessage(toggle.status)}
      <br />
      <br />
      <div className="dib">
        <Toggle
          label={
            initialState
              ? intl.formatMessage(toggle.activate)
              : intl.formatMessage(toggle.deactivate)
          }
          semantic
          checked={initialState}
          onChange={activateDeactivate}
        />
      </div>
    </>
  )
}

export default ToggleArea

```


[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 avatax-br-admin/react/components/Common/modal.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, useContext } from 'react'
import { useIntl } from 'react-intl'
import { Modal, Button } from 'vtex.styleguide'

import EstablishmentContext from '../../context/EstablishmentContext'
import { modal } from '../../utils/definedMessages'

const ModalArea: FC = (props) => {
  const context = useContext(EstablishmentContext)

  const intl = useIntl()

  async function save() {
    const showAlert = await context.saveConfigurations()

    if (showAlert) {
      alert(intl.formatMessage(modal.data))
    }
  }

  return (
    <Modal
      isOpen={context.edit}
      title={intl.formatMessage(modal.edit)}
      responsiveFullScreen
      bottomBar={
        <div className="nowrap">
          <span className="mr4">
            <Button variation="tertiary" onClick={() => context.setEdit(false)}>
              {intl.formatMessage(modal.cancel)}
            </Button>
          </span>
          <span>
            <Button
              variation="primary"
              onClick={() => {
                save()
              }}
            >
              {intl.formatMessage(modal.save)}
            </Button>
          </span>
        </div>
      }
      onClose={() => context.setEdit(false)}
    >
      {props.children}
    </Modal>
  )
}

export default ModalArea

```


[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 avatax-br-admin/react/components/Establishment/EstablishmentButtonAdd.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, useContext } from 'react'
import { useIntl } from 'react-intl'
import { Button, Alert } from 'vtex.styleguide'

import EstablishmentContext from '../../context/EstablishmentContext'
import { buttonAdd } from '../../utils/definedMessages'

const EstablishmentButtonAdd: FC = () => {
  const context = useContext(EstablishmentContext)

  const intl = useIntl()

  return (
    <>
      <div className="mb5">
        <span className="mr4">
          <Button
            variation="primary"
            size="large"
            onClick={() => context.saveConfigurations()}
          >
            {intl.formatMessage(buttonAdd.add)}
          </Button>
        </span>
      </div>
      {context.showAlert === true ? (
        <Alert type="success" onClose={context.handleCloseAlert}>
          {intl.formatMessage(buttonAdd.dataSave)}
        </Alert>
      ) : null}
    </>
  )
}

export default EstablishmentButtonAdd

```


[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 avatax-br-admin/react/components/Establishment/EstablishmentDropdown.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useContext, useState } from 'react'
import { Dropdown } from 'vtex.styleguide'

import EstablishmentContext from '../../context/EstablishmentContext'

interface Props {
  name: string
  label: string
  options: Array<{ value: string | boolean; label: string }>
}

function EstablishmentDropdown({ name, label, options }: Props) {
  const provider = useContext(EstablishmentContext)
  const [text, setText] = useState('')

  const validation = async (event: {
    target: { value?: string | boolean }
  }) => {
    const value = await provider.validationFuntion({
      [name]: event.target.value ?? '',
    })

    setText(value)
  }

  const updateValue = (event: { target: { value?: string | boolean } }) => {
    if (event.target.value === 'true')
      provider.setEstablishment({ [name]: true ?? '' })
    else if (event.target.value === 'false')
      provider.setEstablishment({ [name]: false ?? '' })
    else provider.setEstablishment({ [name]: event.target.value ?? '' })
    validation({ target: { value: event.target.value } })
  }

  if (provider.validationValues[name]) {
    validation({ target: { value: provider.establishment[name] } })
  }

  return (
    <div className="mb5">
      <Dropdown
        name={name}
        label={`${label}*`}
        placeholder={label}
        size="large"
        options={options}
        value={provider.establishment[name] ?? ''}
        onChange={updateValue}
      />
      <p className="mt2" style={{ color: 'red', fontSize: '12px' }}>
        {text}
      </p>
    </div>
  )
}

export default EstablishmentDropdown

```


[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 avatax-br-admin/react/components/Establishment/EstablishmentInput.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useContext, useState } from 'react'
import { Input } from 'vtex.styleguide'

import EstablishmentContext from '../../context/EstablishmentContext'

interface Props {
  name: string
  placeholder?: string
  label?: string
  type?: string
  maxLength?: number
}

function EstablishmentInput({
  name,
  placeholder,
  label,
  type = 'string',
  maxLength,
}: Props) {
  const provider = useContext(EstablishmentContext)
  const [text, setText] = useState('')

  const updateValue = (event: { target: { value?: string } }) => {
    provider.setEstablishment({ [name]: event.target.value ?? '' })
  }

  let required = label

  if (name !== 'suframa' && name !== 'phone') required = `${label}*`

  const validation = async (event: {
    target: { value?: string | boolean }
  }) => {
    const value = await provider.validationFuntion({
      [name]: event.target.value ?? '',
    })

    setText(value)
  }

  if (provider.validationValues[name]) {
    validation({ target: { value: provider.establishment[name] } })
  }

  return (
    <div className="mb3">
      <Input
        name={name}
        placeholder={placeholder}
        label={required}
        size="large"
        value={provider.establishment[name] ?? ''}
        onChange={updateValue}
        type={type}
        onBlur={validation}
        maxLength={maxLength}
      />
      <p className="mt2" style={{ color: 'red', fontSize: '12px' }}>
        {text}
      </p>
    </div>
  )
}

export default EstablishmentInput

```


[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 avatax-br-admin/react/components/Establishment/EstablishmentProvider.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable react-hooks/exhaustive-deps */
import React, { FC, useMemo, useState } from 'react'
import { useLazyQuery, useMutation, useQuery } from 'react-apollo'
import * as yup from 'yup'
import { useIntl } from 'react-intl'

import EstablishmentContext from '../../context/EstablishmentContext'
import getEstablishmentQuery from '../../queries/getEstablishment.gql'
import getSettingsQuery from '../../queries/getSettings.gql'
import deleteEstablishmentMutation from '../../queries/delete.gql'
import saveConfigurationMutation from '../../queries/saveConfiguration.gql'
import updateSettingsMutation from '../../queries/updateSettings.gql'
import verifyPingQuery from '../../queries/verifyPing.gql'
import getDocks from '../../queries/getDocks.gql'
import getAddress from '../../queries/getAddress.gql'
import { cnpjValidation } from './validCnpj'
import { provider } from '../../utils/definedMessages'

const EstablishmentProvider: FC = (props) => {
  const [establishment, setEstablishments] = useState<Establishment>({})
  const [edit, setEdit] = useState<boolean>(false)

  const [showAlert, setShowAlert] = useState(false)
  const [showAlertUpdate, setShowAlertUpdate] = useState(false)
  const [zip, setZip] = useState(false)
  const [settings, setSettings] = useState<Settings>({})
  const [change, setChange] = useState(false)
  const [ping, setPing] = useState(0)

  const [validationValues, setValidationValues] = useState({
    activitySector: false,
    icmsTaxPayer: false,
    taxRegime: false,
    entityType: false,
    stateTaxId: false,
    street: false,
    neighborhood: false,
    zipCode: false,
    city: false,
    state: false,
    streetNumber: false,
    complement: false,
    cnpj: false,
    suframa: false,
    dockId: false,
    dockName: false,
  })

  const intl = useIntl()
  const schema = yup.object().shape({
    activitySector: yup.string().required(),
    icmsTaxPayer: yup.boolean().required(),
    taxRegime: yup.string().required(),
    entityType: yup.string().required(),
    street: yup.string().required(),
    neighborhood: yup.string().required(),
    zipCode: yup
      .string()
      .required()
      .matches(/^[0-9]+$/, intl.formatMessage(provider.number))
      .length(8),
    city: yup.string().required(),
    state: yup.string().required(),
    streetNumber: yup.number().required().positive().integer(),
    complement: yup.string().required(),
    phone: yup.string().nullable(),
    cnpj: yup
      .string()
      .required()
      .matches(/^[0-9]+$/, intl.formatMessage(provider.number))
      .length(14),
    dockId: yup.string().required(),
    dockName: yup.string().required(),
    suframa: yup.string().nullable(),
    stateTaxId: yup.string().when('icmsTaxPayer', {
      is: true,
      then: yup.string().required(),
      otherwise: yup.string(),
    }),
  })

  // Return 1 if its ok, 2 if is null and 3 if cep is smaller than 3 caracteres
  async function validationFuntion(object: Establishment) {
    let text = ''

    for (const [key, value] of Object.entries(object)) {
      try {
        schema.validateSyncAt(key, object)
        if (key === 'cnpj') {
          const returnValue = cnpjValidation(value)

          if (!returnValue) text = intl.formatMessage(provider.cnpj)
        }

        if (key === 'stateTaxId' && value === '')
          text = 'Preencha o campo obrigatório'
      } catch (e) {
        if (
          key === 'zipCode' &&
          e.errors[0] === 'zipCode must be exactly 8 characters'
        )
          text = intl.formatMessage(provider.zipcode)
        else if (
          key === 'cnpj' &&
          e.errors[0] === 'cnpj must be exactly 14 characters'
        )
          text = intl.formatMessage(provider.cnpjLength)
        else text = intl.formatMessage(provider.empty)
      }
    }

    return text
  }

  const handleCloseAlert = () => {
    setShowAlert(false)
  }

  const { data: docks } = useQuery<GetDocks>(getDocks)

  const valueDocks = docks?.getDocks
  const setEstablishment = (object: Establishment) => {
    setEstablishments({
      ...establishment,
      ...object,
    })

    if (object.dockName && !object.dockId) {
      getDockId(object)
    }

    if (object.zipCode && !object.city) {
      getInfo(object)
    }
  }

  async function getDockId(object: Establishment) {
    valueDocks?.forEach((element) => {
      if (element.name === object.dockName) {
        setEstablishment({ dockName: object.dockName, dockId: element.id })
        setValidationValues({
          ...validationValues,
          ...{ dockId: true, dockName: true },
        })
      }
    })
  }

  const [gettingAddress] = useMutation(getAddress)

  async function getInfo(object: Establishment) {
    if (object.zipCode) {
      if (object.zipCode.length === 8) {
        setZip(false)
        const { zipCode } = object
        const valueReturn = await gettingAddress({ variables: { zipCode } })

        setEstablishment({
          city: valueReturn.data.getAddress.city,
          state: valueReturn.data.getAddress.state,
          street: valueReturn.data.getAddress.street,
          zipCode: object.zipCode,
        })
        setValidationValues({
          ...validationValues,
          ...{ city: true, state: true, street: true, zipCode: true },
        })
      } else {
        setZip(true)
      }
    }
  }

  const {
    loading,
    data: establishmentList,
    refetch,
  } = useQuery<GetEstablishment>(getEstablishmentQuery)

  const [deleteEstablishment] = useMutation(deleteEstablishmentMutation)

  const update = (establishmentUpdate: Establishment) => {
    setEstablishment(establishmentUpdate)
    setEdit(true)
  }

  const deleteEstablishments = async (documentId: string | boolean) => {
    await deleteEstablishment({ variables: { documentId } })
    refetch()
  }

  async function validation() {
    const object = establishment
    const retorno = await schema.validate(object).catch(function (err) {
      err.name // => 'ValidationError'
      err.errors // => ['Deve ser maior que 18']

      return false
    })

    return retorno
  }

  const [saveConfiguration] = useMutation(saveConfigurationMutation)

  const saveConfigurations = async () => {
    const valid = await validation()

    setValidationValues({
      activitySector: true,
      icmsTaxPayer: true,
      taxRegime: true,
      entityType: true,
      street: true,
      neighborhood: true,
      zipCode: true,
      city: true,
      state: true,
      streetNumber: true,
      complement: true,
      cnpj: true,
      suframa: true,
      dockId: true,
      dockName: true,
      stateTaxId: establishment.icmsTaxPayer === true,
    })

    if (valid) {
      const valueReturn = await saveConfiguration({
        variables: {
          esta: { ...establishment },
        },
      })

      setEdit(false)
      refetch()

      if (valueReturn.data.saveConfiguration) {
        setShowAlert(true)

        return true
      }
    }

    return false
  }

  // Settings

  const { data: settingsValues } = useQuery<GetSettings>(getSettingsQuery)

  const [updateSetting, { data: updateSettingsValues }] = useMutation(
    updateSettingsMutation
  )

  useMemo(() => {
    updateSettings({
      sandbox: settingsValues?.getSettings?.useAvalaraSandboxEnv,
      clientId: settingsValues?.getSettings.clientIdValue
        ? settingsValues?.getSettings.clientIdValue
        : '',
      clientSecret: settingsValues?.getSettings.clientSecretValue
        ? settingsValues?.getSettings.clientSecretValue
        : '',
    })
  }, [settingsValues])

  useMemo(() => {
    if (updateSettingsValues !== undefined) {
      updateSettings({
        sandbox: updateSettingsValues.updateSettings.useAvalaraSandboxEnv,
        clientId: updateSettingsValues.updateSettings.clientIdValue
          ? updateSettingsValues.updateSettings.clientIdValue
          : '',
        clientSecret: updateSettingsValues.updateSettings.clientSecretValue
          ? updateSettingsValues.updateSettings.clientSecretValue
          : '',
      })
    }
  }, [updateSettingsValues])

  function updateSettings(object: Settings) {
    setSettings({ ...settings, ...object })
  }

  async function updatingSettings() {
    const values = {
      useAvalaraSandboxEnv: settings.sandbox,
      clientIdValue: settings.clientId,
      clientSecretValue: settings.clientSecret,
    }

    setPing(0)

    await updateSetting({ variables: { settings: values } })
  }

  async function changeSettings() {
    if (!change) setChange(true)
    else {
      setChange(false)
      updatingSettings()
    }
  }

  async function updateSettingsSandbox(object: Settings) {
    updateSettings(object)

    const values = {
      useAvalaraSandboxEnv: !settings.sandbox,
      clientIdValue: settings.clientId,
      clientSecretValue: settings.clientSecret,
    }

    await updateSetting({ variables: { settings: values } })
  }

  const [getPing, { data: verifyPingValues }] = useLazyQuery(verifyPingQuery)

  useMemo(() => {
    if (verifyPingValues !== undefined) {
      if (verifyPingValues?.verifyPing !== '') {
        setPing(1)
      } else setPing(2)
    }
  }, [verifyPingValues])

  async function verifyPing() {
    getPing({
      variables: {
        clientId: settings.clientId,
        clientSecret: settings.clientSecret,
        sandbox: settings.sandbox,
      },
    })
  }

  return (
    <EstablishmentContext.Provider
      value={{
        establishment,
        setEstablishment,
        edit,
        setEdit,
        loading,
        establishmentList: establishmentList?.establishments,
        update,
        deleteEstablishments,
        saveConfigurations,
        showAlert,
        setShowAlert,
        handleCloseAlert,
        docks: docks?.getDocks,
        validationValues,
        zip,
        validationFuntion,
        showAlertUpdate,
        setShowAlertUpdate,
        settings,
        changeSettings,
        updateSettings,
        change,
        ping,
        verifyPing,
        updateSettingsSandbox,
      }}
    >
      {props.children}
    </EstablishmentContext.Provider>
  )
}

export default EstablishmentProvider

```


[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 avatax-br-admin/react/components/Establishment/validCnpj.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
export function cnpjValidation(value: any) {
  if (!value) return false

  const validTypes =
    typeof value === 'string' || Number.isInteger(value) || Array.isArray(value)

  if (!validTypes) return false

  const match = value.toString().match(/\d/g)
  const numbers = Array.isArray(match) ? match.map(Number) : []

  if (numbers.length !== 14) return false

  const items = [...new Set(numbers)]

  if (items.length === 1) return false

  const calc = (x: number) => {
    const slice = numbers.slice(0, x)
    let factor = x - 7
    let sum = 0

    for (let i = x; i >= 1; i--) {
      const n = slice[x - i]

      sum += n * factor--
      if (factor < 2) factor = 9
    }

    const result = 11 - (sum % 11)

    return result > 9 ? 0 : result
  }

  const digits = numbers.slice(12)

  const digit0 = calc(12)

  if (digit0 !== digits[0]) return false

  const digit1 = calc(13)

  return digit1 === digits[1]
}

```


[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 avatax-br-admin/react/components/Establishment/EstablishmentButtonSave.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, useContext } from 'react'
import { useIntl } from 'react-intl'
import { Button } from 'vtex.styleguide'

import EstablishmentContext from '../../context/EstablishmentContext'
import { buttonSave } from '../../utils/definedMessages'

const EstablishmentButtonSave: FC = () => {
  const context = useContext(EstablishmentContext)

  const intl = useIntl()

  return (
    <div className="mb5">
      <span className="mr4">
        <Button
          variation="primary"
          size="large"
          onClick={() => context.saveConfigurations()}
        >
          {intl.formatMessage(buttonSave.save)}
        </Button>
      </span>
    </div>
  )
}

export default EstablishmentButtonSave

```


[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 avatax-br-admin/react/components/Logs/LogForm.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { ChangeEvent, useContext, useEffect, useState } from 'react'
import { Table, ButtonWithIcon } from 'vtex.styleguide'
import FileSaver from 'file-saver'
import { useIntl } from 'react-intl'

import Refresh from '../../assets/icons/refresh.png'
import LogContext from '../../context/LogContext'
import { LogTableSchema } from './LogTableSchema'
import parseLogs from './logTableParser'
import usePagination from '../../hooks/setPagination'
import { logMessages } from '../../utils/definedMessages'

export const LogForm = () => {
  const intl = useIntl()
  const context = useContext(LogContext)
  const paginationContext = usePagination(context)
  const parsedLogs = context.logs
    ? context.logs.map(parseLogs(intl.formatMessage))
    : []

  const [searchTerm, setSearchTerm] = useState('')

  useEffect(() => {
    if (!context.loading) {
      paginationContext.setTotal(context.pagination?.total ?? 0)
    }
  }, [context.loading, context.pagination?.total, paginationContext])

  const exportLogs = () => {
    if (!context.logs) return
    const content = JSON.stringify(context.logs, null, 2)

    const blob = new Blob([content], {
      type: 'text/plain;charset=utf-8',
    })

    FileSaver.saveAs(
      blob,
      `logs_from-${paginationContext.pagination.currentItemFrom}-to-${paginationContext.pagination.currentItemTo}.json`
    )
  }

  return (
    <div className="mv6">
      <div className="flex justify-between">
        <div>{intl.formatMessage(logMessages.formCaption)}</div>
        <div className="mr2">
          <ButtonWithIcon
            onClick={() => context.refetch()}
            icon={
              <img
                src={Refresh}
                alt={intl.formatMessage(logMessages.refreshButton)}
              />
            }
            variation="tertiary"
          >
            <span className="c-on-base">
              {intl.formatMessage(logMessages.refreshButton)}
            </span>
          </ButtonWithIcon>
        </div>
      </div>
      <Table
        fullWidth
        emptyStateLabel={intl.formatMessage(logMessages.tableNoResults)}
        schema={LogTableSchema(intl.formatMessage)}
        items={parsedLogs}
        density="high"
        loading={context.loading || context.reloading}
        toolbar={{
          inputSearch: {
            value: searchTerm,
            placeholder: intl.formatMessage(logMessages.orderFilterPlaceholder),
            onChange: (e: ChangeEvent<HTMLInputElement>) =>
              setSearchTerm(e.target.value ?? ''),
            onClear: () => {
              paginationContext.resetPagination()
              context.setSearchTerm('')
            },
            onSubmit: (e: ChangeEvent<HTMLInputElement>) => {
              paginationContext.resetPagination()
              context.setSearchTerm(e.target.value ?? '')
            },
          },
          fields: {
            label: intl.formatMessage(logMessages.tableFieldsCaption),
            showAllLabel: intl.formatMessage(logMessages.tableColumnsShowAll),
            hideAllLabel: intl.formatMessage(logMessages.tableColumnsHideAll),
          },
          download: {
            label: intl.formatMessage(logMessages.downloadButton),
            handleCallback: exportLogs,
          },
        }}
        pagination={{
          onNextClick: paginationContext.pagination.onNextClick,
          onPrevClick: paginationContext.pagination.onPrevClick,
          onRowsChange: paginationContext.pagination.onRowsChange,
          currentItemFrom: paginationContext.pagination.currentItemFrom,
          currentItemTo: paginationContext.pagination.currentItemTo,
          textShowRows: intl.formatMessage(logMessages.tableShowRows),
          textOf: intl.formatMessage(logMessages.tableRowsOf),
          totalItems: paginationContext.total,
          rowsOptions: [5, 10, 15, 25],
        }}
      />
    </div>
  )
}

```


[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 avatax-br-admin/react/components/Logs/LogTableSchema.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { MessageDescriptor } from 'react-intl'

import { logTableSchemaMessages } from '../../utils/definedMessages'
import { LogViewButton } from './LogViewButton'

export const LogTableSchema = (
  formatMessage: (desc: MessageDescriptor) => string
) => {
  return {
    properties: {
      view: {
        title: formatMessage(logTableSchemaMessages.details),
        minWidth: 75,
        cellRenderer: ({ cellData }: { cellData: CalculationLog }) => {
          const logView = <LogViewButton {...cellData} />

          return logView
        },
      },
      createdIn: {
        title: formatMessage(logTableSchemaMessages.createdIn),
        minWidth: 160,
      },
      email: {
        title: formatMessage(logTableSchemaMessages.client),
        minWidth: 250,
      },
      establishment_dockName: {
        title: formatMessage(logTableSchemaMessages.dockName),
        minWidth: 120,
      },
      city: {
        title: formatMessage(logTableSchemaMessages.city),
        minWidth: 180,
      },
      state: {
        title: formatMessage(logTableSchemaMessages.state),
        minWidth: 75,
      },
      activitySector: {
        title: formatMessage(logTableSchemaMessages.activitySector),
        minWidth: 200,
      },
      numberOfProducts: {
        title: formatMessage(logTableSchemaMessages.numberOfProducts),
        minWidth: 70,
      },
      productsTotal: {
        title: formatMessage(logTableSchemaMessages.productsTotal),
        minWidth: 100,
      },
      freightTotal: {
        title: formatMessage(logTableSchemaMessages.freightTotal),
        minWidth: 100,
      },
      includedTaxes: {
        title: formatMessage(logTableSchemaMessages.includedTaxes),
        minWidth: 170,
      },
      includedTaxesTotal: {
        title: formatMessage(logTableSchemaMessages.includedTaxesTotal),
        minWidth: 140,
      },
      addedTaxes: {
        title: formatMessage(logTableSchemaMessages.addedTaxes),
        minWidth: 170,
      },
      addedTaxesTotal: {
        title: formatMessage(logTableSchemaMessages.addedTaxesTotal),
        minWidth: 140,
      },
    },
  }
}

```


[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 avatax-br-admin/react/components/Logs/LogProvider.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, useState } from 'react'
import { useQuery } from 'react-apollo'

import LogContext from '../../context/LogContext'
import getLogsQuery from '../../queries/getLogs.gql'

const LogProvider: FC<{ page: number; pageSize: number }> = (props: {
  children?: React.ReactNode
  page: number
  pageSize: number
}) => {
  const [reloading, setReloading] = useState(false)
  const [search, setSearch] = useState({
    page: props.page,
    pageSize: props.pageSize,
    searchTerm: '',
  })

  const { data, loading, refetch } = useQuery<
    CalculationLogQueryResult,
    { params: { page: number; pageSize: number; searchTerm?: string } }
  >(getLogsQuery, {
    variables: {
      params: {
        page: search.page,
        pageSize: search.pageSize,
        searchTerm: search.searchTerm,
      },
    },
  })

  const setPage = async (page: number, pageSize: number) => {
    setSearch({ ...search, page, pageSize })
  }

  const refetchFn = async () => {
    if (!data?.getLogs.pagination) return
    setReloading(true)
    await refetch({
      params: {
        page: data?.getLogs.pagination.page,
        pageSize: data?.getLogs.pagination.pageSize,
        searchTerm: search.searchTerm,
      },
    })
    setReloading(false)
  }

  return (
    <LogContext.Provider
      value={{
        loading,
        reloading,
        logs: data?.getLogs.data,
        pagination: data?.getLogs.pagination,
        setPage,
        refetch: refetchFn,
        searchTerm: search.searchTerm,
        setSearchTerm: (term?: string) => {
          if (search.searchTerm !== term) {
            setSearch({
              ...search,
              page: search.searchTerm !== term ? 1 : search.page,
              searchTerm: term ?? '',
            })
          }
        },
      }}
    >
      {props.children}
    </LogContext.Provider>
  )
}

export default LogProvider

```


[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 avatax-br-admin/react/components/Logs/LogViewButton.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useState } from 'react'
import { ButtonWithIcon, Modal } from 'vtex.styleguide'
import ReactJson from 'react-json-view'
import { useIntl } from 'react-intl'

import Info from '../../assets/icons/info.png'
import { omitTypename } from '../../utils/omitTypename'
import { logMessages } from '../../utils/definedMessages'
import { LogRequestDownloadButton } from './LogRequestDownloadButton'

export const LogViewButton = (cellData: CalculationLog) => {
  const intl = useIntl()
  const [isModalOpen, setIsModalOpen] = useState(false)

  const handleModalToggle = () => {
    setIsModalOpen(!isModalOpen)
  }

  return (
    <>
      <ButtonWithIcon
        icon={
          <img src={Info} alt={intl.formatMessage(logMessages.detailsButton)} />
        }
        variation="tertiary"
        onClick={() => setIsModalOpen(true)}
      />
      <Modal centered isOpen={isModalOpen} onClose={handleModalToggle}>
        <div className="flex flex-column mt4">
          <div className="flex justify-between mb4 items-center">
            <h2>{intl.formatMessage(logMessages.detailsCaption)}</h2>
            <LogRequestDownloadButton {...cellData} />
          </div>
          <ReactJson
            src={JSON.parse(
              JSON.stringify({
                ...cellData,
                payload: JSON.parse(cellData.payload, omitTypename),
              }),
              omitTypename
            )}
            iconStyle="square"
            displayDataTypes={false}
            name={false}
            displayObjectSize={false}
          />
        </div>
      </Modal>
    </>
  )
}

```


[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 avatax-br-admin/react/components/Logs/logTableParser.ts from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { MessageDescriptor } from 'react-intl'

import { activitySectors } from '../../utils/constants/activitySector'

const truncate = (input: string) =>
  input && input.length > 10 ? `${input.substring(0, 10)}...` : input

export const parse = (formatMessage: (desc: MessageDescriptor) => string) => (
  log: CalculationLog
) => {
  return {
    view: log,
    createdIn: new Date(log.createdIn).toLocaleDateString('pt-BR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false,
    }),
    email: log.email,
    activitySector: `${truncate(
      activitySectors[log.establishment.activitySector]
        ? formatMessage(activitySectors[log.establishment.activitySector])
        : log.establishment.activitySector
    )} → ${truncate(
      activitySectors[log.client.activitySector]
        ? formatMessage(activitySectors[log.client.activitySector])
        : log.client.activitySector
    )}`,
    establishment_dockName: log.establishment.dockName,
    city: `${log.establishment.city} → ${log.client.city}`,
    state: `${log.establishment.state} → ${log.client.state}`,
    numberOfProducts: log.avalaraReturn
      .map((item) => item.numberOfItems)
      .reduce((val1, val2) => val1 + val2, 0),
    productsTotal: log.avalaraReturn
      .map((item) => item.lineAmount)
      .reduce((val1, val2) => val1 + val2, 0)
      .toLocaleString('pt-BR', {
        style: 'currency',
        currency: 'BRL',
      }),
    freightTotal: log.avalaraReturn
      .map((item) => item.freightAmount)
      .reduce((val1, val2) => val1 + val2, 0)
      .toLocaleString('pt-BR', {
        style: 'currency',
        currency: 'BRL',
      }),
    includedTaxes: log.avalaraReturn
      .map((obj) =>
        obj.taxDetails
          .filter((tax) => tax.taxImpact.impactOnFinalPrice === 'Included')
          .map((tax) => tax.taxType)
      )
      .reduce((acc, tax) => acc.concat(tax), [])
      .filter((val, index, arr) => arr.indexOf(val) === index)
      .join(', '),
    includedTaxesTotal: log.avalaraReturn
      .map((obj) =>
        obj.taxDetails
          .filter((tax) => tax.taxImpact.impactOnFinalPrice === 'Included')
          .map((tax) => tax.tax)
      )
      .reduce((acc, tax) => acc.concat(tax), [])
      .reduce((val1, val2) => val1 + val2, 0)
      .toLocaleString('pt-BR', {
        style: 'currency',
        currency: 'BRL',
      }),
    addedTaxes: log.avalaraReturn
      .map((obj) =>
        obj.taxDetails
          .filter((tax) => tax.taxImpact.impactOnFinalPrice === 'Add')
          .map((tax) => tax.taxType)
      )
      .reduce((acc, tax) => acc.concat(tax), [])
      .filter((val, index, arr) => arr.indexOf(val) === index)
      .join(', '),
    addedTaxesTotal: log.avalaraReturn
      .map((obj) =>
        obj.taxDetails
          .filter((tax) => tax.taxImpact.impactOnFinalPrice === 'Add')
          .map((tax) => tax.tax)
      )
      .reduce((acc, tax) => acc.concat(tax), [])
      .reduce((val1, val2) => val1 + val2, 0)
      .toLocaleString('pt-BR', {
        style: 'currency',
        currency: 'BRL',
      }),
  }
}

export default parse

```


[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 avatax-br-admin/react/components/Logs/LogRequestDownloadButton.tsx from the avatax-br-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { ButtonWithIcon } from 'vtex.styleguide'
import FileSaver from 'file-saver'
import { useIntl } from 'react-intl'

import AvaralaIcon from '../../assets/icons/A-check_RGB.png'
import { omitTypename } from '../../utils/omitTypename'
import { logMessages } from '../../utils/definedMessages'

export const LogRequestDownloadButton = (cellData: CalculationLog) => {
  const intl = useIntl()
  const downloadRequest = () => {
    const content = JSON.stringify(
      JSON.parse(cellData.payload, omitTypename),
      null,
      2
    )

    const blob = new Blob([content], {
      type: 'text/plain;charset=utf-8',
    })

    FileSaver.saveAs(blob, `request_${cellData.createdIn}.json`)
  }

  return (
    <>
      <ButtonWithIcon
        icon={
          <img
            src={AvaralaIcon}
            alt={intl.formatMessage(logMessages.downloadRequestButton)}
          />
        }
        variation="secondary"
        onClick={downloadRequest}
      >
        {intl.formatMessage(logMessages.downloadRequestButton)}
      </ButtonWithIcon>
    </>
  )
}

```


[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 awin/docs/README.md from the awin VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Awin

Open the VTEX APP Store and install the app on your store.

or

Run the following command:

```sh
vtex install vtex.awin@0.x
```

Next, open the app settings on your admin and fill the form with <FIELDS>.

```


[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 awin/react/index.tsx from the awin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { canUseDOM } from 'vtex.render-runtime'

export function handleEvents(e: PixelMessage) {
  switch (e.data.eventName) {
    case 'vtex:pageView': {

    }
    default: {
      return
    }
  }
}

if (canUseDOM) {
  window.addEventListener('message', handleEvents)
}

```


[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 awin/react/package.json from the awin VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "dependencies": {
    "ramda": "^0.26.1"
  },
  "devDependencies": {
    "@types/graphql": "^14.2.0",
    "@types/jest": "^24.0.11",
    "@types/node": "^11.13.0",
    "@types/ramda": "^0.26.5",
    "@vtex/test-tools": "^1.1.0",
    "eslint": "^5.16.0",
    "eslint-config-vtex-react": "^4.1.0",
    "prettier": "^1.18.2",
    "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 awin/store/interfaces.json from the awin VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "pixel.APPNAME": {
    "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 awin/react/typings/events.d.ts from the awin VTEX app.

[Assistant]
Here's the implementation:

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

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 AddToCartData extends EventData {
  event: 'addToCart'
  eventName: 'vtex:addToCart'
  items: CartItem[]
}

export interface RemoveToCartData extends EventData {
  event: 'removeFromCart'
  eventName: 'vtex:removeFromCart'
  items: CartItem[]
}

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'
  impressions: Impression[]
  product?: Product // deprecated, use impressions list!
  position?: number // deprecated, use impressions list!
  list: string
}

interface CartItem {
  skuId: string
  variant: string
  price: number
  name: string
  quantity: number
  productRefId: string
  brand: string
  category: string
}

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

export interface Impression {
  product: Product
  position: number
}

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
  productRefId: string
  ean: string
  slug: string
  brand: string
  brandId: string
  seller: string
  sellerId: string
  category: string
  categoryId: string
  categoryTree: string[]
  categoryIdTree: string[]
  priceTags: PriceTag[]
  originalPrice: number
  price: number
  sellingPrice: number
  tax: number
  quantity: number
  components: any[]
  measurementUnit: string
  unitMultiplier: number
}

interface PriceTag {
  identifier: string
  isPercentual: boolean
  value: number
}

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
  [key: string]: any
}

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

```


[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 awin/react/typings/vtex.render-runtime.d.ts from the awin 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 awin/react/typings/global.d.ts from the awin VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface Window extends Window {
  dataLayer: any[]
}

```


[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 slider/docs/README.md from the slider VTEX app.

[Assistant]
Here's the implementation:

```markdown
# VTEX Slider

## Description

The VTEX Slider is a slider that aims a good support for SSR and can display one or more slides per page.

:loudspeaker: **Disclaimer:** Don't fork this project; use, contribute, or open issue with your feature request

## Table of Contents
- [Usage](#usage)
  - [Configuration](#configuration)
    - [Slider](#slider)
    - [Slide](#slide)
    - [SliderContainer](#slidercontainer)
    - [Dots](#dots)
  - [Styles API](#styles-api)
    - [CSS namespaces](#css-namespaces)
- [Tests](#tests)

## Usage

To import it you can add to you `manifest.json` the following:

```json
{
  "dependencies": {
    "vtex.slider": "0.x"
  }
}
```

And then in your component you can import the components exported from the slider:

```javascript
import { Slider, Slide } from 'vtex.slider'
```

You can use it in your code like a React component with the jsx tags:

```javascript

handleChangeSlide = i => {
  this.setState({ currentSlide: i })
}

render() {
  const { currentSlide } = this.state
  // ...

  const { myProducts } = this.props

  return (
    <Slider currentSlide={currentSlide} onChangeSlide={this.handleChangeSlide}>
      {myProducts.map(product => (
        <Slide key={product.id}>
          <DisplayProductComponent product={product} />
        </Slide>
      ))}
    </Slider>
  )
}

```

If you want to show multiple items in the same page at the same time you can use the prop `perPage`:

```javascript
render() {
  const { currentSlide } = this.state
  const { myProducts } = this.props

  // The keys of the object represent the size of the window in px.
  // In this case if the window is 1300px large or bigger it will show 5 items,
  // If it has 900px or any size until 1299px it will show 4 items
  const perPage = {
    1300: 5,
    900: 4,
    700: 2,
    600: 1,
  }

  return (
    <Slider
      currentSlide={currentSlide}
      onChangeSlide={this.handleChangeSlide}
      perPage={perPage}
    >
      {myProducts.map(product => (
        <Slide key={product.id}>
          <DisplayProductComponent product={product} />
        </Slide>
      ))}
    </Slider>
  )
}
```

Bellow is an example with all the components together:

```javascript
arrowRender = ({ orientation, onClick }) => {
  return (
    <div className="arrow-container-class" onClick={onClick}>
      <MyArrowComponent orientation={orientation} />
    </div>
  )
}

arrowContainerRender = ({ children }) => {
  return (
    <MyContainerComponent>
      {children}
    </MyContainerComponent>
  )
}

render() {
  const { currentSlide } = this.state
  const { myProducts } = this.props

  const perPage = {
    1300: 5,
    1100: 4,
    900: 3,
    700: 2,
    300: 1
  }

  return (
    <SliderContainer className="mw9">
      <Slider
        loop
        easing="ease"
        duration={500}
        perPage={perPage}
        currentSlide={currentSlide}
        arrowRender={this.arrowRender}
        onChangeSlide={this.handleChangeSlide}
        arrowsContainerComponent={this.arrowContainerRender}
      >
        {myProducts.map(product => (
          <Slide
            className="slide-css-class"
            sliderTransitionDuration={500}
            key={product.id}
            defaultWidth={280}
          >
            <ProductComponent product={product} />
          </Slide>
        ))}
      </Slider>
      <Dots
        loop
        showDotsPerPage
        perPage={this.perPage}
        currentSlide={currentSlide}
        totalSlides={myProducts.length}
        onChangeSlide={this.handleChangeSlide}
        classes={{
          root: 'pv4',
          notActiveDot: 'bg-muted-3',
          dot: 'dot pointer br-100',
          activeDot: 'bg-emphasis'
        }}
      />
    </SliderContainer>
  )
}
```

### Configuration

#### Slider

| Prop name | Type | isRequired | defaultValue | Description |
| --- | --- | --- | --- | -- |
| `arrowRender` | `func` | :no_entry_sign: | :no_entry_sign: | A render function that will receive as props an orientation prop and an onClick callback |
| `arrowsContainerComponent` | `func/string` | :no_entry_sign: | :no_entry_sign: | The component used to contain both arrows. Either a string to use a DOM element or a component |
| `children` | `element/array` | :heavy_check_mark: | :no_entry_sign: | The slides to render |
| `classes` | `object` | :no_entry_sign: | No extra classes applied to any element | Classes to apply to the Slider elements |
| `currentSlide` | `number` | :no_entry_sign: | `0` | Current slide on the screen, if you have perPage > 1, then the current slide is the most left slide on the screen (You should not use this variable to display the index of the slide on the screen if you're using `loop={true}`). |
| `cursor` | `string` | :no_entry_sign: | `'-webkit-grab'` | Css value of cursor when mouse is hovering the slider frame |
| `cursorOnMouseDown` | `string` | :no_entry_sign: | `'-webkit-grabbing'` | Css value of cursor when mouse is down |
| `duration` | `number` | :no_entry_sign: | `250` | Duration of transitions |
| `easing` | `string` | :no_entry_sign: | `'ease-out'` | Transition function |
| `loop` | `bool` | :no_entry_sign: | `false` | If the slides should be looping |
| `onChangeSlide` | `func` | :heavy_check_mark: | :no_entry_sign: | Function to change the value of currentSlide. The function should expect a `number` as it's only parameter |
| `perPage` | `number/object` | :no_entry_sign: | `1` | Amount of slides to be on the screen, if a number is passed, then that's the number of slides that will be shown, if an object with breakpoints is passed, then the component will check the size of the screen to see how many slides will be on the screen at the same time |
| `minPerPage` | `number` | :no_entry_sign: | `1` | Minimum amount of slides to be on the screen, can be used to control how many itens will be displayed in the smallest screen size |
| `resizeDebounce` | `number` | :no_entry_sign: | `250` | Resize debounce timer in milliseconds |
| `rootTag` | `string` | :no_entry_sign: | `'div'` | Tag to be rendered in the root of the slider |
| `sliderFrameTag` | `string` | :no_entry_sign: | `'ul'` | Tag to be rendered in the slider frame element |
| `threshold` | `number` | :no_entry_sign: | `50` | Minimum of pixels to drag until the slider change the `currentSlide` |
| `navigationStep`| `number` | `'page'` | :no_entry_sign: | `'page'` | How many elements should pass when you click in the arrows to navigate |

#### Slide

| Prop name | Type | isRequired | defaultValue | Description |
| --- | --- | --- | --- | --- |
| `children` | `node` | :heavy_check_mark: | :no_entry_sign: | Node to render |
| `className` | `string` | :no_entry_sign: | :no_entry_sign: | Classes to pass to the root element of the Slide |
| `defaultWidth` | `number` | :no_entry_sign: | :no_entry_sign: | Default width of the slide (only applied in the first render) |
| `tag` | `string` | :no_entry_sign: | `li` | Tag to be rendered in the root element |
| `fitImg` | `bool` | :no_entry_sign: | `true` | If the slide component should try to fit the `img` (only works if children is an `img` element) |
| `resizeDebounce` | `number` | :no_entry_sign: | `250` | Time of debounce of resize event listener |
| `sliderTransitionDuration` | `number` | :no_entry_sign: | `250` | Duration of transition passed to Slider (must be the same), if nothing is passed to any of the components it will apply the same default value |

#### SliderContainer

| Prop name | Type | isRequired | defaultValue | Description |
| --- | --- | --- | --- | --- |
| `autoplay` | `bool` | :no_entry_sign: | `false` | If the slider should be passing automatically |
| `autoplayInterval` | `number` | :no_entry_sign: | `5000` | Time in milliseconds of the interval to change the currentSlider |
| `children` | `node` | :heavy_check_mark: | :no_entry_sign: | Children of the component to render |
| `className` | `string` | :no_entry_sign: | :no_entry_sign: | Classes to be applied to the root element |
| `onNextSlide` | `func` | :no_entry_sign: | :no_entry_sign: | Function to be called if `autoplay={true}` |
| `pauseOnHover` | `bool` | :no_entry_sign: | `true` | If the interval should not be executed when the mouse is hovering the component |
| `tag` | `string` | :no_entry_sign: | `'div'` | Tag to render the component |

#### Dots

| Prop name | Type | isRequired | defaultValue | Description |
| --- | --- | --- | --- | --- |
| `classes` | `object` | :no_entry_sign: | No extra classes applied to any element | Classes to style the elements of the component |
| `dotProps` | `object` | :no_entry_sign: | :no_entry_sign: | Extra props to be applied to the dot element |
| `dotSize` | `number/string` | :no_entry_sign: | :no_entry_sign: | The size of the dots, can be a number (in this case it will use px unit), or a string (you have to pass the number with the unit e.g `'3rem'`) |
| `dotTag` | `string` | :no_entry_sign: | `'li'` | Tag to be rendered in the dot element |
| `loop` | `bool` | :no_entry_sign: | `false` | If the slides should be looping |
| `onChangeSlide` | `func` | :heavy_check_mark: | :no_entry_sign: | Function to change the currentSlide |
| `perPage` | `number/object` | :no_entry_sign: | `1` | This prop works the same way the `perPage` of `Slider` and this component should receive the same value of `Slider` |
| `resizeDebounce` | `number` | :no_entry_sign: | `250` | Debounce time in milliseconds |
| `rootTag` | `string` | :no_entry_sign: | `'ul'` | Tag to be rendered as the root element of the component |
| `totalSlides` | `number` | :heavy_check_mark: | :no_entry_sign: | Total value of sliders that will be rendered |
| `minPerPage` | `number` | :no_entry_sign: | `1` | This prop works the same way the `minPerPage` of `Slider` and this component should receive the same value of `Slider` |
| `showDotsPerPage` | `bool` | :no_entry_sign: | `false` | If this frag is true, then every dot represent a page of slides (e.g. if `perPage = 2` and you have 4 elements, then you have 2 dots), if false, then it will render one dot to each slide |

## Styles API

You can style this app by using the props `classeName` and `classes` of the components. But if you want to style every slider of your app you need to use the [CSS namespaces](#css-namespaces) to do it.

### CSS namespaces

:construction: :construction: :construction:

## Tests

[![Coverage Status](https://coveralls.io/repos/github/vtex-apps/slider/badge.svg?branch=master)](https://coveralls.io/github/vtex-apps/slider?branch=master)

## Travis CI

[![Build Status](https://travis-ci.org/vtex-apps/slider.svg?branch=master)](https://travis-ci.org/vtex-apps/slider)

```


[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 slider/react/resolveSlidesNumber.js from the slider VTEX app.

[Assistant]
Here's the implementation:

```javascript
import resolveSlidesNumber from './utils/resolveSlidesNumber'

export default resolveSlidesNumber

```


[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 slider/react/Dots.js from the slider VTEX app.

[Assistant]
Here's the implementation:

```javascript
import Dots from './components/Dots'

export default Dots

```


[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 slider/react/Slide.js from the slider VTEX app.

[Assistant]
Here's the implementation:

```javascript
import Slide from './components/Slide'

export default Slide

```


[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 slider/react/package.json from the slider VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "vtex.slider",
  "version": "0.8.3",
  "description": "A React Slider component that works well in SPA and SSR",
  "files": [
    "react"
  ],
  "scripts": {
    "pretest": "yarn",
    "test": "vtex-test-tools test",
    "test:watch": "vtex-test-tools test --watch",
    "test:coverage": "vtex-test-tools test --collectCoverage",
    "gen:coveralls": "yarn test:coverage && cat ./coverage/lcov.info | coveralls"
  },
  "dependencies": {
    "classnames": "^2.2.6",
    "debounce": "^1.2.0",
    "prop-types": "^15.6.2",
    "ramda": "^0.26.1",
    "react": "^16.6.3",
    "react-event-listener": "^0.6.5"
  },
  "devDependencies": {
    "@vtex/test-tools": "^0.2.0",
    "coveralls": "^3.0.3",
    "eslint": "^5.15.3",
    "eslint-config-vtex-react": "^4.0.0",
    "jsdom": "^14.0.0",
    "prettier": "^1.16.4",
    "typescript": "3.9.7"
  }
}

```