[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 pharma-orders-admin/react/utils/intl.ts from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

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

const prefix = 'admin/admin.app.pharma-orders.'

export const titlesIntl = defineMessages({
  textOf: { id: `${prefix}textOf` },
  textShowRows: { id: `${prefix}textShowRows` },
  filterClear: { id: `${prefix}filterClear` },
  filterAll: { id: `${prefix}filterAll` },
  filterNone: { id: `${prefix}filterNone` },
  filterAny: { id: `${prefix}filterAny` },
  filterIs: { id: `${prefix}filterIs` },
  filterIsNot: { id: `${prefix}filterIsNot` },
  filterContains: { id: `${prefix}filterContains` },
  filterApply: { id: `${prefix}filterApply` },
  ordersTableOrderId: { id: `${prefix}ordersTableOrderId` },
  ordersTableStatus: { id: `${prefix}ordersTableStatus` },
  ordersTableProducts: { id: `${prefix}ordersTableProducts` },
  ordersTableFiles: { id: `${prefix}ordersTableFiles` },
  selectedOrders: { id: `${prefix}selectedOrders` },
  selectAllOrders: { id: `${prefix}selectAllOrders` },
  pageTitle: { id: `${prefix}pageTitle` },
  approve: { id: `${prefix}approve` },
  confirm: { id: `${prefix}confirm` },
  cancel: { id: `${prefix}cancel` },
  buttonShowProducts: { id: `${prefix}buttonShowProducts` },
  buttonShowFiles: { id: `${prefix}buttonShowFiles` },
  productTableProductId: { id: `${prefix}productTableProductId` },
  productTableQuantity: { id: `${prefix}productTableQuantity` },
  productTableName: { id: `${prefix}productTableName` },
  prescription: { id: `${prefix}prescription` },
  withoutPrescription: { id: `${prefix}withoutPrescription` },
  theOrder: { id: `${prefix}theOrder` },
  wasCanceled: { id: `${prefix}wasCanceled` },
  wasNotCanceled: { id: `${prefix}wasNotCanceled` },
  wasAlreadyCanceled: { id: `${prefix}wasAlreadyCanceled` },
  canceled: { id: `${prefix}canceled` },
  created: { id: `${prefix}created` },
  approved: { id: `${prefix}approved` },
  confirmed: { id: `${prefix}confirmed` },
  wasApproved: { id: `${prefix}wasApproved` },
  wasNotApproved: { id: `${prefix}wasNotApproved` },
  wasAlreadyApproved: { id: `${prefix}wasAlreadyApproved` },
  wasConfirmed: { id: `${prefix}wasConfirmed` },
  isConfirmed: { id: `${prefix}isConfirmed` },
  wasNotConfirmed: { id: `${prefix}wasNotConfirmed` },
  wasAlreadyConfirmed: { id: `${prefix}wasAlreadyConfirmed` },
  approvedBeforeConfirming: { id: `${prefix}approvedBeforeConfirming` },
  isCanceled: { id: `${prefix}isCanceled` },
  noOrdersYet: { id: `${prefix}noOrdersYet` },
  invoiceNumber: { id: `${prefix}invoiceNumber` },
  placeholderInvoiceNumber: { id: `${prefix}placeholderInvoiceNumber` },
  noInvoiceNumber: { id: `${prefix}noInvoiceNumber` },
})

```


[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 pharma-orders-admin/react/style/Alert.global.css from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```css
.success-container {
  max-width: 1200px;
  margin: 20px auto;
}

.error-container {
  max-width: 1200px;
  margin: 20px auto;
  max-height: 8rem;
  overflow-y: scroll;
  scroll-behavior: smooth;
}

.error-container::-webkit-scrollbar {
  display: none;
}

```


[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 pharma-orders-admin/react/style/ImagePreview.global.css from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```css
.magnifier-image {
  display: block;
}

.magnifier {
  width: inherit !important;
}

.wrapMagnifier {
  display: flex;
  justify-content: center;
}

```


[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 pharma-orders-admin/react/style/Loading.global.css from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```css
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

```


[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 pharma-orders-admin/react/components/SuccessMessage.tsx from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import '../style/Alert.global.css'

import React from 'react'
import { Alert } from 'vtex.styleguide'

export default function SuccessMessage({ message, onClose }: SuccessComponent) {
  return (
    <div className="success-container">
      <Alert type="success" onClose={onClose}>
        {message}
      </Alert>
    </div>
  )
}

export function SuccessArrayMessage({
  messages,
  onClose,
}: SuccessArrayComponent) {
  return (
    <div className="success-container">
      <Alert type="success" onClose={onClose}>
        <div>
          {messages.map((message: string, index: number) => (
            <p className="ma0" key={index}>
              {message}
            </p>
          ))}
        </div>
      </Alert>
    </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 pharma-orders-admin/react/components/ErrorMessage.tsx from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import '../style/Alert.global.css'

import React from 'react'
import { Alert } from 'vtex.styleguide'

export function ErrorMessage({ message, onClose }: ErrorComponent) {
  return (
    <div className="error-container">
      <Alert type="error" onClose={onClose}>
        {message}
      </Alert>
    </div>
  )
}

export function ErrorArrayMessage({ messages, onClose }: ErrorArrayComponent) {
  return (
    <div className="error-container">
      <Alert type="error" onClose={onClose}>
        <div>
          {messages.map((message: string, index: number) => (
            <p className="ma0" key={index}>
              {message}
            </p>
          ))}
        </div>
      </Alert>
    </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 pharma-orders-admin/react/components/ProductsTable.tsx from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { EXPERIMENTAL_Table as Table } from 'vtex.styleguide'
import useTableMeasures from '@vtex/styleguide/lib/EXPERIMENTAL_Table/hooks/useTableMeasures'
import { useQuery } from 'react-apollo'
import { useIntl } from 'react-intl'

import getOrderItems from '../graphql/getOrderItems.gql'
import LoadingSpinner from './LoadingSpinner'
import { titlesIntl } from '../utils/intl'

export default function ProductsTable({ orderId }: ProductTableProps) {
  const intl = useIntl()

  const responseFromGetOrder = useQuery(getOrderItems, {
    variables: { orderId },
    ssr: false,
  })

  const items = responseFromGetOrder?.data?.getOrder?.data?.items

  const columns = [
    {
      id: 'productId',
      title: intl.formatMessage(titlesIntl.productTableProductId),
    },
    {
      id: 'quantity',
      title: intl.formatMessage(titlesIntl.productTableQuantity),
    },
    {
      id: 'name',
      title: intl.formatMessage(titlesIntl.productTableName),
    },
  ]

  const measures = useTableMeasures({ size: items?.length })

  return (
    <div className="mt7">
      {!items && <LoadingSpinner />}
      {items && (
        <Table
          measures={measures}
          items={items}
          columns={columns}
          highlightOnHover
        />
      )}
    </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 pharma-orders-admin/react/components/FilesColumn.tsx from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState } from 'react'
import { useQuery } from 'react-apollo'
import { ButtonWithIcon, Modal, Tag } from 'vtex.styleguide'
import Image from '@vtex/styleguide/lib/icon/Image'
import { useIntl } from 'react-intl'

import { titlesIntl } from '../utils/intl'
import getOrderCustomData from '../graphql/getOrderCustomData.gql'
import ImagePreview from './ImagePreview'

export default function FilesTable({ orderId }: ProductTableProps) {
  const intl = useIntl()

  const responseFromGetOrder = useQuery(getOrderCustomData, {
    variables: { orderId },
    ssr: false,
  })

  const customApps =
    responseFromGetOrder?.data?.getOrder?.data?.customData?.customApps

  const files = customApps?.find((app: any) => app.id === 'uploadfiles')?.fields
    .data

  const filesObject = files && JSON.parse(files.replace(/'/g, '"'))

  const [isImagenPreviewModalOpen, setIsImagenPreviewModalOpen] =
    useState(false)

  const [fileUrlPreview, setfileUrlPreview] = useState('')

  const handleModalImagenPreviewToggle = () => {
    setIsImagenPreviewModalOpen(!isImagenPreviewModalOpen)
  }

  function handleOnClick(url: string) {
    setfileUrlPreview(url)
    handleModalImagenPreviewToggle()
  }

  const icon = <Image />
  const withoutPrescription = intl.formatMessage(titlesIntl.withoutPrescription)

  return (
    <div>
      {(!filesObject || filesObject.length === 0) && (
        <Tag color="#134CD8" variation="low">
          {withoutPrescription}
        </Tag>
      )}
      {filesObject && (
        <div>
          {filesObject.map((file: any, index: number) => (
            <span className="mr3" key={`${file.name} ${index}`}>
              <ButtonWithIcon
                icon={icon}
                variation="secondary"
                size="small"
                onClick={() => handleOnClick(file.url)}
              >
                {`${intl.formatMessage(titlesIntl.prescription)} ${index + 1}`}
              </ButtonWithIcon>
            </span>
          ))}
        </div>
      )}
      <Modal
        centered
        isOpen={isImagenPreviewModalOpen}
        onClose={handleModalImagenPreviewToggle}
      >
        <ImagePreview url={fileUrlPreview} />
      </Modal>
    </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 pharma-orders-admin/react/components/ImagePreview.tsx from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import React from 'react'
import Magnifier from 'react-magnifier'
import '../style/ImagePreview.global.css'

export default function ImagePreview({ url }: ImagePreviewProps) {
  return (
    <div className="wrapMagnifier">
      <Magnifier src={url} />
    </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 pharma-orders-admin/react/components/LoadingSpinner.tsx from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { Spinner } from 'vtex.styleguide'
import React from 'react'
import '../style/Loading.global.css'

export default function LoadingSpinner() {
  return (
    <div className="loading-container">
      <Spinner />
    </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 pharma-orders-admin/react/components/OrdersTable.tsx from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable react/jsx-handler-names */
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
  EXPERIMENTAL_Table as Table,
  Checkbox,
  Input,
  Button,
  Modal,
  Tag,
} from 'vtex.styleguide'
import useTableMeasures from '@vtex/styleguide/lib/EXPERIMENTAL_Table/hooks/useTableMeasures'
import useCheckboxTree from '@vtex/styleguide/lib/EXPERIMENTAL_useCheckboxTree/index'
import React, { useState, useEffect, useCallback } from 'react'
import { useIntl } from 'react-intl'
import { useMutation, useQuery } from 'react-apollo'

import { titlesIntl } from '../utils/intl'
import ProductsTable from './ProductsTable'
import FilesColumn from './FilesColumn'
import { ErrorArrayMessage } from './ErrorMessage'
import { SuccessArrayMessage } from './SuccessMessage'
import LoadingSpinner from './LoadingSpinner'
import cancelOrder from '../graphql/cancelOrder.gql'
import updateDocument from '../graphql/updateDocument.gql'
import getPaymentTransaction from '../graphql/getPaymentTransaction.gql'
import paymentNotification from '../graphql/paymentNotification.gql'
import startHandlingOrder from '../graphql/startHandlingOrder.gql'
import invoiceOrder from '../graphql/invoiceOrder.gql'
import getOrderStatus from '../graphql/getOrderStatus.gql'
import getOrderDataToInvoice from '../graphql/getOrderDataToInvoice.gql'

export default function OrdersTable({ orderList }: TableProps) {
  const intl = useIntl()
  const [items, setItems] = useState(orderList)
  const [cancelOrderMutation] = useMutation(cancelOrder)
  const [updateDocumentMutation] = useMutation(updateDocument)
  const getPaymentTransactionQuery = useQuery(getPaymentTransaction)
  const [paymentNotificationMutation] = useMutation(paymentNotification)
  const [startHandlingOrderMutation] = useMutation(startHandlingOrder)
  const [invoiceOrderMutation] = useMutation(invoiceOrder)
  const getOrderStatusQuery = useQuery(getOrderStatus)
  const getOrderDataToInvoiceQuery = useQuery(getOrderDataToInvoice)

  // const [error, setError] = useState(false)
  const [errorArray, setErrorArray] = useState(false)
  // const [success, setSuccess] = useState(false)
  const [successArray, setSuccessArray] = useState(false)
  const [loading, setLoading] = useState(false)
  // const [message, setMessage] = useState('')
  const [messageArraySuccess, setMessageArraySuccess] = useState<string[]>([])
  const [messageArrayError, setMessageArrayError] = useState<string[]>([])
  const [textInvoice, setTextInvoice] = useState('')

  const clearAlerts = useCallback(() => {
    // setError(false)
    setErrorArray(false)
    // setSuccess(false)
    setSuccessArray(false)
    setLoading(false)
    // setMessage('')
    setMessageArraySuccess([])
    setMessageArrayError([])
  }, [])

  const loadingAlert = useCallback(() => {
    // setError(false)
    setErrorArray(false)
    // setSuccess(false)
    setSuccessArray(false)
    setLoading(true)
    // setMessage('')
    setMessageArraySuccess([])
    setMessageArrayError([])
  }, [])

  const canceled = intl.formatMessage(titlesIntl.canceled)
  const created = intl.formatMessage(titlesIntl.created)
  const approved = intl.formatMessage(titlesIntl.approved)
  const confirmed = intl.formatMessage(titlesIntl.confirmed)

  const columns = [
    {
      id: 'status',
      title: intl.formatMessage(titlesIntl.ordersTableStatus),
      cellRenderer: ({ data }: any) => {
        let tag

        switch (data) {
          case 'canceled':
            tag = <Tag bgColor="#F71963">{canceled}</Tag>
            break

          case 'created':
            tag = <Tag bgColor="#E67E22">{created}</Tag>
            break

          case 'approved':
            tag = <Tag bgColor="#7D3C98">{approved}</Tag>
            break

          case 'confirmed':
            tag = <Tag bgColor="#16A085">{confirmed}</Tag>
            break

          default:
            break
        }

        return
{tag}

      },
    },
    {
      id: 'orderId',
      title: intl.formatMessage(titlesIntl.ordersTableOrderId),
    },
    {
      id: 'products',
      title: intl.formatMessage(titlesIntl.ordersTableProducts),
      cellRenderer: ({ data }: any) => {
        return (

            <Button
              variation="secondary"
              size="small"
              onClick={() => handleModalProductsToggle(data)}
            >
              {intl.formatMessage(titlesIntl.buttonShowProducts)}
            </Button>

        )
      },
    },
    {
      id: 'files',
      title: intl.formatMessage(titlesIntl.ordersTableFiles),
      cellRenderer: ({ data }: any) => {
        return <FilesColumn orderId={data} />
      },
    },
    {
      id: 'invoice',
      title: intl.formatMessage(titlesIntl.invoiceNumber),
      cellRenderer: ({ data }: any) => {
        const itemIsChecked = (item: any) =>
          item.id === data.rowId && item.status === 'approved'

        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        const checked = checkboxes.checkedItems.some(itemIsChecked)
        const errorCondition = !textInvoice && checked

        return (
          <Input
            defaultValue={data.invoiceNumber}
            onChange={(e: any) => {
              const tempItems = items

              tempItems[data.rowId].invoice = {
                rowId: data.rowId,
                invoiceNumber: e.target.value,
              }
              setTextInvoice(e.target.value)
              setItems(tempItems)
            }}
            /*
            placeholder={intl.formatMessage(
              titlesIntl.placeholderInvoiceNumber
            )}
            */
            disabled={!checked}
            error={errorCondition}
            errorMessage={
              errorCondition &&
              intl.formatMessage(titlesIntl.placeholderInvoiceNumber)
            }
          />
        )
      },
    },
  ]

  const [isProductModalOpen, setIsProductModalOpen] = useState(false)

  const [orderIdToModal, setOrderIdToModal] = useState()

  const handleModalProductsToggle = (orderId: any) => {
    setOrderIdToModal(orderId)
    setIsProductModalOpen(!isProductModalOpen)
  }

  const [withCheckboxes, isRowActive, checkboxes] = useColumnsWithCheckboxes({
    columns,
    items,
  })

  const approveAction = {
    label: intl.formatMessage(titlesIntl.approve),
    onClick: () => handleApproveAction(checkboxes.checkedItems),
  }

  const confirmAction = {
    label: intl.formatMessage(titlesIntl.confirm),
    onClick: () => handleConfirmAction(checkboxes.checkedItems),
  }

  const cancelAction = {
    label: intl.formatMessage(titlesIntl.cancel),
    onClick: () => handleCancelAction(checkboxes.checkedItems),
  }

  async function handleApproveAction(selectedRows: any) {
    loadingAlert()
    const tempItems = items
    const successArrayTemp: string[] = []
    const errorArrayTemp: string[] = []

    for await (const row of selectedRows) {
      console.info('row', row)
      if (row.id === 'VTEX_CheckboxTreeRoot') {
        continue
      }

      if (row.status === 'created') {
        /*
        const dataFromUpdateDocumentMutation = await cancelOrderMutation({
          variables: {
            orderId: row.orderId,
          },
        })

        const { status } = dataFromUpdateDocumentMutation.data.cancelOrder
        */
        const statusFromSendNotification = 200

        if (statusFromSendNotification === 200) {
          const bodyToMasterData: BodyUpdateDocument = {
            orderId: row.orderId,
            status: 'approved',
            invoiceNumber: '',
          }

          const dataFromUpdateDocumentMutation = await updateDocumentMutation({
            variables: {
              documentId: row.idMasterData,
              body: bodyToMasterData,
            },
          })

          const { status: statusUpdateDocument } =
            dataFromUpdateDocumentMutation.data.updateDocument

          if (statusUpdateDocument === 200) {
            tempItems[row.id].status = 'approved'
            successArrayTemp.push(
              `${intl.formatMessage(titlesIntl.theOrder)} ${
                row.orderId
              } ${intl.formatMessage(titlesIntl.wasApproved)}`
            )
          } else {
            // aca habria que ver algo como intentar de actualizar el documento mas adelante
            errorArrayTemp.push(
              `${intl.formatMessage(titlesIntl.theOrder)} ${
                row.orderId
              } ${intl.formatMessage(titlesIntl.wasNotApproved)}`
            )
          }
        } else {
          errorArrayTemp.push(
            `${intl.formatMessage(titlesIntl.theOrder)} ${
              row.orderId
            } ${intl.formatMessage(titlesIntl.wasNotApproved)}`
          )
        }
      } else if (row.status === 'approved' || row.status === 'confirmed') {
        errorArrayTemp.push(
          `${intl.formatMessage(titlesIntl.theOrder)} ${
            row.orderId
          } ${intl.formatMessage(titlesIntl.wasAlreadyApproved)}`
        )
      } else {
        errorArrayTemp.push(
          `${intl.formatMessage(titlesIntl.theOrder)} ${
            row.orderId
          } ${intl.formatMessage(titlesIntl.isCanceled)}`
        )
      }
    }

    if (tempItems.length > 0) {
      setItems(tempItems)
    }

    if (successArrayTemp.length > 0) {
      setSuccessArray(true)
      setMessageArraySuccess(successArrayTemp)
    }

    if (errorArrayTemp.length > 0) {
      setErrorArray(true)
      setMessageArrayError(errorArrayTemp)
    }

    setLoading(false)
  }

  async function consult(orderId: string): Promise<any> {
    const dataFromGetOrderStatusQuery = await getOrderStatusQuery.refetch({
      orderId,
    })

    console.info('dataFromGetOrderStatusQuery', dataFromGetOrderStatusQuery)
    const statusOfOrder =
      dataFromGetOrderStatusQuery.data.getOrderStatus.data.status

    console.info('statusOfOrder inside', statusOfOrder)

    if (statusOfOrder === 'ready-for-handling') {
      return true
    }

    const awaitTimeout = (delay: number) =>
      new Promise((resolve) => setTimeout(resolve, delay * 1000))

    await awaitTimeout(2)

    return validarReintento(orderId)
  }

  async function validarReintento(orderId: string) {
    const response = await consult(orderId)

    return response
  }

  async function handleConfirmAction(selectedRows: any) {
    loadingAlert()
    const tempItems = items
    const successArrayTemp: string[] = []
    const errorArrayTemp: string[] = []

    for await (const row of selectedRows) {
      console.info('row', row)
      if (row.id === 'VTEX_CheckboxTreeRoot') {
        continue
      }

      if (row.status === 'approved') {
        const { invoiceNumber } = row.invoice

        if (invoiceNumber) {
          const dataFromGetPaymentTransactionQuery =
            await getPaymentTransactionQuery.refetch({
              orderId: row.orderId,
            })

          const { status: statusPaymentTransaction } =
            dataFromGetPaymentTransactionQuery.data.getPaymentTransaction

          if (statusPaymentTransaction === 200) {
            const { payments } =
              dataFromGetPaymentTransactionQuery.data.getPaymentTransaction.data

            const promiseInfo = payments.find(
              (p: any) => p.paymentSystemName === 'Promissory'
            )

            const paymentId = promiseInfo.id

            const dataFromPaymentNotificationMutation =
              await paymentNotificationMutation({
                variables: {
                  orderId: row.orderId,
                  paymentId,
                },
              })

            const { status: statusPaymentNotification } =
              dataFromPaymentNotificationMutation.data.paymentNotification

            if (await validarReintento(row.orderId)) {
              console.info('ok')
              if (statusPaymentNotification === 204) {
                console.info('statusPaymentNotification === 204')
                const dataFromStartHandlingOrderMutation =
                  await startHandlingOrderMutation({
                    variables: {
                      orderId: row.orderId,
                    },
                  })

                console.info(
                  'dataFromStartHandlingOrderMutation',
                  dataFromStartHandlingOrderMutation
                )
                const { status: statusStartHandlingOrder } =
                  dataFromStartHandlingOrderMutation.data.startHandlingOrder

                console.info(
                  'statusStartHandlingOrder',
                  statusStartHandlingOrder
                )

                const dataFromGetOrderStatusQuery =
                  await getOrderStatusQuery.refetch({
                    orderId: row.orderId,
                  })

                console.info(
                  'dataFromGetOrderStatusQuery',
                  dataFromGetOrderStatusQuery
                )
                const { status: statusOfOrder } =
                  dataFromGetOrderStatusQuery.data.getOrderStatus.data

                console.info('statusOfOrder', statusOfOrder)

                if (
                  statusStartHandlingOrder === 200 &&
                  statusOfOrder === 'handling'
                ) {
                  // Order invoice notification
                  const issuanceDate = new Date(Date.now()).toISOString()

                  console.info('datetime', issuanceDate)

                  const dataFromGetOrderDataToInvoiceQuery =
                    await getOrderDataToInvoiceQuery.refetch({
                      orderId: row.orderId,
                    })

                  console.info(
                    'dataFromGetOrderDataToInvoiceQuery',
                    dataFromGetOrderDataToInvoiceQuery
                  )

                  const { status: statusOfGetOrderDataToInvoice } =
                    dataFromGetOrderDataToInvoiceQuery.data.getOrder

                  if (statusOfGetOrderDataToInvoice === 200) {
                    const { value: invoiceValue, items: itemsToInvoice } =
                      dataFromGetOrderDataToInvoiceQuery.data.getOrder.data

                    const itemsToInvoiceBody = itemsToInvoice.map(
                      (item: any) => {
                        const itemAux = {
                          id: item.id,
                          quantity: item.quantity,
                          price: item.price,
                        }

                        return itemAux
                      }
                    )

                    console.info('issuanceDate', issuanceDate)
                    console.info('invoiceNumber', invoiceNumber)
                    console.info('invoiceValue', invoiceValue)
                    console.info('itemsToInvoiceBody', itemsToInvoiceBody)
                    const bodyInvoice: InvoiceBody = {
                      type: 'Output',
                      issuanceDate,
                      invoiceNumber,
                      invoiceValue,
                      items: itemsToInvoiceBody,
                    }

                    console.info('invoiceBody', bodyInvoice)
                    const dataFromInvoiceOrderMutation =
                      await invoiceOrderMutation({
                        variables: {
                          orderId: row.orderId,
                          bodyInvoice,
                        },
                      })

                    const { status: statusInvoiceOrder } =
                      dataFromInvoiceOrderMutation.data.invoiceOrder

                    console.info('statusInvoiceOrder', statusInvoiceOrder)

                    const bodyToMasterData: BodyUpdateDocument = {
                      orderId: row.orderId,
                      status: 'confirmed',
                      invoiceNumber,
                    }

                    const dataFromUpdateDocumentMutation =
                      await updateDocumentMutation({
                        variables: {
                          documentId: row.idMasterData,
                          body: bodyToMasterData,
                        },
                      })

                    const { status: statusUpdateDocument } =
                      dataFromUpdateDocumentMutation.data.updateDocument

                    if (statusUpdateDocument === 200) {
                      tempItems[row.id].status = 'confirmed'
                      successArrayTemp.push(
                        `${intl.formatMessage(titlesIntl.theOrder)} ${
                          row.orderId
                        } ${intl.formatMessage(titlesIntl.wasConfirmed)}`
                      )
                    } else {
                      // aca habria que ver algo como intentar de actualizar el documento mas adelante
                      errorArrayTemp.push(
                        `${intl.formatMessage(titlesIntl.theOrder)} ${
                          row.orderId
                        } ${intl.formatMessage(titlesIntl.wasNotConfirmed)}`
                      )
                    }
                  } else {
                    errorArrayTemp.push(
                      `${intl.formatMessage(titlesIntl.theOrder)} ${
                        row.orderId
                      } ${intl.formatMessage(titlesIntl.wasNotConfirmed)}`
                    )
                  }
                } else {
                  errorArrayTemp.push(
                    `${intl.formatMessage(titlesIntl.theOrder)} ${
                      row.orderId
                    } ${intl.formatMessage(titlesIntl.wasNotConfirmed)}`
                  )
                }
              } else {
                errorArrayTemp.push(
                  `${intl.formatMessage(titlesIntl.theOrder)} ${
                    row.orderId
                  } ${intl.formatMessage(titlesIntl.wasNotConfirmed)}`
                )
              }
            }
          } else {
            errorArrayTemp.push(
              `${intl.formatMessage(titlesIntl.theOrder)} ${
                row.orderId
              } ${intl.formatMessage(titlesIntl.wasNotConfirmed)}`
            )
          }
        } else {
          errorArrayTemp.push(
            `${intl.formatMessage(titlesIntl.theOrder)} ${
              row.orderId
            } ${intl.formatMessage(
              titlesIntl.wasNotConfirmed
            )} ${intl.formatMessage(titlesIntl.noInvoiceNumber)}`
          )
        }
      } else if (row.status === 'confirmed') {
        errorArrayTemp.push(
          `${intl.formatMessage(titlesIntl.theOrder)} ${
            row.orderId
          } ${intl.formatMessage(titlesIntl.wasAlreadyConfirmed)}`
        )
      } else if (row.status === 'created') {
        errorArrayTemp.push(
          `${intl.formatMessage(titlesIntl.theOrder)} ${
            row.orderId
          } ${intl.formatMessage(titlesIntl.approvedBeforeConfirming)}`
        )
      } else {
        errorArrayTemp.push(
          `${intl.formatMessage(titlesIntl.theOrder)} ${
            row.orderId
          } ${intl.formatMessage(titlesIntl.isCanceled)}`
        )
      }
    }

    if (tempItems.length > 0) {
      setItems(tempItems)
    }

    if (successArrayTemp.length > 0) {
      setSuccessArray(true)
      setMessageArraySuccess(successArrayTemp)
    }

    if (errorArrayTemp.length > 0) {
      setErrorArray(true)
      setMessageArrayError(errorArrayTemp)
    }

    setLoading(false)
  }

  async function handleCancelAction(selectedRows: any) {
    loadingAlert()
    const tempItems = items
    const successArrayTemp: string[] = []
    const errorArrayTemp: string[] = []

    for await (const row of selectedRows) {
      if (row.id === 'VTEX_CheckboxTreeRoot') {
        continue
      }

      console.info('row', row)
      if (row.status === 'confirmed') {
        errorArrayTemp.push(
          `${intl.formatMessage(titlesIntl.theOrder)} ${
            row.orderId
          } ${intl.formatMessage(titlesIntl.isConfirmed)}`
        )
      } else if (row.status !== 'canceled') {
        const dataFromUpdateDocumentMutation = await cancelOrderMutation({
          variables: {
            orderId: row.orderId,
          },
        })

        const { status } = dataFromUpdateDocumentMutation.data.cancelOrder

        if (status === 200) {
          tempItems[row.id].status = 'canceled'
          successArrayTemp.push(
            `${intl.formatMessage(titlesIntl.theOrder)} ${
              row.orderId
            } ${intl.formatMessage(titlesIntl.wasCanceled)}`
          )
        } else {
          errorArrayTemp.push(
            `${intl.formatMessage(titlesIntl.theOrder)} ${
              row.orderId
            } ${intl.formatMessage(titlesIntl.wasNotCanceled)}`
          )
        }
      } else {
        errorArrayTemp.push(
          `${intl.formatMessage(titlesIntl.theOrder)} ${
            row.orderId
          } ${intl.formatMessage(titlesIntl.wasAlreadyCanceled)}`
        )
      }
    }

    if (tempItems.length > 0) {
      setItems(tempItems)
    }

    if (successArrayTemp.length > 0) {
      setSuccessArray(true)
      setMessageArraySuccess(successArrayTemp)
    }

    if (errorArrayTemp.length > 0) {
      setErrorArray(true)
      setMessageArrayError(errorArrayTemp)
    }

    setLoading(false)
  }

  const [filteredItems, setFilteredItems] = useState(items)
  const [filterStatements, setFilterStatements] = useState([])

  const ITEMS_PER_PAGE = 5

  const { slicedItems, ...paginationProps } = usePagination(
    ITEMS_PER_PAGE,
    filteredItems
  )

  const listOfRowsOptions: number[] = [5]

  if (filteredItems.length >= 5) {
    listOfRowsOptions.push(10)
    if (filteredItems.length >= 10) {
      listOfRowsOptions.push(15)
    }
  }

  const pagination = {
    ...paginationProps,
    textOf: intl.formatMessage(titlesIntl.textOf),
    rowsOptions: listOfRowsOptions,
    textShowRows: intl.formatMessage(titlesIntl.textShowRows),
    totalItems: filteredItems.length,
  }

  const measures = useTableMeasures({
    size:
      pagination.totalItems < pagination.tableSize
        ? pagination.totalItems
        : pagination.tableSize,
    density: 'comfortable',
  })

  function handleFiltersChange(statements = []) {
    let newData = items.slice()

    statements.forEach((st: any) => {
      if (!st || !st.object) return
      const { subject, verb, object } = st

      switch (subject) {
        case 'orderId':
          if (verb === 'contains') {
            newData = newData.filter((item: any) => {
              return item[subject].includes(object)
            })
          } else if (verb === '=') {
            newData = newData.filter((item: any) => item[subject] === object)
          } else if (verb === '!=') {
            newData = newData.filter((item: any) => item[subject] !== object)
          }

          break

        case 'status':
          if (!object) return
          // eslint-disable-next-line no-case-declarations
          const selectedStatus = Object.keys(object).reduce(
            (acc: any, item: any) => (object[item] ? [...acc, item] : acc),
            []
          )

          newData = newData.filter((item: any) => {
            let status

            switch (item[subject]) {
              case 'canceled':
                status = canceled
                break

              case 'created':
                status = created
                break

              case 'approved':
                status = approved
                break

              case 'confirmed':
                status = confirmed
                break

              default:
                break
            }

            return selectedStatus.includes(status)
          })
          break

        default:
          break
      }
    })
    setFilteredItems(newData)
    setFilterStatements(statements)
  }

  const filterClear = intl.formatMessage(titlesIntl.filterClear)
  const filterAll = intl.formatMessage(titlesIntl.filterAll)
  const filterNone = intl.formatMessage(titlesIntl.filterNone)
  const filterAny = intl.formatMessage(titlesIntl.filterAny)
  const filterIs = intl.formatMessage(titlesIntl.filterIs)
  const filterIsNot = intl.formatMessage(titlesIntl.filterIsNot)
  const filterContains = intl.formatMessage(titlesIntl.filterContains)
  const filterApply = intl.formatMessage(titlesIntl.filterApply)

  const filters = {
    alwaysVisibleFilters: ['status', 'orderId'],
    statements: filterStatements,
    onChangeStatements: handleFiltersChange,
    clearAllFiltersButtonLabel: filterClear,
    collapseLeft: true,
    submitFilterLabel: filterApply,
    options: {
      status: {
        label: intl.formatMessage(titlesIntl.ordersTableStatus),
        renderFilterLabel: (st: any) => {
          if (!st || !st.object) {
            return filterAll
          }

          const keys: any = st.object ? Object.keys(st.object) : {}
          const isAllTrue = !keys.some((key: any) => !st.object[key])
          const isAllFalse = !keys.some((key: any) => st.object[key])
          const trueKeys = keys.filter((key: any) => st.object[key])
          let trueKeysLabel = ''

          trueKeys.forEach((key: any, index: any) => {
            trueKeysLabel += `${key}${
              index === trueKeys.length - 1 ? '' : ', '
            }`
          })

          const labelsArray = trueKeysLabel
            .split(',')
            .map((item: any) => item.trim())

          return `${
            isAllTrue ? filterAll : isAllFalse ? filterNone : `${labelsArray}`
          }`
        },
        verbs: [
          {
            value: 'includes',
            object: {
              renderFn: statusSelectorObject,
              extraParams: {},
            },
          },
        ],
      },
      orderId: {
        label: intl.formatMessage(titlesIntl.ordersTableOrderId),
        ...simpleInputVerbsAndLabel(),
      },
    },
  }

  function simpleInputObject({ values, onChangeObjectCallback }: any) {
    return (
      <Input
        value={values || ''}
        onChange={(e: any) => onChangeObjectCallback(e.target.value)}
      />
    )
  }

  function simpleInputVerbsAndLabel() {
    return {
      renderFilterLabel: (st: any) => {
        if (!st || !st.object) {
          // you should treat empty object cases only for alwaysVisibleFilters
          return filterAny
        }

        return `${
          st.verb === '='
            ? filterIs
            : st.verb === '!='
            ? filterIsNot
            : filterContains
        } ${st.object}`
      },
      verbs: [
        {
          label: filterIs,
          value: '=',
          object: {
            renderFn: simpleInputObject,
            extraParams: {},
          },
        },
        {
          label: filterIsNot,
          value: '!=',
          object: {
            renderFn: simpleInputObject,
            extraParams: {},
          },
        },
        {
          label: filterContains,
          value: 'contains',
          object: {
            renderFn: simpleInputObject,
            extraParams: {},
          },
        },
      ],
    }
  }

  function statusSelectorObject({ values, onChangeObjectCallback }: any) {
    const initialValue = {
      [created]: true,
      [approved]: true,
      [confirmed]: true,
      [canceled]: true,
      ...(values || {}),
    }

    const toggleValueByKey = (key: any) => {
      const newValues = {
        ...(values || initialValue),
        [key]: values ? !values[key] : false,
      }

      return newValues
    }

    return (

        {Object.keys(initialValue).map((opt, index) => {
          return (
            <div className="mb3" key={`class-statment-object-${opt}-${index}`}>
              <Checkbox
                checked={values ? values[opt] : initialValue[opt]}
                label={opt}
                name="default-checkbox-group"
                onChange={() => {
                  const newValue = toggleValueByKey(`${opt}`)
                  const newValueKeys = Object.keys(newValue)
                  const isEmptyFilter = !newValueKeys.some(
                    (key) => !newValue[key]
                  )

                  onChangeObjectCallback(isEmptyFilter ? null : newValue)
                }}
                value={opt}
              />

          )
        })}

    )
  }

  return (

        {loading && <LoadingSpinner />}
        {successArray && (
          <SuccessArrayMessage
            onClose={clearAlerts}
            messages={messageArraySuccess}
          />
        )}
        {errorArray && (
          <ErrorArrayMessage
            onClose={clearAlerts}
            messages={messageArrayError}
          />
        )}

            {!checkboxes.allChecked && (

                {intl.formatMessage(titlesIntl.selectedOrders)}{' '}
                {checkboxes.checkedItems?.length}

            )}

              {intl.formatMessage(titlesIntl.selectedOrders)} {items.length}

      <Modal
        centered
        isOpen={isProductModalOpen}
        onClose={() => handleModalProductsToggle(null)}
      >
        <ProductsTable orderId={orderIdToModal} />
      </Modal>

  )
}

function useColumnsWithCheckboxes({ columns, items }: any) {
  const checkboxes = useCheckboxTree({
    items,
  })

  const mappedCheckboxes = checkboxes.itemTree.children.map(
    (item: { id: any }) => {
      const id = `${item.id}`

      return (
        <Checkbox
          key={id}
          id={id}
          checked={checkboxes.isChecked(item)}
          partial={checkboxes.isPartiallyChecked(item)}
          disabled={checkboxes.isDisabled(item)}
          onChange={() => checkboxes.toggle(item)}
        />
      )
    }
  )

  const withCheckboxes = [
    {
      id: 'checkbox',
      title: (
        <Checkbox
          id={`${checkboxes.itemTree.id}`}
          checked={checkboxes.allChecked}
          partial={checkboxes.someChecked}
          onChange={checkboxes.toggleAll}
        />
      ),
      width: 32,
      extended: true,
      cellRenderer: ({ data }: any) => {
        return
{mappedCheckboxes[data.id]}

      },
    },
    ...columns,
  ]

  return [withCheckboxes, (data: any) => checkboxes.isChecked(data), checkboxes]
}

function usePagination(initialSize: number, itemsToPaginate: any) {
  const [state, setState] = useState({
    tableSize: initialSize,
    currentPage: 1,
    currentItemFrom: 1,
    currentItemTo: initialSize,
    slicedItems: [...itemsToPaginate].slice(0, initialSize),
  })

  /** resets state on items change */
  useEffect(() => {
    setState({
      tableSize: initialSize,
      currentPage: 1,
      currentItemFrom: 1,
      currentItemTo: initialSize,
      slicedItems: [...itemsToPaginate].slice(0, initialSize),
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [itemsToPaginate])

  /** gets the next page */
  const onNextClick = useCallback(() => {
    const newPage = state.currentPage + 1
    const itemFrom = state.currentItemTo + 1
    const itemTo = state.tableSize * newPage
    const newItems = [...itemsToPaginate].slice(itemFrom - 1, itemTo)

    setState({
      ...state,
      currentPage: newPage,
      currentItemFrom: itemFrom,
      currentItemTo: itemTo,
      slicedItems: newItems,
    })
  }, [state, itemsToPaginate])

  /** gets the previous page */
  const onPrevClick = useCallback(() => {
    if (state.currentPage === 0) return
    const newPage = state.currentPage - 1
    const itemFrom = state.currentItemFrom - state.tableSize
    const itemTo = state.currentItemFrom - 1
    const newItems = [...itemsToPaginate].slice(itemFrom - 1, itemTo)

    setState({
      ...state,
      currentPage: newPage,
      currentItemFrom: itemFrom,
      currentItemTo: itemTo,
      slicedItems: newItems,
    })
  }, [state, itemsToPaginate])

  /** deals rows change of Pagination component */
  const onRowsChange = useCallback(
    (_, value) => {
      const rowValue = parseInt(value, 10)

      setState({
        ...state,
        tableSize: rowValue,
        currentItemTo: rowValue,
        slicedItems: [...itemsToPaginate].slice(
          state.currentItemFrom - 1,
          rowValue
        ),
      })
    },
    [state, itemsToPaginate]
  )

  return {
    onNextClick,
    onPrevClick,
    onRowsChange,
    ...state,
  }
}

```


[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 pharma-orders-admin/react/graphql/invoiceOrder.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation invoiceOrder($orderId: String, $bodyInvoice: BodyInvoiceOrder) {
  invoiceOrder(orderId: $orderId, bodyInvoice: $bodyInvoice) {
    status
  }
}

```


[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 pharma-orders-admin/react/graphql/updateDocument.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation updateDocument(
  $documentId: String
  $body: BodyUpdateDocumentMasterData
) {
  updateDocument(documentId: $documentId, body: $body) {
    status
  }
}

```


[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 pharma-orders-admin/react/graphql/startHandlingOrder.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation startHandlingOrder($orderId: String) {
  startHandlingOrder(orderId: $orderId) {
    status
  }
}

```


[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 pharma-orders-admin/react/graphql/paymentNotification.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation paymentNotification($orderId: String, $paymentId: String) {
  paymentNotification(orderId: $orderId, paymentId: $paymentId) {
    status
  }
}

```


[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 pharma-orders-admin/react/graphql/getOrderStatus.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getOrderStatus($orderId: String) {
  getOrderStatus(orderId: $orderId) {
    status
    data {
      status
    }
  }
}

```


[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 pharma-orders-admin/react/graphql/getPaymentTransaction.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getPaymentTransaction($orderId: String) {
  getPaymentTransaction(orderId: $orderId) {
    status
    data {
      status
      isActive
      transactionId
      merchantName
      payments {
        id
        paymentSystem
        paymentSystemName
        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 pharma-orders-admin/react/graphql/getOrderCustomData.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getOrderCustomData($orderId: String) {
  getOrder(orderId: $orderId) {
    status
    data {
      customData {
        customApps {
          fields {
            data
          }
          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 pharma-orders-admin/react/graphql/cancelOrder.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation cancelOrder($orderId: String) {
  cancelOrder(orderId: $orderId) {
    status
    data {
      date
      orderId
      receipt
    }
  }
}

```


[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 pharma-orders-admin/react/graphql/getOrderItems.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getOrderItems($orderId: String) {
  getOrder(orderId: $orderId) {
    status
    data {
      items {
        id
        productId
        quantity
        name
      }
    }
  }
}

```


[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 pharma-orders-admin/react/graphql/getData.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getData {
  getData {
    status
    data {
      id
      orderId
      status
      invoiceNumber
    }
  }
}

```


[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 pharma-orders-admin/react/graphql/getOrderDataToInvoice.gql from the pharma-orders-admin VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getOrderDataToInvoice($orderId: String) {
  getOrder(orderId: $orderId) {
    status
    data {
      value
      items {
        id
        quantity
        price
      }
    }
  }
}

```


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

[Assistant]
Here's the implementation:

```markdown
# Service Worker Example

Service Workers (SWs) are a poweful tool to handle network requests separate from a web page, as scripts running in the background. They are well known to handle push notifications and background syncronization.

With `service-worker` builder, we can allow an app to expose its own implementation of a Service Worker, enabling VTEX stores to use such Service Worker into their scope.

Service Workers allow us to introduce 6 different event handlers, which can be implemented inside the `service-workers/` folder:

1. [activate](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/activate_event) → `activate.js`
2. [fetch](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onfetch) → `fetch.js`
3. [install](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/install_event) → `install.js`
4. [message](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/message_event) → `message.js`
5. [push](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/push_event) → `push.js`
6. [sync](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onsync) → `sync.js`

Whatever is outside those 6 files, should be implemented in `header.js`. The implementation result in the VTEX store DevTools should be as follows:

![image](https://user-images.githubusercontent.com/21017429/114235943-84d14600-9946-11eb-8e1a-4a8f19d3d3d8.png)

Each function can be tested according to the behavior of each event handler. When triggering such event handler, the function body will be executed as follows:

![image](https://user-images.githubusercontent.com/21017429/114235975-8e5aae00-9946-11eb-91f8-b1d7f6d92485.png)

An example is provided in this app for exploration purposes.

```


[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 service-worker-example/service-workers/message.js from the service-worker-example VTEX app.

[Assistant]
Here's the implementation:

```javascript
function exampleSWMessage() {
  // eslint-disable-next-line no-console
  console.log('[example-sw] Message of service worker')
}

export default exampleSWMessage

```


[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 service-worker-example/service-workers/sync.js from the service-worker-example VTEX app.

[Assistant]
Here's the implementation:

```javascript
function exampleSWSync() {
  // eslint-disable-next-line no-console
  console.log('[example-sw] Sync of service worker')
}

export default exampleSWSync

```


[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 service-worker-example/service-workers/fetch.js from the service-worker-example VTEX app.

[Assistant]
Here's the implementation:

```javascript
function exampleSWFetch() {
  // eslint-disable-next-line no-console
  console.log('[example-sw] Fetch of service worker')
}

export default exampleSWFetch

```


[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 service-worker-example/service-workers/header.js from the service-worker-example VTEX app.

[Assistant]
Here's the implementation:

```javascript
function exampleSWHeader() {
  // eslint-disable-next-line no-console
  console.log('[example-sw] Header of service worker')
}

export default exampleSWHeader

```


[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 service-worker-example/service-workers/install.js from the service-worker-example VTEX app.

[Assistant]
Here's the implementation:

```javascript
function exampleSWInstall() {
  // eslint-disable-next-line no-console
  console.log('[example-sw] Install of service worker')
}

export default exampleSWInstall

```


[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 service-worker-example/service-workers/push.js from the service-worker-example VTEX app.

[Assistant]
Here's the implementation:

```javascript
function exampleSWPush() {
  // eslint-disable-next-line no-console
  console.log('[example-sw] Push of service worker')
}

export default exampleSWPush

```


[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 service-worker-example/service-workers/activate.js from the service-worker-example VTEX app.

[Assistant]
Here's the implementation:

```javascript
function exampleSWActivate() {
  // eslint-disable-next-line no-console
  console.log('[example-sw] Activate of service worker')
}

export default exampleSWActivate

```


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

[Assistant]
Here's the implementation:

```markdown
# Bluecore

VTEX Bluecore first-party app

## How to install

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

Now, open the app settings on your admin and fill in your Bluecore's Site 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 bluecore/react/index.tsx from the bluecore VTEX app.

[Assistant]
Here's the implementation:

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

export interface Order {
  visitorContactInfo: string[]
  transactionId: string
  transactionTotal: number,
  transactionProducts: ProductOrder[]
}

interface ProductOrder {
  productRefId: string,
}

function addPixelImage(order: Order) {
  const token = window.__bluecore_site_id

  const email = order.visitorContactInfo[0]
  const total = order.transactionTotal
  const orderId = order.transactionId
  const productsIds = order.transactionProducts.map(({ productRefId }) => productRefId).join(',')

  const img = document.createElement('img')
  const url = `https://www.bluecore.com/api/track/purchase_pixel?token=${token}&email=${email}&total=${total}&order_id=${orderId}&product_ids=${productsIds}`

  img.setAttribute('id', 'bluecore_purchase_pixel')
  img.setAttribute('src', url)

  document.body.appendChild(img)
}

function handleMessages(e: PixelMessage) {
  switch (e.data.eventName) {
    case 'vtex:orderPlaced': {
      const order = e.data as Order
      addPixelImage(order)
      break
    }
    case "vtex:addToCart": {
      const { items } = e.data

      items.forEach(item => {
        try {
          window.triggermail.Partner.dataReady({
            event_type: "add_to_cart",
            id: item.productRefId
          })
        } catch (e) {
          console.error(e)
        }
      })
      return
    }
    case "vtex:removeFromCart": {
      const { items } = e.data

      items.forEach(item => {
        try {
          window.triggermail.Partner.dataReady({
            event_type: "remove_from_cart",
            id: item.productRefId
          });
        } catch (e) {
          console.error(e)
        }
      })
      break
    }
    default:
      break
  }
}

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

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "devDependencies": {
    "@types/node": "^10.12.18",
    "@types/prop-types": "^15.5.6",
    "@types/ramda": "types/npm-ramda#dist",
    "@types/react": "^16.4.14",
    "eslint": "5",
    "eslint-config-vtex-react": "4",
    "prettier": "^1.18.2",
    "typescript": "3.5.2"
  },
  "version": "1.1.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 bluecore/store/interfaces.json from the bluecore VTEX app.

[Assistant]
Here's the implementation:

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

[Assistant]
Here's the implementation:

```typescript
export interface PixelMessage extends MessageEvent {
  data: OrderPlacedData | 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";
}

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

[Assistant]
Here's the implementation:

```typescript
interface Window extends Window {
  __bluecore_site_id: string;
  triggermail: Bluecore;
}

interface Bluecore {
  Partner: {
    dataReady(params: AddToCart | RemoveFromCart): void;
  };
}

type AddToCart = { event_type: "add_to_cart"; id: string };
type RemoveFromCart = { event_type: "remove_from_cart"; id: string };

```


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

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

[Assistant]
Here's the implementation:

```markdown
# Blog Interfaces

> Interfaces for a blog integration app.

This app provides extensible interfaces that can be used by the `vtex.store` and a theme app. A blog app (either native or a third-party integration) would depend on this app and extend the interfaces provided to become available in the store.

For an example, see the [vtex.wordpress-integration](https://github.com/vtex-apps/wordpress-integration) app.

## Use cases

1. Create store pages for blog posts, blog categories, and blog search results.
2. Add blog-related blocks to product pages and search pages.

```


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

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test",
    "lint": "eslint --ext js,jsx,ts,tsx ."
  },
  "dependencies": {
    "react": "^16.8.3",
    "react-dom": "^16.8.3"
  },
  "devDependencies": {
    "@types/graphql": "^14.2.0",
    "@types/jest": "^24.0.11",
    "@types/node": "^11.13.0",
    "@types/prop-types": "^15.7.0",
    "@types/react": "^16.8.10",
    "eslint": "^5.16.0",
    "eslint-config-vtex": "^10.1.0",
    "prettier": "^1.16.4",
    "tslint-eslint-rules": "^5.4.0",
    "typescript": "3.8.3"
  },
  "version": "0.2.0"
}

```


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

[User] Show me the implementation of blog-interfaces/react/Noop.tsx from the blog-interfaces VTEX app.

[Assistant]
Here's the implementation:

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

const Noop: FunctionComponent = () => <></>

export default Noop

```


[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 blog-interfaces/store/interfaces.json from the blog-interfaces VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "blog-all-posts": {
    "component": "Noop",
    "extensible": "public"
  },
  "blog-latest-posts-preview": {
    "component": "Noop",
    "extensible": "public"
  },
  "blog-category-preview": {
    "component": "Noop",
    "extensible": "public"
  },
  "blog-category-list": {
    "component": "Noop",
    "extensible": "public"
  },
  "blog-post-container": {
    "component": "Noop",
    "extensible": "public",
    "composition": "children"
  },
  "blog-post-details": {
    "component": "Noop",
    "extensible": "public",
    "composition": "children",
    "allowed": [
      "blog-related-products"
    ]
  },
  "blog-post-navigation": {
    "component": "Noop",
    "extensible": "public"
  },
  "blog-page-details": {
    "component": "Noop",
    "extensible": "public",
    "composition": "children",
    "allowed": [
      "blog-related-products"
    ]
  },
  "blog-search": {
    "component": "Noop",
    "extensible": "public"
  },
  "search-blog-articles-preview": {
    "component": "Noop",
    "extensible": "public"
  },
  "search-blog-articles-list": {
    "component": "Noop",
    "extensible": "public"
  },
  "blog-search-list": {
    "component": "Noop",
    "extensible": "public"
  },
  "blog-related-products": {
    "component": "Noop",
    "extensible": "public"
  },
  "blog-related-posts": {
    "component": "Noop",
    "extensible": "public"
  },
  "blog-breadcrumb": {
    "component": "Noop",
    "extensible": "public"
  }
}
```


[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 opencart/system/library/shared/tcpdf/README.md from the opencart VTEX app.

[Assistant]
Here's the implementation:

```markdown
# TCPDF
*PHP PDF Library*

[![Donate via PayPal](https://img.shields.io/badge/donate-paypal-87ceeb.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&currency_code=GBP&business=paypal@tecnick.com&item_name=donation%20for%20TCPDF%20project)
*Please consider supporting this project by making a donation via [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&currency_code=GBP&business=paypal@tecnick.com&item_name=donation%20for%20TCPDF%20project)*

* **category**    Library
* **author**      Nicola Asuni <info@tecnick.com>
* **copyright**   2002-2020 Nicola Asuni - Tecnick.com LTD
* **license**     http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* **link**        http://www.tcpdf.org
* **source**      https://github.com/tecnickcom/TCPDF

## IMPORTANT
A new version of this library is under development at https://github.com/tecnickcom/tc-lib-pdf and as a consequence this version will not receive any additional development or support.
This version should be considered obsolete, new projects should use the new version as soon it will become stable.

## Description

PHP library for generating PDF documents on-the-fly.

### Main Features:
* no external libraries are required for the basic functions;
* all standard page formats, custom page formats, custom margins and units of measure;
* UTF-8 Unicode and Right-To-Left languages;
* TrueTypeUnicode, OpenTypeUnicode v1, TrueType, OpenType v1, Type1 and CID-0 fonts;
* font subsetting;
* methods to publish some XHTML + CSS code, Javascript and Forms;
* images, graphic (geometric figures) and transformation methods;
* supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/script/formats.php)
* 1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;
* JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;
* automatic page header and footer management;
* document encryption up to 256 bit and digital signature certifications;
* transactions to UNDO commands;
* PDF annotations, including links, text and file attachments;
* text rendering modes (fill, stroke and clipping);
* multiple columns mode;
* no-write page regions;
* bookmarks, named destinations and table of content;
* text hyphenation;
* text stretching and spacing (tracking);
* automatic page break, line break and text alignments including justification;
* automatic page numbering and page groups;
* move and delete pages;
* page compression (requires php-zlib extension);
* XOBject Templates;
* Layers and object visibility.
* PDF/A-1b support.

### Third party fonts:

This library may include third party font files released with different licenses.

All the PHP files on the fonts directory are subject to the general TCPDF license (GNU-LGPLv3),
they do not contain any binary data but just a description of the general properties of a particular font.
These files can be also generated on the fly using the font utilities and TCPDF methods.

All the original binary TTF font files have been renamed for compatibility with TCPDF and compressed using the gzcompress PHP function that uses the ZLIB data format (.z files).

The binary files (.z) that begins with the prefix "free" have been extracted from the GNU FreeFont collection (GNU-GPLv3).
The binary files (.z) that begins with the prefix "pdfa" have been derived from the GNU FreeFont, so they are subject to the same license.
For the details of Copyright, License and other information, please check the files inside the directory fonts/freefont-20120503
Link : http://www.gnu.org/software/freefont/

The binary files (.z) that begins with the prefix "dejavu" have been extracted from the DejaVu fonts 2.33 (Bitstream) collection.
For the details of Copyright, License and other information, please check the files inside the directory fonts/dejavu-fonts-ttf-2.33
Link : http://dejavu-fonts.org

The binary files (.z) that begins with the prefix "ae" have been extracted from the Arabeyes.org collection (GNU-GPLv2).
Link : http://projects.arabeyes.org/

### ICC profile:

TCPDF includes the sRGB.icc profile from the icc-profiles-free Debian package:
https://packages.debian.org/source/stable/icc-profiles-free

## Developer(s) Contact

* Nicola Asuni <info@tecnick.com>

```


[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 opencart/system/library/shared/tcpdf/composer.json from the opencart VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "tecnickcom/tcpdf",
  "version": "6.3.5",
  "homepage": "http://www.tcpdf.org/",
  "type": "library",
  "description": "TCPDF is a PHP class for generating PDF documents and barcodes.",
  "keywords": [
    "PDF",
    "tcpdf",
    "PDFD32000-2008",
    "qrcode",
    "datamatrix",
    "pdf417",
    "barcodes"
  ],
  "license": "LGPL-3.0-only",
  "authors": [
    {
      "name": "Nicola Asuni",
      "email": "info@tecnick.com",
      "role": "lead"
    }
  ],
  "require": {
    "php": ">=5.3.0"
  },
  "autoload": {
    "classmap": [
      "config",
      "include",
      "tcpdf.php",
      "tcpdf_parser.php",
      "tcpdf_import.php",
      "tcpdf_barcodes_1d.php",
      "tcpdf_barcodes_2d.php",
      "include/tcpdf_colors.php",
      "include/tcpdf_filters.php",
      "include/tcpdf_font_data.php",
      "include/tcpdf_fonts.php",
      "include/tcpdf_images.php",
      "include/tcpdf_static.php",
      "include/barcodes/datamatrix.php",
      "include/barcodes/pdf417.php",
      "include/barcodes/qrcode.php"
    ]
  }
}

```


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

[Assistant]
Here's the implementation:

```markdown
# React Portal

# Basic Usage

It is possible to wrap a React element with [Overlay](https://github.com/vtex-apps/react-portal/blob/master/react/Overlay.tsx) to make use of its advantages such as making the block overlap any other block despite its z-index.

## Example:

```
<Overlay>

Hello World!

</Overlay>
```

## Props

| Prop name    | Type          | Description                                                  | Default value |
| ------------ | ------------- | ------------------------------------------------------------ | ------------- |
| `alignment`  | `String`      | Horizontal alignment                                         | `left`        |
| `fullWindow` | `Boolean`     | If true, the overlay will fill the whole window horizontally | -             |
| `target`     | `HTMLElement` | Defines the container where the overlay will be created.     | -             |

Here are the possible values of `HorizontalAlignment`

| Value    | Description         |
| -------- | ------------------- |
| 'center' | Align to the center |
| 'left'   | Align to the left   |
| 'right'  | Align to the right  |

```


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

[Assistant]
Here's the implementation:

```tsx
import Overlay from './Overlay'

export { Overlay }

```


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

[Assistant]
Here's the implementation:

```json
{
  "dependencies": {
    "@vtex/css-handles": "^1.1.3",
    "lodash.throttle": "^4.1.1",
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  },
  "devDependencies": {
    "@types/lodash.throttle": "^4.1.6",
    "@types/react": "^16.8.15",
    "@types/react-dom": "^16.8.4",
    "@vtex/test-tools": "^0.1.4",
    "vtex.css-handles": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles"
  },
  "version": "0.4.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 react-portal/react/Overlay.tsx from the react-portal VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, {
  useRef,
  useEffect,
  useState,
  useCallback,
  PropsWithChildren,
} from 'react'
import Portal, { Props as PortalProps } from './components/Portal'
import throttle from 'lodash.throttle'

interface Props extends PortalProps {
  fullWindow?: boolean
  alignment?: HorizontalAlignment
}

interface Position {
  x: number
  y: number
}

type HorizontalAlignment = 'right' | 'left' | 'center'

const getXPositionByHorizontalAlignment = (
  alignment: HorizontalAlignment,
  bounds: ClientRect | DOMRect
) => {
  switch (alignment) {
    case 'left':
      return bounds.left
    case 'right':
      return bounds.right
    case 'center':
      return (bounds.right + bounds.left) / 2
    default:
      return bounds.left
  }
}

const getJustifyTypeByHorizontalAlignment = (
  alignment: HorizontalAlignment
) => {
  switch (alignment) {
    case 'left':
      return 'justify-start'
    case 'right':
      return 'justify-end'
    case 'center':
      return 'justify-center'
    default:
      return 'justify-start'
  }
}

function Overlay({
  children,
  fullWindow,
  target,
  alignment = 'left',
}: PropsWithChildren<Props>) {
  const container = useRef<HTMLDivElement>(null)
  const [position, setPosition] = useState<Position>()

  /** updatePosition is throttled due to the use of getBoundingClientRect,
   * which triggers a recalculation of the entire page layout, which in
   * turn can be quite heavy */
  const updatePosition = useCallback(
    throttle(
      () => {
        if (!fullWindow && container.current) {
          const bounds = container.current.getBoundingClientRect()

          setPosition({
            x: getXPositionByHorizontalAlignment(alignment, bounds),
            y: bounds.top,
          })
        }
        /** Also, the throttling is set to leading: false (which means that
         * the function won't be called right away, but only after X ms),
         * to improve hydration performance */
      },
      200,
      { leading: false }
    ),
    [alignment, fullWindow]
  )

  useEffect(() => {
    updatePosition()

    if (window) {
      window.addEventListener('scroll', updatePosition)
      window.addEventListener('load', updatePosition)
      window.addEventListener('resize', updatePosition)
      window.addEventListener('visibilitychange', updatePosition)
    }

    return () => {
      if (window) {
        window.removeEventListener('scroll', updatePosition)
        window.removeEventListener('load', updatePosition)
        window.removeEventListener('resize', updatePosition)
        window.removeEventListener('visibilitychange', updatePosition)
      }
    }
  }, [alignment, fullWindow, updatePosition, children])

  if (!fullWindow) {
    return (
      // Div used for anchoring the position of the overlay, for popovers etc
      <div
        ref={container}
        style={{
          width: 'auto',
          height: 1,
          marginTop: -1,
        }}
      >
        {position && (
          <Portal target={target}>
            <div
              className={`flex ${getJustifyTypeByHorizontalAlignment(
                alignment
              )}`}
              style={{
                position: 'absolute',
                left: position.x,
                top: position.y,
              }}
            >
              <div className="absolute">{children}</div>
            </div>
          </Portal>
        )}
      </div>
    )
  }

  return (
    <Portal target={target} cover>
      {children}
    </Portal>
  )
}

export default Overlay

```


[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 react-portal/react/components/Portal.tsx from the react-portal VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FunctionComponent } from 'react'
import ReactDOM from 'react-dom'

import { useCssHandles } from 'vtex.css-handles'

export interface Props {
  cover?: boolean
  target?: HTMLElement
  zIndex?: number
}

const CSS_HANDLES = ['portalContainer', 'portalWrapper'] as const

const Portal: FunctionComponent<Props> = ({
  children,
  target,
  zIndex = 2147483647,
  cover,
}) => {
  const handles = useCssHandles(CSS_HANDLES)

  if (!target) {
    target = window && window.document && window.document.body
  }

  if (!target) {
    return null
  }

  return ReactDOM.createPortal(
    <div
      className={handles.portalContainer}
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        ...(cover
          ? {
              bottom: 0,
              right: 0,
              pointerEvents: 'none',
            }
          : {}),
        zIndex,
      }}
    >
      <div className={handles.portalWrapper} style={{ pointerEvents: 'auto' }}>
        {children}
      </div>
    </div>,
    target
  )
}

export default Portal

```


[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 modal-layout/messages/hu.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "Mégse",
  "admin/editor.modal-layout.close-button.title": "Modális bezárása gomb",
  "admin/editor.modal-layout.close-button.label.title": "Gombcímke",
  "admin/editor.modal-layout.close-button.label.description": "Pl. „Modális bezárása”"
}

```


[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 modal-layout/messages/th-TH.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "ยกเลิก",
  "admin/editor.modal-layout.close-button.title": "ปุ่มปิดกล่องแสดงข้อความแบบโมดอล",
  "admin/editor.modal-layout.close-button.label.title": "ป้ายชื่อปุ่ม",
  "admin/editor.modal-layout.close-button.label.description": "เช่น \"ปิดกล่องแสดงข้อความแบบโมดอล\""
}

```


[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 modal-layout/messages/ja.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "キャンセル",
  "admin/editor.modal-layout.close-button.title": "モーダルボタンを閉じる",
  "admin/editor.modal-layout.close-button.label.title": "ボタンラベル",
  "admin/editor.modal-layout.close-button.label.description": "例「モーダルを閉じる」"
}

```


[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 modal-layout/messages/fi.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "Peruuta",
  "admin/editor.modal-layout.close-button.title": "Sulje modaali -painike",
  "admin/editor.modal-layout.close-button.label.title": "Painikkeen selite",
  "admin/editor.modal-layout.close-button.label.description": "Esim.: ”Sulje modaali”"
}

```


[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 modal-layout/messages/id-ID.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "Batalkan",
  "admin/editor.modal-layout.close-button.title": "Tombol Tutup Modal",
  "admin/editor.modal-layout.close-button.label.title": "Label tombol",
  "admin/editor.modal-layout.close-button.label.description": "Mis. \"Tutup 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 modal-layout/messages/pt.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "Cancelar",
  "admin/editor.modal-layout.close-button.title": "Close Modal Button",
  "admin/editor.modal-layout.close-button.label.title": "Button label",
  "admin/editor.modal-layout.close-button.label.description": "E.g \"Close 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 modal-layout/messages/en.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "Cancel",
  "store/modal-layout.modal-trigger.aria-label": "Open modal",
  "admin/editor.modal-layout.close-button.title": "Close Modal Button",
  "admin/editor.modal-layout.close-button.label.title": "Button label",
  "admin/editor.modal-layout.close-button.label.description": "E.g \"Close 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 modal-layout/messages/fr.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
    "store/modal-layout.close-button.default-label": "Annuler",
    "store/modal-layout.modal-trigger.aria-label": "Ouvrir le modal",
    "admin/editor.modal-layout.close-button.title": "Bouton de fermeture du modal",
    "admin/editor.modal-layout.close-button.label.title": "Étiquette du bouton",
    "admin/editor.modal-layout.close-button.label.description": "Par exemple « Fermer le 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 modal-layout/messages/ro.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "Anulează",
  "admin/editor.modal-layout.close-button.title": "Închide butonul modal",
  "admin/editor.modal-layout.close-button.label.title": "Etichetă buton",
  "admin/editor.modal-layout.close-button.label.description": "De exemplu, „Închide 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 modal-layout/messages/ko.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "취소",
  "admin/editor.modal-layout.close-button.title": "모달 버튼 닫기",
  "admin/editor.modal-layout.close-button.label.title": "버튼 라벨",
  "admin/editor.modal-layout.close-button.label.description": "예: \"모달 닫기\""
}

```


[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 modal-layout/messages/no.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "Avbryt",
  "admin/editor.modal-layout.close-button.title": "Lukk modalknapp",
  "admin/editor.modal-layout.close-button.label.title": "Etikett for knapp",
  "admin/editor.modal-layout.close-button.label.description": "F.eks \"Lukk 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 modal-layout/messages/da.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "Annuller",
  "admin/editor.modal-layout.close-button.title": "Vælg Modal knap",
  "admin/editor.modal-layout.close-button.label.title": "Knap mærkat",
  "admin/editor.modal-layout.close-button.label.description": "F.eks. \"Vælg 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 modal-layout/messages/nn.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "Avbryt",
  "admin/editor.modal-layout.close-button.title": "Lukk modalknapp",
  "admin/editor.modal-layout.close-button.label.title": "Etikett for knapp",
  "admin/editor.modal-layout.close-button.label.description": "F.eks \"Lukk 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 modal-layout/messages/es.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "Cancelar",
  "admin/editor.modal-layout.close-button.title": "Close Modal Button",
  "admin/editor.modal-layout.close-button.label.title": "Button label",
  "admin/editor.modal-layout.close-button.label.description": "E.g \"Close 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 modal-layout/messages/ar.json from the modal-layout VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/modal-layout.close-button.default-label": "إلغاء",
  "admin/editor.modal-layout.close-button.title": "زر نموذج الإغلاق",
  "admin/editor.modal-layout.close-button.label.title": "تسمية الزر",
  "admin/editor.modal-layout.close-button.label.description": "على سبيل المثال \"إغلاق النموذج\""
}

```