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

[User] Show me the implementation of slider-layout/react/hooks/useHovering.ts from the slider-layout VTEX app.

[Assistant]
Here's the implementation:

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

import {
  useSliderGroupState,
  useSliderGroupDispatch,
} from '../SliderLayoutGroup'

/**
 * Hook that returns the hover state of a passed ref
 * @param ref React ref
 */
const useHovering = (ref: React.RefObject<HTMLDivElement>) => {
  const [isHovering, setHovering] = useState(false)
  const groupState = useSliderGroupState()
  const groupDispatch = useSliderGroupDispatch()

  useEffect(() => {
    const onMouseEnter = () => {
      groupDispatch?.({ type: 'HOVER', payload: { isHovering: true } })

      setHovering(true)
    }

    const onMouseLeave = () => {
      groupDispatch?.({ type: 'HOVER', payload: { isHovering: false } })

      setHovering(false)
    }

    if (ref?.current) {
      ref.current.addEventListener('mouseenter', onMouseEnter)
      ref.current.addEventListener('mouseleave', onMouseLeave)
    }

    return () => {
      const { current } = ref

      if (!current) {
        return
      }

      current.removeEventListener('mouseenter', onMouseEnter)
      current.removeEventListener('mouseleave', onMouseLeave)
    }
  }, [ref, groupDispatch])

  if (groupState?.isHovering) {
    return { isHovering: true }
  }

  return { isHovering }
}

export default useHovering

```


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

[User] Show me the implementation of slider-layout/react/modules/cssHandles.ts from the slider-layout VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { createCssHandlesContext } from 'vtex.css-handles'

import { CSS_HANDLES } from '../SliderLayout'

const { CssHandlesProvider, useContextCssHandles } = createCssHandlesContext(
  CSS_HANDLES
)

export { CssHandlesProvider, useContextCssHandles }

```


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

[User] Show me the implementation of checkout-step-group/messages/pt.json from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/checkout-label": "Checkout",
  "store/checkout-autofill-message": "Bem vindo de volta! Seus dados foram preenchidos com segurança.",
  "store/checkout-autofill-close-label": "Fechar",
  "store/checkout-profile-step-title": "Perfil",
  "store/checkout-shipping-step-title": "Entrega",
  "store/checkout-address-step-title": "Endereço",
  "store/checkout-payment-step-title": "Pagamento"
}

```


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

[User] Show me the implementation of checkout-step-group/messages/en.json from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/checkout-label": "Checkout",
  "store/checkout-autofill-message": "Welcome back! Your data was filled securely.",
  "store/checkout-autofill-close-label": "Close",
  "store/checkout-profile-step-title": "Profile",
  "store/checkout-shipping-step-title": "Shipping",
  "store/checkout-address-step-title": "Address",
  "store/checkout-payment-step-title": "Payment"
}

```


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

[User] Show me the implementation of checkout-step-group/messages/es.json from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/checkout-label": "Checkout",
  "store/checkout-autofill-message": "¡Dar una buena acogida! Sus datos han sido completados de forma segura.",
  "store/checkout-autofill-close-label": "Cerca",
  "store/checkout-profile-step-title": "Perfil",
  "store/checkout-shipping-step-title": "Entrega",
  "store/checkout-address-step-title": "Dirección",
  "store/checkout-payment-step-title": "Pago"
}

```


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

[User] Show me the implementation of checkout-step-group/docs/README.md from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Checkout Step Group

The Step Group component renders a list of "steps" in the Checkout interfaces. Each step
is represented by a required part of the checkout process that the user must complete before
they finish their order.

![Illustration of the checkout step group component](https://user-images.githubusercontent.com/10223856/75803899-ed222100-5d5d-11ea-8d02-133f17950297.png)

## Configuration

1. Add the Step Group app to your theme's dependencies in the `manifest.json`. For example:

```json
{
  "dependencies": {
    "vtex.checkout-step-group": "0.x"
  }
}
```

2. Add the `checkout-step-group` block inside the block which renders the checkout. For example:

```jsonc
// interfaces.json
{
  "my-checkout-page": {
    "around": ["checkout-container"],
    "composition": "children"
  }
}
```

```jsonc
// blocks.json
{
  "my-checkout-page": {
    "children": ["checkout-step-group"]
  }
}
```

## Advanced customization

The `checkout-step-group` block renders by default 3 steps, the most common ones in the checkout process:

- `profile-step`: Renders the profile form, and the profile summary
- `shipping-step`: Renders the shipping form, which includes the address form and pickup point
- `payment-step`: Renders the payment form, with all the available payment methods in the current store

If you want to customize and remove (or add) one of these steps, you can do so by doing the following:

```jsonc
// blocks.json
{
  "checkout-step-group#my-checkout": {
    "children": [
      // you can include here only the steps you need
      // in your store
      "profile-step",
      "payment-step"
    ]
  },
  "my-checkout-page": {
    "children": ["checkout-step-group#my-checkout"]
  }
}
```

## CSS Customization

In order to apply CSS customizations in this and other blocks, follow the instructions given in [this recipe](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization)
regarding using CSS classes for store customization.

| CSS Handles |
| --- |
| `stepGroupWrapper` |
| `stepGroupList` |
| `stepGroupCheckoutLabel` |
| `step` |
| `indicator` |
| `indicatorActive` |
| `indicatorInactive` |
| `stepTitle` |
| `stepContentWrapper` |
| `stepDivider` |
| `stepContent` |

```


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

[User] Show me the implementation of checkout-step-group/react/ShippingStep.tsx from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { ButtonPlain, IconEdit } from 'vtex.styleguide'
import { Router, ContainerContext, routes } from 'vtex.checkout-container'
import { ShippingSummary, ShippingForm } from 'vtex.checkout-shipping'

import Step from './Step'

const { useHistory, useRouteMatch } = Router
const { useCheckoutContainer } = ContainerContext

const ShippingStep: React.FC = () => {
  const history = useHistory()
  const match = useRouteMatch(routes.SHIPPING)
  const { isShippingEditable } = useCheckoutContainer()

  return (
    <Step
      title={<FormattedMessage id="store/checkout-shipping-step-title" />}
      data-testid="edit-shipping-step"
      actionButton={
        !match &&
        isShippingEditable && (
          <ButtonPlain onClick={() => history.push(routes.SHIPPING)}>
            <IconEdit solid />
          </ButtonPlain>
        )
      }
      active={!!match}
    >
      <Router.Switch>
        <Router.Route path={routes.SHIPPING}>
          <ShippingForm />
        </Router.Route>
        <Router.Route path="*">
          <ShippingSummary />
        </Router.Route>
      </Router.Switch>
    </Step>
  )
}

export default ShippingStep

```


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

[User] Show me the implementation of checkout-step-group/react/StepGroup.tsx from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, {
  useMemo,
  useRef,
  useContext,
  useLayoutEffect,
  useCallback,
  useState,
} from 'react'
import { useCssHandles } from 'vtex.css-handles'
import { OrderForm } from 'vtex.order-manager'
import { Alert } from 'vtex.styleguide'
import { FormattedMessage, useIntl } from 'react-intl'

const { useOrderForm } = OrderForm

/**
 * The component below is implemented following the "guidelines" of
 * this [1] gist. It is known that creating compound components in React
 * that have a strong relation of parent-child (like a select and their
 * option's) is hard, and there is currently no good way to implement this
 * because of the lack of primitives in the library.
 *
 * [1] https://gist.github.com/ryanflorence/10e9387f633f9d2e6f444a9bddaabf6e
 */

interface StepContext {
  items: React.MutableRefObject<HTMLLIElement[]>
  assigning: React.MutableRefObject<boolean>
  activeIndex: number | undefined
  updateParent: () => void
  setActive: (element: HTMLLIElement | undefined) => void
}

const ctx = React.createContext<StepContext | undefined>(undefined)

const useForceUpdate = (): [object, () => void] => {
  const [sentinel, setSentinel] = useState<object>({})

  return [
    sentinel,
    useCallback(() => {
      setSentinel({})
    }, []),
  ]
}

export const useStepContext = () => {
  const value = useContext(ctx)

  if (!value) {
    throw new Error('useStepContext must be used inside a <StepGroup />')
  }

  return value
}

const classes = [
  'stepGroupWrapper',
  'stepGroupList',
  'stepGroupCheckoutLabel',
  'stepGroupAlert',
] as const

const StepGroup: React.FC = ({ children }) => {
  const { orderForm } = useOrderForm()
  const intl = useIntl()
  const [alertOpen, setAlertOpen] = useState(!orderForm.canEditData)

  const [activeElement, setActive] = useState<HTMLLIElement | undefined>(
    undefined
  )

  const assigning = useRef(true)

  const [sentinel, forceUpdate] = useForceUpdate()
  const stepListRef = useRef<HTMLLIElement[]>([])

  const cssHandles = useCssHandles(classes)

  useLayoutEffect(() => {
    if (assigning.current) {
      // At this point all of the children have pushed into the array so we set
      // assigning to false and force an update. Since we're in
      // useLayoutEffect, we won't get a flash of rendered content, it will all
      // happen synchronously. And now that this is false, children won't push
      // into the array on the forceUpdate
      assigning.current = false
      forceUpdate()
    } else {
      // After the forceUpdate completes, we end up here and set assigning back
      // to true for the next update from the app
      assigning.current = true
    }

    return () => {
      // this cleanup function runs right before the next render, so it's the
      // right time to empty out the array to be reassigned with whatever shows
      // up next render.
      if (assigning.current) {
        // we only want to empty out the array before the next render cycle if
        // it was NOT the result of our forceUpdate, so being guarded behind
        // assigning.current works
        stepListRef.current = []
      }
    }
  }, [forceUpdate, sentinel])

  const contextValue = useMemo(
    () => ({
      activeIndex: activeElement && stepListRef.current.indexOf(activeElement),
      setActive,
      items: stepListRef,
      assigning,
      updateParent: forceUpdate,
      sentinel,
    }),
    [activeElement, forceUpdate, sentinel]
  )

  const handleAlertClose = () => {
    setAlertOpen(false)
  }

  return (
    <ctx.Provider value={contextValue}>
      <div className={cssHandles.stepGroupWrapper}>
        <h3
          className={`${cssHandles.stepGroupCheckoutLabel} c-muted-1 f5 mb5 mb6-ns mt7 pt4`}
        >
          <FormattedMessage id="store/checkout-label" />
        </h3>
        {alertOpen && (
          <div className={`${cssHandles.stepGroupAlert} mb5 mb6-ns`}>
            <Alert
              type="success"
              closeIconLabel={intl.formatMessage({
                id: 'store/checkout-autofill-close-label',
              })}
              onClose={handleAlertClose}
            >
              <FormattedMessage id="store/checkout-autofill-message" />
            </Alert>
          </div>
        )}
        <ol className={`${cssHandles.stepGroupList} pa0 ma0`}>{children}</ol>
      </div>
    </ctx.Provider>
  )
}

export default StepGroup

```


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

[User] Show me the implementation of checkout-step-group/react/PaymentStep.tsx from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { ButtonPlain, IconEdit } from 'vtex.styleguide'
import { Router, ContainerContext, routes } from 'vtex.checkout-container'
import { Payment, PaymentSummary } from 'vtex.checkout-payment'
import { useOrderPayment } from 'vtex.order-payment/OrderPayment'

import Step from './Step'

const { useHistory, useRouteMatch } = Router
const { useCheckoutContainer } = ContainerContext

const PaymentStep: React.FC = () => {
  const history = useHistory()
  const match = useRouteMatch(routes.PAYMENT)
  const { isFreePurchase } = useOrderPayment()
  const { isPaymentEditable } = useCheckoutContainer()

  const shouldShowEditButton = !match && !isFreePurchase && isPaymentEditable

  return (
    <Step
      title={<FormattedMessage id="store/checkout-payment-step-title" />}
      data-testid="edit-payment-step"
      actionButton={
        shouldShowEditButton && (
          <ButtonPlain onClick={() => history.push(routes.PAYMENT)}>
            <IconEdit solid />
          </ButtonPlain>
        )
      }
      active={!!match}
    >
      <div hidden={!match}>
        <Payment />
      </div>
      <div hidden={match}>
        <PaymentSummary />
      </div>
    </Step>
  )
}

export default PaymentStep

```


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

[User] Show me the implementation of checkout-step-group/react/Step.tsx from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```tsx
import classNames from 'classnames'
import React, { useEffect, useLayoutEffect, useRef } from 'react'
import { useCssHandles } from 'vtex.css-handles'

import { useStepContext } from './StepGroup'

const CSS_HANDLES = [
  'step',
  'stepTitle',
  'stepContentWrapper',
  'stepContent',
  'stepDivider',
  'indicator',
  'indicatorActive',
  'indicatorInactive',
] as const

const useStepIndicator = (elementRef: React.RefObject<HTMLLIElement>) => {
  const indexRef = useRef<number>(-1)
  const { assigning, items, updateParent, ...context } = useStepContext()

  useLayoutEffect(() => {
    if (!assigning.current) {
      return
    }

    indexRef.current = items.current.push(elementRef.current!) - 1
    updateParent()
  })

  return {
    // index is wrong on the first render, but the parent forces a
    // synchronous second render that fixes its value without flashing
    // the component
    index: indexRef.current,
    lastIndex: items.current.length - 1,
    ...context,
  }
}

interface StepProps {
  title: React.ReactNode
  'data-testid'?: string
  actionButton?: React.ReactNode
  active?: boolean
}

const Step: React.FC<StepProps> = ({
  children,
  title,
  'data-testid': dataTestId,
  active = false,
  actionButton = null,
}) => {
  const elementRef = useRef<HTMLLIElement>(null)
  const { index, lastIndex, activeIndex, setActive } = useStepIndicator(
    elementRef
  )

  useEffect(() => {
    if (!active) {
      return
    }

    setActive(elementRef.current!)

    return () => setActive(undefined)
  }, [active, index, setActive])

  const handles = useCssHandles(CSS_HANDLES)

  const isActive = activeIndex === index

  const borderWidth = (index ?? 0) < lastIndex ? 1 : 0

  return (
    <li
      className={classNames(handles.step, 'flex flex-wrap items-center')}
      ref={elementRef}
    >
      <span
        className={classNames(
          handles.indicator,
          'w1 h1 br-100 b flex items-center justify-center',
          {
            [handles.indicatorInactive]: !isActive,
            [handles.indicatorActive]: isActive,
            'bg-muted-5 c-on-muted-5 pa2 pa3-ns f6 f5-ns': !isActive,
            'bg-muted-4 c-on-muted-4 na2-ns pa3 pa4-ns f5 f4-ns': isActive,
          }
        )}
      >
        {index + 1}
      </span>
      <span
        className={classNames(
          handles.stepTitle,
          'flex items-center lh-copy ml3 ml4-ns pl2-ns',
          {
            'c-muted-1': activeIndex !== undefined && !isActive,
          }
        )}
      >
        <h2 className={classNames('mv0 fw6', { f5: !active, f4: active })}>
          {title}
        </h2>
        {actionButton && (
          <div className="pl4" data-testid={dataTestId}>
            {actionButton}
          </div>
        )}
      </span>
      <div
        className={classNames(
          handles.stepContentWrapper,
          'mt4 mb6 mb7-ns w-100 flex',
          {
            'mt3-ns': !active,
            'mt5-ns': active,
          }
        )}
      >
        <div
          style={{ width: borderWidth, minWidth: borderWidth }}
          className={classNames(
            handles.stepDivider,
            'dn db-ns bg-muted-4 nt4 nb6 nb7-ns mh5',
            {
              'nt3-ns': !active,
              'nt5-ns': active,
            }
          )}
        />
        <div className={classNames(handles.stepContent, 'ml5-ns w-100 pr8-ns')}>
          {children}
        </div>
      </div>
    </li>
  )
}

export default Step

```


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

[User] Show me the implementation of checkout-step-group/react/package.json from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "vtex.checkout-step-group",
  "version": "0.13.0",
  "private": true,
  "license": "UNLICENSED",
  "dependencies": {
    "classnames": "^2.2.6",
    "react": "^16.12.0",
    "react-intl": "^3.12.0"
  },
  "devDependencies": {
    "@types/classnames": "^2.2.9",
    "@types/node": "^13.7.2",
    "@types/react": "^16.9.20",
    "@types/react-dom": "^16.9.5",
    "vtex.checkout-container": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-container@0.7.0/public/@types/vtex.checkout-container",
    "vtex.checkout-payment": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-payment@0.13.0/public/@types/vtex.checkout-payment",
    "vtex.checkout-profile": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-profile@0.3.0/public/@types/vtex.checkout-profile",
    "vtex.checkout-shipping": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-shipping@0.7.1/public/@types/vtex.checkout-shipping",
    "vtex.css-handles": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles",
    "vtex.order-manager": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.9.0/public/@types/vtex.order-manager",
    "vtex.order-payment": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-payment@0.8.0/public/@types/vtex.order-payment",
    "vtex.order-shipping": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-shipping@0.7.0/public/@types/vtex.order-shipping",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.126.11/public/@types/vtex.render-runtime",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.135.3/public/@types/vtex.styleguide"
  }
}

```


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

[User] Show me the implementation of checkout-step-group/react/ProfileStep.tsx from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { ButtonPlain, IconEdit } from 'vtex.styleguide'
import { Router, ContainerContext, routes } from 'vtex.checkout-container'
import { ProfileForm, ProfileSummary } from 'vtex.checkout-profile'
import { OrderForm } from 'vtex.order-manager'

import Step from './Step'

const { useOrderForm } = OrderForm
const { useHistory, useRouteMatch } = Router
const { useCheckoutContainer } = ContainerContext

const ProfileStep: React.FC = () => {
  const { orderForm } = useOrderForm()
  const history = useHistory()
  const match = useRouteMatch(routes.PROFILE)
  const { requestLogin, isProfileEditable } = useCheckoutContainer()

  const handleProfileEdit = () => {
    if (orderForm.canEditData) {
      history.push(routes.PROFILE)
    } else {
      requestLogin()
    }
  }

  return (
    <Step
      title={<FormattedMessage id="store/checkout-profile-step-title" />}
      data-testid="edit-profile-step"
      actionButton={
        !match &&
        isProfileEditable && (
          <ButtonPlain onClick={handleProfileEdit}>
            <IconEdit solid />
          </ButtonPlain>
        )
      }
      active={!!match}
    >
      <Router.Switch>
        <Router.Route path={routes.PROFILE}>
          <ProfileForm />
        </Router.Route>
        <Router.Route path="*">
          <ProfileSummary />
        </Router.Route>
      </Router.Switch>
    </Step>
  )
}

export default ProfileStep

```


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

[User] Show me the implementation of checkout-step-group/react/AddressStep.tsx from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { ButtonPlain, IconEdit } from 'vtex.styleguide'
import { Router, ContainerContext, routes } from 'vtex.checkout-container'
import { AddressSummary, ShippingAddress } from 'vtex.checkout-shipping'
import { OrderForm } from 'vtex.order-manager'
import { OrderShipping } from 'vtex.order-shipping'

import Step from './Step'

const { useOrderForm } = OrderForm
const { useOrderShipping } = OrderShipping
const { useHistory, useRouteMatch } = Router
const { useCheckoutContainer } = ContainerContext

const AddressStep: React.FC = () => {
  const history = useHistory()
  const match = useRouteMatch(routes.ADDRESS)
  const { requestLogin, isAddressEditable } = useCheckoutContainer()
  const { orderForm } = useOrderForm()
  const { selectedAddress } = useOrderShipping()

  const handleAddressEdit = () => {
    if (orderForm.canEditData || selectedAddress?.isDisposable) {
      history.push(routes.ADDRESS)
    } else {
      requestLogin()
    }
  }

  return (
    <Step
      title={<FormattedMessage id="store/checkout-address-step-title" />}
      data-testid="edit-address-step"
      actionButton={
        !match &&
        isAddressEditable && (
          <ButtonPlain onClick={handleAddressEdit}>
            <IconEdit solid />
          </ButtonPlain>
        )
      }
      active={!!match}
    >
      <Router.Switch>
        <Router.Route path={routes.ADDRESS}>
          <ShippingAddress />
        </Router.Route>
        <Router.Route path="*">
          <AddressSummary />
        </Router.Route>
      </Router.Switch>
    </Step>
  )
}

export default AddressStep

```


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

[User] Show me the implementation of checkout-step-group/store/blocks.json from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "checkout-step-group": {
    "children": [
      "profile-step",
      "shipping-step",
      "address-step",
      "payment-step"
    ]
  }
}

```


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

[User] Show me the implementation of checkout-step-group/store/interfaces.json from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "checkout-step-group": {
    "component": "StepGroup",
    "composition": "children"
  },
  "checkout-step": {
    "component": "Step",
    "composition": "children"
  },
  "profile-step": {
    "component": "ProfileStep"
  },
  "shipping-step": {
    "component": "ShippingStep",
    "preview": {
      "type": "box",
      "height": 250,
      "fullWidth": true,
      "options": {
        "padding": 0
      }
    }
  },
  "address-step": {
    "component": "AddressStep",
    "preview": {
      "type": "box",
      "height": 250,
      "fullWidth": true,
      "options": {
        "padding": 0
      }
    }
  },
  "payment-step": {
    "component": "PaymentStep"
  }
}

```


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

[User] Show me the implementation of checkout-step-group/react/typings/vtex.order-payment.d.ts from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.order-payment/OrderPayment' {
  export * from 'vtex.order-payment/react/OrderPayment'
  export { default } from 'vtex.order-payment/react/OrderPayment'
}

```


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

[User] Show me the implementation of checkout-step-group/react/typings/vtex.checkout-payment.d.ts from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.checkout-payment/Payment' {
  export { default } from 'vtex.checkout-payment/react/Payment'
}

```


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

[User] Show me the implementation of checkout-step-group/react/typings/assets.d.ts from the checkout-step-group VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.css' {
  const styles: { [name: string]: string }
  export default styles
}

```


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

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

[Assistant]
Here's the implementation:

```typescript
import * as Styleguide from 'vtex.styleguide'

declare module 'vtex.styleguide' {
  import React from 'react'

  export const Alert: React.FC

  export const Button: React.FC

  export const Input: React.FC

  export const IconCheck: React.FC
  export const IconClose: React.FC
  export const IconEdit: React.FC
}

```


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

[Assistant]
Here's the implementation:

```markdown
# RTB House

The RTB House engine, one of its kind powered by **deep learning algorithms**, identifies potential buyers and boosts performance via 1:1 ultra-personalized retargeting **up to 50 percent more efficient** than standard machine learning AI-based approaches.
For more information please visit, [RTB HOUSE](https://www.rtbhouse.com/) website.

## App Installation
Open the VTEX APP Store and install the RTB HOUSE app on your store.

or

Run the following command:

```sh
vtex install vtex.rtbhouse@1.x
```

Next, open the app settings on your admin and fill the form with your RTB House 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 rtbhouse/react/index.tsx from the rtbhouse VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { canUseDOM } from 'vtex.render-runtime'
import { PixelMessage } from './typings/events'
import { getCategories, getDepartment, createIframeTag } from './helpers/index'

function handleMessages(e: PixelMessage) {
  const { rtbhouseId } = window
  switch (e.data.eventName) {
    case 'vtex:pageInfo': {
      createIframeTag(`//us.creativecdn.com/tags?id=pr_${rtbhouseId}&ncm=1`)
      if (e.data.eventType !== 'homeView') break
      const iframeId = 'rtbhouse_home'
      const src = `//us.creativecdn.com/tags?id=pr_${rtbhouseId}_home`
      const iframe = document.getElementById(iframeId)
      if (!iframe) createIframeTag(src, iframeId)
      break
    }
    case 'vtex:productView': {
      const {
        product: { productId },
      } = e.data
      if (productId)
        createIframeTag(
          `//us.creativecdn.com/tags?id=pr_${rtbhouseId}_offer_${productId}`
        )
      break
    }
    case 'vtex:internalSiteSearchView': {
      const { products } = e.data
      const skus = products
        .map(({ productId }) => productId)
        .slice(0, 5)
        .join()
      createIframeTag(
        `//us.creativecdn.com/tags?id=pr_${rtbhouseId}_listing_${skus}`,
        'rtbhouse_search'
      )
      break
    }
    case 'vtex:categoryView': {
      const { products } = e.data
      const categories = getCategories(products)
      createIframeTag(
        `//us.creativecdn.com/tags?id=pr_${rtbhouseId}_category2_${categories}`,
        'rtbhouse_category'
      )
      break
    }
    case 'vtex:departmentView': {
      const { products } = e.data
      const categories = getDepartment(products)
      const department = categories[0]
      createIframeTag(
        `//us.creativecdn.com/tags?id=pr_${rtbhouseId}_category2_${department}`,
        'rtbhouse_category'
      )
      break
    }
    case 'vtex:orderPlaced': {
      const { transactionSubtotal, transactionId, transactionProducts } = e.data
      const skus = transactionProducts.map(({ id }) => id).join(',')
      createIframeTag(
        `//us.creativecdn.com/tags?id=pr_${rtbhouseId}_orderstatus2_${transactionSubtotal}_${transactionId}_${skus}&cd=default`,
        'rtbhouse_purchase'
      )
      break
    }
    default:
      break
  }
}

function handleLoad() {
  const {
    rtbhouseId,
    location: { pathname },
  } = window
  if (pathname !== '/login') return
  const iframeId = 'rtbhouse_otherPages'
  const iframe = document.getElementById(iframeId)
  if (!iframe)
    createIframeTag(
      `//us.creativecdn.com/tags?id=pr_${rtbhouseId}&ncm=1`,
      iframeId
    )
}

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

```


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

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "devDependencies": {
    "@types/graphql": "^14.2.0",
    "@types/jest": "^24.0.11",
    "@types/node": "^11.13.0",
    "@vtex/test-tools": "^1.1.0",
    "eslint": "^5.16.0",
    "eslint-config-vtex-react": "^4.1.0",
    "prettier": "^1.18.2",
    "tslint-eslint-rules": "^5.4.0",
    "typescript": "3.7.3",
    "vtex.render-runtime": "http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.render-runtime@8.50.0/public/_types/react",
    "vtex.pixel-interfaces": "http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.pixel-interfaces@1.1.0/public/_types/react"
  },
  "version": "1.0.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 rtbhouse/store/interfaces.json from the rtbhouse VTEX app.

[Assistant]
Here's the implementation:

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

[Assistant]
Here's the implementation:

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

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

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

export interface PageInfoData extends EventData {
  event: 'pageInfo'
  eventName: 'vtex:pageInfo'
  eventType: string
  pageUrl: string
}

export interface InternalSiteSearchViewData extends EventData {
  event: 'internalSiteSearchView'
  eventName: 'vtex:internalSiteSearchView'
  products: Product[]
  currency: string
}

export interface CategoryViewData extends EventData {
  event: 'categoryView'
  eventName: 'vtex:categoryView'
  products: Product[]
  currency: string
}

export interface DepartmentData extends EventData {
  event: 'departmentView'
  eventName: 'vtex:departmentView'
  products: Product[]
  currency: string
}

export interface AddToCartData extends EventData {
  event: 'addToCart'
  eventName: 'vtex:addToCart'
  items: CartItem[]
}

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

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

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

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

export interface ProductImpressionData extends EventData {
  event: 'productImpression'
  eventName: 'vtex:productImpression'
  impressions: Impression[]
  product?: Product // deprecated, use impressions list!
  position?: number // deprecated, use impressions list!
  list: string
}

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

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

export interface Impression {
  product: Product
  position: number
}

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

interface ShippingMethod {
  itemId: string
  selectedSla: string
}

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

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

interface Product {
  brand: string
  categoryId?: string // inconsistency
  categories: string[]
  productId: string
  productName: string
  selectedSku: {
    itemId: 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 rtbhouse/react/typings/vtex.render-runtime.d.ts from the rtbhouse 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 rtbhouse/react/typings/global.d.ts from the rtbhouse VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface Window extends Window {
  rtbhouseId: 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 rtbhouse/react/helpers/index.tsx from the rtbhouse VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { Product } from '../typings/events'

export function getCategories(products: Product[]) {
  const [categories] = products.map(({ categories: [category] }) =>
    strNormalize(
      category
        .split('/')
        .filter(item => item)
        .join(',')
    )
  )
  return categories
}

export function getDepartment(products: Product[]) {
  const [department] = products.map(
    ({ categories: [category] }) =>
      category.split('/').filter(item => item)
  )
  return department
}

export function createIframeTag(src: string, id?: string) {
  const iframe = document.createElement('iframe')
  iframe.setAttribute('src', src)
  id && iframe.setAttribute('id', id)
  iframe.setAttribute('width', '1')
  iframe.setAttribute('height', '1')
  iframe.setAttribute('scrolling', '1')
  iframe.setAttribute('frameborder', '0')
  iframe.setAttribute('style', 'display:none')
  document.body.appendChild(iframe)
}

export function strNormalize(str: string): string {
  let strNormalized = str.normalize("NFD").replace(/[\u0300-\u036f]/g, "")
  return strNormalized
}

```


[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 omnichannel-order-status/messages/pt.json from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "b2bOrders.link": "Pedidos B2B",
  "titleOrderDetails": "Detalhes do pedido",
  "title.OrderPage": "Pedido B2B",
  "message.results": "Nenhum registro encontrado",
  "message.error": "Erro ao carregar dados. Por favor, tenten novamente.",
  "title.searchOrders": "Pesquisar por número de pedido",
  "title.searchDate": "Pesquisar por data",
  "label.numberOrderWeb": "Número pedido web",
  "label.numberDigimess": "Número pedido ERP",
  "label.myOrder": "Meu pedido",
  "label.date": "Data",
  "label.dateUpTo": "Até",
  "btn.search": "Pesquisar",
  "table.orderNumber": "Númedo do pedido",
  "table.orderStatus": "Status do pedido",
  "table.orderDate": "Data do pedido",
  "table.orderTotal": "Total do pedido",
  "table.details": "Detalhes",
  "table.invoice": "Nota fiscal",
  "table.name": "Nome",
  "order.tracking": "Rastreamento do pedido",
  "order.inAnalysis": "Em analise",
  "order.waiting": "Aguardando",
  "order.commercialRelease": "Liberação Comercial",
  "order.financeRelease": "Liberação Financeira",
  "order.separation": "Separação",
  "order.dispatch": "Despacho",
  "order.delivery": "Entrega",
  "order.billingAddress": "Endereço de cobrança",
  "order.deliveryAddress": "Endereço de entrega",
  "order.otherInformations": "Outras informações",
  "order.purchaseData": "Dados da compra",
  "table.price": "Preço",
  "table.quantity": "Quantidade",
  "table.freight": "Frete",
  "title.serviceTax": "Serviços & Área fiscal",
  "table.city": "Cidade",
  "table.state": "Estado",
  "table.address": "Endereço",
  "table.zipCode": "Cep",
  "table.methodPayment": "Forma de pagamento",
  "table.optionPayment": "Opção de pagamento",
  "label.required": "Informe um valor",
  "table.deliveryMethod": "Método de entrega",
  "table.carrierLink": "Link da Transportadora"
}
```


[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 omnichannel-order-status/messages/en.json from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "b2bOrders.link": "Orders B2B",
  "titleOrderDetails": "Order Details",
  "title.OrderPage": "Order B2B",
  "message.results": "No record found",
  "message.error": "Error on load data. Please, try again.",
  "title.searchOrders": "Search by order number",
  "title.searchDate": "Search by date",
  "label.numberOrderWeb": "Web number order",
  "label.numberDigimess": "ERP order number",
  "label.myOrder": "My order",
  "label.date": "Date",
  "label.dateUpTo": "Up to",
  "btn.search": "Search",
  "table.orderNumber": "Order number",
  "table.orderStatus": "Order status",
  "table.orderDate": "Order date",
  "table.orderTotal": "Order total",
  "table.details": "Details",
  "table.invoice": "Invoice",
  "table.name": "Name",
  "order.tracking": "Order tracking",
  "order.inAnalysis": "in analysis",
  "order.waiting": "Waiting",
  "order.commercialRelease": "Commercial release",
  "order.financeRelease": "Finance release",
  "order.separation": "Separation",
  "order.dispatch": "Dispatch",
  "order.delivery": "Delivery",
  "order.billingAddress": "Billing Address",
  "order.deliveryAddress": "Delivery Address",
  "order.otherInformations": "Other Informations",
  "order.purchaseData": "Purchase Data",
  "table.price": "Price",
  "table.quantity": "Quantity",
  "table.freight": "Freight",
  "title.serviceTax": "Services & Taxes",
  "table.city": "City",
  "table.state": "State",
  "table.address": "Address",
  "table.zipCode": "Zip Code",
  "table.methodPayment": "Payment Method",
  "table.optionPayment": "Payment information",
  "label.required": "Fill this field",
  "table.deliveryMethod": "Delivery Method",
  "table.carrierLink": "Carrier Link"
}
```


[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 omnichannel-order-status/messages/context.json from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "b2bOrders.link": "Orders B2B",
  "titleOrderDetails": "Orders Details",
  "title.OrderPage": "Order B2B",
  "message.results": "No record found",
  "message.error": "Error on load data. Please, try again.",
  "title.searchOrders": "Search by order number",
  "title.searchDate": "Search by date",
  "label.numberOrderWeb": "Web number order",
  "label.numberDigimess": "ERP order number",
  "label.myOrder": "My order",
  "label.date": "Date",
  "label.dateUpTo": "Up to",
  "btn.search": "Search",
  "table.orderNumber": "Order number",
  "table.orderStatus": "Order status",
  "table.orderDate": "Order date",
  "table.orderTotal": "Order total",
  "table.details": "Details",
  "table.invoice": "Invoice",
  "table.name": "Name",
  "order.tracking": "Order tracking",
  "order.inAnalysis": "in analysis",
  "order.waiting": "Waiting",
  "order.commercialRelease": "Commercial release",
  "order.financeRelease": "Finance release",
  "order.separation": "Separation",
  "order.dispatch": "Dispatch",
  "order.delivery": "Delivery",
  "order.billingAddress": "Billing Address",
  "order.deliveryAddress": "Delivery Address",
  "order.otherInformations": "Other Informations",
  "order.purchaseData": "Purchase Data",
  "table.price": "Price",
  "table.quantity": "Quantity",
  "table.freight": "Freight",
  "title.serviceTax": "Services & Tax Area",
  "table.city": "City",
  "table.state": "State",
  "table.address": "Address",
  "table.zipCode": "Zip Code",
  "table.methodPayment": "Form Payment",
  "table.optionPayment": "Option Payment",
  "label.required": "Fill this field"
}
```


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

[Assistant]
Here's the implementation:

```markdown
# B2B Orders

In a B2B business model, your company and your partners may need to share selected information, such as order statuses.

For these scenarios, we recommend that you install and set up the *B2B Orders* app in your VTEX account.

By communicating with your *Enterprise resource planning (ERP)*, this app allows your business' customers to securely check their order status at any time they want.

For more information on how to set up the *B2B Orders* app and its related external APIs to the ERP, check the following section.

### Prerequisites - Changes to existing **CL** table
We need to add one field to existing **CL** master data table.
```
companyId: Integer
```

This field is an identifier that will be automatically passed when requesting the APIs below. Thus, the endpoints will be able to know which client is involved in the request

> **companyId** field should check following checkboxes
> **Is nullable**,
> **Make readable without credential**,
> **Allow editing without credential**,
> **Allow filter without credential**,
> **Is searchable**,
> **Is filterable**,

Dont forget to `save` and `reindex` `CL` table once you add all the fields.

## Install and setup

1. Clone this app using you prefered git app

2. At the manifest.json file, change the value of `policies` -> `attrs` -> `host` setting the hostname of your API. Eg: apivtex.vtex.com.br

3. Using a testing workspace, kink the app using `vtex link` [https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-linking-an-app]

4. In your browser, access your account's admin as in `https://{workspace}--{accountname}.myvtex.com/admin`.

>⚠ *Remember to replace the values between the curly brackets according to your scenario.*

5. Under `Account Settings`, go to `Apps > My apps`. Look for the *B2B Orders*.

6. Click on `Settings` to set up the necessary information for communicating with the desired service. That is:

- **Link endpoint** - the endpoint address of the desired service.
- **Login** - credentials for accessing the service.
- **Token** - authentication token for accessing the service.

![omnichannel-order](https://user-images.githubusercontent.com/60782333/99416894-17aa0f00-28d8-11eb-8414-28ded9fc2d1e.png)

>⚠ *So that the *B2B Orders* app can properly work, your ERP API must have different endpoints for each of the following scenarios: order search, order details, order documents. To learn more about it, check the [ERP API requirements](#erp-api-requirements) section.*

7. Save your changes.

Once your changes are duly saved, a new option, namely **Orders B2B**, will be available in your client's menu, as in the following image:

![client-view](https://user-images.githubusercontent.com/60782333/95912705-83e5a000-0d79-11eb-866c-f6f10832a36f.png)

>⚠ After you finished you testing API, don't forget to publish and install at your master workspace. Instructions here: https://vtex.io/docs/recipes/development/publishing-an-app

## ERP API requirements

To facilitate its implementation, the *B2B Orders* app comes with a well-defined pattern for communicating with the ERP API.

This pattern implies that your company's ERP API has different endpoints for each of the following scenarios:

- Order search.
- Order details.
- [OPTIONAL] Order documents.

>⚠ *For specific needs, not satisfied by the scenarios presented, you might need to customize the B2B Orders.*

In the following, we present the possible requests and response format for each one of the ERP API's related endpoints.

### Order search

By exposing the `POST` `api/v1/pedido/pesquisa` endpoint, your company's client will be able to search for orders in the ERP by filling one of the following objects: `porPeriodo`, `porCodigo` or `porNotaFiscal`.

#### Request format

```
{
  "revendaId": number,
  "porCodigo": {
    "codigo": string,
    "tipo": number (PedidoId: 0, PedidoClienteId: 1, PedidoErpId: 2)
  },
  "porPeriodo": {
    "dataInicial": Date,
    "dataFim": Date
  },
  "porNotaFiscal": {
    "notaFiscal": string,
    "serieNotaFiscal": string
  }
}

```

#### Response format

```
{
  "itens": [
    {
      "pedidoErpId": string,
      "pedidoClienteId": string,
      "totalPedido": number,
      "status": number,
      "dataPedido": Date,
      "observacao": string,
      "notaFiscal": string,
      "serieNotaFiscal": string,
    }
  ]
}

```

### Order Details

By exposing the `GET` `api/v1/pedido?pedidoErpId={pedidoErpId}&revendaId={revendaId}` endpoint, your company's client will be able to consult the details of a specific order directly from the ERP.

#### Request format

```
{
  pedidoErpId: string
  revendaId: number
}

```

#### Response format

```
{
  "pedidoErpId": string,
  "status": integer,
  "itens": [
    {
      "partNumber": string,
      "descricaoDoProduto": string,
      "quantidade": decimal number,
      "valorUnitario": decimal number,
      "valorTotal": decimal number,
      "comissao": decimal number
    }
  ],
  "revendaId": integer,
  "clienteFinalId": string,
  "clienteFinalCnpj": string,
  "clienteFinalCpf": string,
  "clienteFinalNome": string,
  "valorFrete": decimal number,
  "valorTotalPedido": decimal number,
  "dataPedido": Date,
  "dataPrevisaoEntrega": Date,
  "observacao": string,
  "notaFiscal": string",
  "serieNotaFiscal": string,
  "paymentMethod": string,
  "paymentOptions": string,
  "linkTransportadora": string,
  "billingAddressCorpname": string,
  "billingAddressFormattedAddres": string,
  "billingAddressCity": string,
  "billingAddressState": string,
  "billingAddresszipcode": string,
  "deliveryAddressCorpname": string,
  "deliveryAddressformattedAddres": string,
  "deliveryAddressCity": string,
  "deliveryAddressState": string,
  "deliveryAddresszipcode": string,
  "paymentMethod": string,
  "paymentOptions": string,
  "deliveryMethod": string,
  "centrosDeDistribuicao": [
    {
      "distributionCenterPrefix": string,
      "itens": [
        {
          "partNumber": string,
          "descricaoDoProduto": string,
          "quantidade": decimal number,
          "valorUnitario": decimal number,
          "valorTotal": decimal number,
          "comissao": decimal number
        }
      ],
      "valorFrete": decimal number,
      "valorTotalCD": decimal number
    },
    {
      "distributionCenterPrefix": string,
      "itens": [
        {
          "partNumber": string,
          "descricaoDoProduto": string,
          "quantidade": decimal number,
          "valorUnitario": decimal number,
          "valorTotal": decimal number,
          "comissao": decimal number
        }
      ],
      "valorFrete": decimal number,
      "valorTotalCD": decimal number
    }
  ]
}

```

### [OPTIONAL] Order documents

By exposing the `GET` `api/v1/arquivospedido?pedidoErpId={pedidoErpId}&revendaId={revendaId}` endpoint, your company's client will be able to consult the document files related to a given order by providing the related order number.

#### Request format

```
{
  pedidoErpId: string
  revendaId: number
}

```

#### Response format

```
{
  "pedidoErpId": string,
  "itens": [
    {
      "tipoArquivo": number (SegundaViaBoleto: 0, SegundaViaTransferencia: 1, Xml: 2, Danfe: 3, NumeroDeSerie: 4, GARE: 5, GNRE: 6, Outros: 7),
      "descricao": string,
      "url": string"
    },
    {
      "tipoArquivo": number,
      "descricao": string,
      "url": 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 omnichannel-order-status/node/service.json from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "memory": 256,
  "ttl": 10,
  "timeout": 10,
  "minReplicas": 2,
  "maxReplicas": 4,
  "routes": {
    "ordersb2b": {
      "path": "/_v/ordersb2b/:order",
      "public": true
    },
    "ordersDate": {
      "path": "/_v/ordersb2b/date",
      "public": true
    },
    "ordersFiles": {
      "path": "/_v/ordersb2b/files/:order",
      "public": true
    }
  }
}

```


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

[User] Show me the implementation of omnichannel-order-status/node/package.json from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "dependencies": {
    "co-body": "^6.0.0",
    "ramda": "^0.25.0"
  },
  "devDependencies": {
    "@types/co-body": "^0.0.3",
    "@types/jest": "^24.0.18",
    "@types/node": "8.x",
    "@types/ramda": "types/npm-ramda#dist",
    "@vtex/api": "3.8.1",
    "@vtex/test-tools": "^1.0.0",
    "tslint": "^5.14.0",
    "tslint-config-vtex": "^2.1.0",
    "typescript": "3.9.7"
  },
  "scripts": {
    "lint": "tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'"
  },
  "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 omnichannel-order-status/node/index.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { ClientsConfig, Service, ServiceContext } from '@vtex/api'

import { Clients } from './clients'
import {
  ordersMiddleware,
  ordersFilesMiddleware,
  ordersPeriodMiddleware,
} from './middlewares/orders'

import { orderValidationMiddleware } from './middlewares/oderValidation'

const TIMEOUT_MS = 10000

const clients: ClientsConfig<Clients> = {
  implementation: Clients,
  options: {
    default: {
      retries: 2,
      timeout: TIMEOUT_MS,
    },
  },
}

declare global {
  type Context = ServiceContext<Clients, State>
  interface State {
    order: String
  }
}

// Export a service that defines route handlers and client options.
export default new Service<Clients, State>({
  clients,
  routes: {
    // `status` is the route ID from service.json. It maps to an array of middlewares (or a single handler).
    ordersb2b: [orderValidationMiddleware, ordersMiddleware],
    ordersFiles: [orderValidationMiddleware, ordersFilesMiddleware],
    ordersDate: [ordersPeriodMiddleware],
  },
})

```


[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 omnichannel-order-status/react/OrdersB2BPage.tsx from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```tsx

import React, { Fragment } from 'react'
import { Route } from 'react-router-dom'

// Your component pages
import OrderB2B from './components/OrdersB2B'
import OrderDetail from './components/OrderDetails'

const OrdersB2BPage = () => (
   <Fragment>
      <Route path="/b2b-order" component={OrderB2B}/>
      <Route path="/b2b-order-details/:order" component={OrderDetail}/>
   </Fragment>
)

export default OrdersB2BPage
```


[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 omnichannel-order-status/react/OrdersB2BLink.tsx from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { FunctionComponent } from 'react'
import { InjectedIntlProps, injectIntl } from 'react-intl'

const OrdersB2BLink: FunctionComponent<Props> = ({ render, intl }) => {
   return render([
      {
         name: intl.formatMessage({
            id: 'b2bOrders.link',
         }),
         path: '/b2b-order',
      },
   ])
}

interface Props extends InjectedIntlProps {
   render: (args: { name: string; path: string }[]) => any
}

export default injectIntl(OrdersB2BLink)
```


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

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test",
    "lint": "tsc --noEmit && eslint --ext js,ts,tsx .",
    "format": "prettier --write \"**/*.{ts,js,json}\""
  },
  "dependencies": {
    "@vtex/css-handles": "^1.0.0",
    "@vtex/styleguide": "^9.135.4",
    "axios": "^0.19.2",
    "classnames": "^2.2.6",
    "ramda": "^0.26.1",
    "react": "^16.8.3",
    "react-apollo": "^3.1.3",
    "react-dom": "^16.8.3",
    "react-intl": "^2.7.2",
    "react-router-dom": "^4.3.1"
  },
  "devDependencies": {
    "@types/classnames": "^2.2.7",
    "@types/jest": "^24.0.18",
    "@types/node": "^12.7.5",
    "@types/prop-types": "^15.7.0",
    "@types/ramda": "^0.26.5",
    "@types/react": "^16.9.2",
    "@types/react-datepicker": "^2.11.0",
    "@types/react-router-dom": "^5.1.5",
    "@vtex/test-tools": "^1.1.0",
    "apollo-client": "^2.5.1",
    "eslint": "^5.16.0",
    "eslint-config-vtex-react": "^4.1.0",
    "@vtex/prettier-config": "^0.1.3",
    "tslint-eslint-rules": "^5.4.0",
    "typescript": "3.9.7",
    "vtex.css-handles": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.2/public/@types/vtex.css-handles",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.94.0/public/@types/vtex.render-runtime",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.135.4/public/@types/vtex.styleguide"
  },
  "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 omnichannel-order-status/store/interfaces.json from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "my-account-link.orders-b2b-link": {
    "component": "OrdersB2BLink"
  },
  "my-account-link.orders-b2b-page": {
    "component": "OrdersB2BPage"
  }
}
```


[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 omnichannel-order-status/store/plugins.json from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```json
{
   "my-account-menu > my-account-link": "my-account-link.orders-b2b-link",
   "my-account-pages > my-account-page": "my-account-link.orders-b2b-page"
}
```


[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 omnichannel-order-status/node/clients/order.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

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

export default class Orders extends ExternalClient {
  constructor(context: IOContext, options?: InstanceOptions) {
    super('', context, options)
  }

  public async getOrganization(
    hostSite: String,
    email: String
  ): Promise<IOResponse<string>> {
    return this.http.getRaw(
      `http://${hostSite}/api/dataentities/CL/search?_fields=companyId&_where=email=${email}`,
      {
        metric: 'get-email',
      }
    )
  }

  public async getOrdersWithHeaders(
    order: String,
    endpoint: String,
    token: String,
    revendaId: String
  ): Promise<IOResponse<string>> {
    return this.http.getRaw(
      endpoint +
        '/api/v1/pedido/?pedidoErpId=' +
        order +
        '&revendaId=' +
        revendaId,
      {
        metric: 'status-get-raw',
        headers: {
          Authorization: 'Bearer ' + token + '',
        },
      }
    )
  }

  public async getOrdersFilesWithHeaders(
    order: String,
    endpoint: String,
    token: String,
    revendaId: String
  ): Promise<IOResponse<string>> {
    return this.http.getRaw(
      endpoint +
        '/api/v1/ArquivosPedido/?pedidoErpId=' +
        order +
        '&revendaId=' +
        revendaId,
      {
        metric: 'status-get-raw',
        headers: {
          Authorization: 'Bearer ' + token + '',
        },
      }
    )
  }

  public async postOrdersPeriod(
    body: any,
    endpoint: String,
    token: String
  ): Promise<IOResponse<string>> {
          return this.http.postRaw(endpoint + '/api/v1/pedido/pesquisa', body, {
      metric: 'get-order',
      headers: {
        Authorization: 'Bearer ' + token + '',
        'Content-Type': 'application/json',
      },
    })
  }
}

```


[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 omnichannel-order-status/node/clients/index.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

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

import Ordersb2b from './order'

export class Clients extends IOClients {
  public get orders() {
    return this.getOrSet('orders', Ordersb2b)
  }
}

```


[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 omnichannel-order-status/node/middlewares/orders.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { json } from 'co-body'

export async function ordersMiddleware(ctx: Context, next: () => Promise<any>) {
  const {
    state: { order },
    clients: { orders: statusClient },
  } = ctx

  const appId = process.env.VTEX_APP_ID as string
  const settings = await ctx.clients.apps.getAppSettings(appId)
  const email = ctx.request.header['x-vtex-caller']
  const hostSite = ctx.request.header['x-forwarded-host']

  const { data: organizationId }: any = await statusClient.getOrganization(
    hostSite,
    email
    )

  const {
    headers,
    data,
    status: responseStatus,
  } = await statusClient.getOrdersWithHeaders(
    order,
    settings.endpoint,
    settings.token,
    organizationId[0].companyId
  )

  ctx.status = responseStatus
  ctx.body = data
  ctx.set('Cache-Control', headers['cache-control'])

  await next()
}

export async function ordersFilesMiddleware(
  ctx: Context,
  next: () => Promise<any>
) {
  const {
    state: { order },
    clients: { orders: statusClient },
  } = ctx

  const appId = process.env.VTEX_APP_ID as string
  const settings = await ctx.clients.apps.getAppSettings(appId)
  const email = ctx.request.header['x-vtex-caller']
  const hostSite = ctx.request.header['x-forwarded-host']

  const { data: organizationId }: any = await statusClient.getOrganization(
    hostSite,
    email
    )

  const {
    headers,
    data,
    status: responseStatus,
  } = await statusClient.getOrdersFilesWithHeaders(
    order,
    settings.endpoint,
    settings.token,
    organizationId[0].companyId
  )

  ctx.status = responseStatus
  ctx.body = data
  ctx.set('Cache-Control', headers['cache-control'])

  await next()
}

export async function ordersPeriodMiddleware(
  ctx: Context,
  next: () => Promise<any>
) {
  const {
    clients: { orders: statusClient },
  } = ctx

  const appId = process.env.VTEX_APP_ID as string
  const settings = await ctx.clients.apps.getAppSettings(appId)
  const email = ctx.request.header['x-vtex-caller']
  const hostSite = ctx.request.header['x-forwarded-host']

  const { data: organizationId }: any = await statusClient.getOrganization(
    hostSite,
    email
    )

  let body = await json(ctx.req)

  body = {
    ...body,
    revendaId: organizationId[0].companyId,
    }

  const {
    headers,
    data,
    status: responseStatus,
  } = await statusClient.postOrdersPeriod(
    body,
    settings.endpoint,
    settings.token
  )

  ctx.status = responseStatus
  ctx.body = data
  ctx.set('Cache-Control', headers['cache-control'])
  await next()
}

```


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

[User] Show me the implementation of omnichannel-order-status/node/middlewares/oderValidation.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

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

export async function orderValidationMiddleware(
  ctx: Context,
  next: () => Promise<any>
) {
  const {
    vtex: {
      route: { params },
    },
  } = ctx

  const { order } = params

  if (!order) {
    throw new UserInputError('Validation Error')
  }

  ctx.state.order = order.toString()

  await next()
}

```


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

[User] Show me the implementation of omnichannel-order-status/react/typings/storefront.d.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { FunctionComponent } from 'react'

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

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

```


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

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

[Assistant]
Here's the implementation:

```typescript
/* Typings for `render-runtime` */
declare module 'vtex.render-runtime' {
  import { Component, ComponentType, ReactElement, ReactType } from 'react'

  export interface NavigationOptions {
    page: string
    params?: any
  }

  export interface RenderContextProps {
    runtime: {
      navigate: (options: NavigationOptions) => void
    }
  }

  interface ExtensionPointProps {
    id: string
    [key: string]: any
  }

  export const ExtensionPoint: ComponentType<ExtensionPointProps>

  interface ChildBlockProps {
    id: string
  }

  export const ChildBlock: ComponentType<ChildBlockProps>
  export const useChildBlock = function({ id: string }): object {}

  export const Helmet: ReactElement
  export const Link: ReactType
  export const NoSSR: ReactElement
  export const RenderContextConsumer: ReactElement
  export const canUseDOM: boolean
  export const withRuntimeContext: <TOriginalProps extends {}>(
    Component: ComponentType<TOriginalProps & RenderContextProps>
  ) => ComponentType<TOriginalProps>
}

```


[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 omnichannel-order-status/react/typings/global.d.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```typescript
export interface TimeSplit {
    hours: string,
    minutes: string,
    seconds: 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 omnichannel-order-status/react/typings/css.d.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.css' {
  const css: any
  export default css
}

```


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

[User] Show me the implementation of omnichannel-order-status/react/typings/graphql.d.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

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

  const value: DocumentNode
  export default value
}

```


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

[User] Show me the implementation of omnichannel-order-status/react/typings/vtex.styleguide.d.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.styleguide' {
  import { ComponentType } from 'react'

  export const Input: ComponentType<InputProps>

  interface InputProps {
    [key: string]: any
  }

  export const DatePicker: ComponentType<any>
  export const Spinner: ComponentType<any>
  export const Alert: ComponentType<any>
  export const Button: ComponentType<any>
  export const Table: ComponentType<any>
  export const EXPERIMENTAL_Table: ComponentType<any>
  export const Link: ComponentType<any>
  export const ArrowDown: ComponentType<any>
  export const ArrowUp: ComponentType<any>
}

declare module '@vtex/styleguide/lib/*' {
  const Component: ComponentType<any>
  export default Component
}
```


[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 omnichannel-order-status/react/utils/order.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const orderStatus = (s: any) => {
  switch (s) {
    case -1:
      s = 'Cancelado'
      break
    case 0:
      s = 'Recebido'
      break
    case 1:
      s = 'Liberação Comercial'
      break
    case 2:
      s = 'Liberação Financeira'
      break
    case 3:
      s = 'Em Separação'
      break
    case 4:
      s = 'Despachado'
      break
    case 5:
      s = 'Entregue'
      break
    default:
      s = '----'
  }
  return s
}
```


[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 omnichannel-order-status/react/utils/time.ts from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { TimeSplit } from "../typings/global"

const SECONDS_IN_MINUTE = 60
const SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE

export const parseTimeRemaining = (totalSeconds: number) : TimeSplit => {
    const hours = Math.floor(totalSeconds / SECONDS_IN_HOUR)
    const minutes = Math.floor(((totalSeconds % SECONDS_IN_HOUR) / SECONDS_IN_MINUTE))
    const seconds = Math.floor(((totalSeconds % SECONDS_IN_HOUR) % SECONDS_IN_MINUTE))
    return {
        hours: fillWithZero(2, hours),
        minutes: fillWithZero(2, minutes),
        seconds: fillWithZero(2, seconds)
    }
}

const fillWithZero = (digits: number, number: number) : string => {
   const filled = '0'.repeat(digits - 1) + number
   return filled.slice(filled.length - digits)
}

/**
 *
 * @param targetDate ISOString for the date that the countdown will expire
 * @param dispatchFn A function that updates the state of the component
 */
export const tick = (targetDate: string, dispatchFn: React.Dispatch<React.SetStateAction<TimeSplit>>) => {
  const ONE_SECOND_IN_MILLIS = 1000
  let finalDate = new Date(targetDate)
  let now = new Date()

  let secondsLeft = (finalDate.getTime() - now.getTime())/ONE_SECOND_IN_MILLIS

  setTimeout(()=> {
    dispatchFn(parseTimeRemaining(secondsLeft))
  }, ONE_SECOND_IN_MILLIS)
}

```


[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 omnichannel-order-status/react/components/CurrencyContext.tsx from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { createContext, useContext } from 'react'

export const CurrencyContext = createContext<string>('BRL')

export function useCurrency() {
   return useContext(CurrencyContext)
}
```


[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 omnichannel-order-status/react/components/FormattedPrice.tsx from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

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

import { useCurrency } from './CurrencyContext'

interface Props {
   value: number
}

const FormattedPrice: FC<Props> = ({ value }) => {
   const currency = useCurrency()

   return (
      <FormattedNumber currency={currency} style="currency" value={value / 100} />
   )
}

export default FormattedPrice
```


[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 omnichannel-order-status/react/graphql/productReleaseDate.graphql from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```graphql
query productReleaseDate($slug: String){
  product(slug: $slug) {
    releaseDate
  }
}

```


[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 omnichannel-order-status/react/components/OrderDetails/index.tsx from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useState, useEffect, FunctionComponent } from 'react'
import { ContentWrapper } from 'vtex.my-account-commons'
import ApiB2B from '../Services/ApiB2b'
import OrderTracking from './orderTracking'

import { FormattedMessage } from 'react-intl'
import { FormattedCurrency } from 'vtex.format-currency'
import { format } from 'date-fns'
import { Link, Alert, Spinner, EXPERIMENTAL_Table } from 'vtex.styleguide'
 import  useTableMeasures  from '@vtex/styleguide/lib/EXPERIMENTAL_Table/hooks/useTableMeasures'
import './style.global.css'

import {
  tableSchemaProducts,
tableSchemaBillingAddress,
tableSchemaDeliveryAddress,
tableSchemaOtherInformations
} from "./tableStructure"

const OrderDatails: FunctionComponent<Props> = ({ match }) => {
  const [dataOrder, setDataOrder] = useState<any | undefined>([])
  const [dataFiles, setDataFile] = useState<any | undefined>([])

  const [isLoading, setisLoading] = useState<boolean | false>(false)
  const [isErrorDataOrder, setIsErrorDataOrder] = useState<boolean | false>(false)
  const [isErrorDataFile, setIsErrorDataFile] = useState<boolean | false>(false)

  const idOrder = match.params.order.toString()

  const itensOthersInformations = [
    {
    paymentMethod: dataOrder.paymentMethod,
    paymentOptions: dataOrder.paymentOptions,
    deliveryMethod: dataOrder.deliveryMethod,
    linkTransportadora: dataOrder.linkTransportadora
    }
  ]

  const itensDeliveryAddress = [
    {
      deliveryAddressCorpname: dataOrder.deliveryAddressCorpname,
      billingAddressCity: dataOrder.billingAddressCity,
      billingAddressState: dataOrder.billingAddressState,
      billingAddresszipcode: dataOrder.billingAddresszipcode
    }
  ]

  const itensBillingAddress = [
    {
      deliveryAddressCorpname: dataOrder.deliveryAddressCorpname,
      billingAddressFormattedAddres: dataOrder.billingAddressFormattedAddres,
      billingAddressCity: dataOrder.billingAddressCity,
      billingAddressState: dataOrder.billingAddressState,
      billingAddresszipcode: dataOrder.billingAddresszipcode
    }
  ]

  const measuresProducts = useTableMeasures({ size: dataOrder.itens?.length })
  const measuresOthersInformations = useTableMeasures({ size: itensOthersInformations?.length })
  const measuresDeliveryAddress = useTableMeasures({ size: itensDeliveryAddress?.length })
  const measureBillingAddress = useTableMeasures({ size: itensBillingAddress?.length })

  async function detailOrders() {
    setisLoading(true)
    try {
      const results = await ApiB2B.get('ordersb2b/' + idOrder)
      setDataOrder(results.data)
    } catch (err) {
      setIsErrorDataOrder(true)
      console.warn('Pedido', err)
    } finally {
      setisLoading(false)
    }
  }

  async function getFiles() {
    try {
      const result = await ApiB2B.get('ordersb2b/files/' + idOrder)
      setDataFile(result.data)
    } catch (err) {
      setIsErrorDataFile(true)
      console.warn('Arquivos do pedido', err)
    }
  }

  useEffect(() => {
    getFiles(), detailOrders()
  }, [])

   return (
    <ContentWrapper
      titleId="titleOrderDetails"
      namespace="custom-page"
      backButton={{
        title: "return",
        titleId: "titleOrderDetails",
        path: "/b2b-order"
      }
    }>
      {() => (
        <div>
          {isErrorDataOrder && (
            <Alert type="error" onClose={() => console.log('Closed!')}>
              <FormattedMessage id="message.error" />
            </Alert>
          )}
          <div className="vtex_orders-detail c-on-base">
            <table className="f6 w-100 mw8">
              <tbody className="lh-copy">
                <tr>
                  <td className="fw6 pv3 pr3 bb tl b--black-20 c-on-base">
                    {<FormattedMessage id="label.numberOrderWeb" />}
                  </td>
                  <td className="pv3 pr3 bb tr b--black-20">
                    {dataOrder.pedidoErpId}
                  </td>
                </tr>
                <tr>
                  <td className="fw6 pv3 pr3 bb tl b--black-20 c-on-base">
                    {<FormattedMessage id="table.orderDate" />}
                  </td>
                  <td className="pv3 pr3 bb tr b--black-20">
                    {dataOrder.dataPedido
                      ? format(new Date(dataOrder.dataPedido), 'dd/MM/yyyy')
                      : dataOrder.dataPedido}
                  </td>
                </tr>
                <tr>
                  <td className="fw6 pv3 pr3 bb tl b--black-20 c-on-base">
                    {<FormattedMessage id="table.name" />}
                  </td>
                  <td className="pv3 pr3 bb tr b--black-20">
                    {dataOrder.clienteFinalNome}
                  </td>
                </tr>
                <tr>
                  <td className="fw6  pr3 bb tl b--black-20 c-on-base">
                    CPF/CNPJ
                  </td>
                  <td className="pv3 pr3 bb tr b--black-20">
                    {dataOrder.clienteFinalCpf}
                    {dataOrder.clienteFinalCnpj}
                  </td>
                </tr>
              </tbody>
            </table>

            <div className="t-heading-4 mt6 mb5">
              {<FormattedMessage id="order.tracking" />}
            </div>

            <div>
              <OrderTracking status={dataOrder.status} />
            </div>

            {isErrorDataOrder ? (
              <div className="flex items-center h-100 c-muted-2 pa7-l">
                <div className="w-80 w-60-l center tc">
                  <span className="t-heading-4 mt0">Nothing to show.</span>
                </div>
              </div>
            ) : (
              <div>
                <div className="w-100 pa2">
                  <p>
                    <strong className="c-on-base">
                      {<FormattedMessage id="order.billingAddress" />}
                    </strong>
                  </p>
                  {isLoading ? (
                    <div className="tc">
                      <Spinner />
                    </div>
                  ) : (
                    <EXPERIMENTAL_Table
                      measures={measureBillingAddress}
                      columns={tableSchemaBillingAddress}
                      items={itensBillingAddress}
                    />
                  )}
                </div>

                <div className="w-100 pa2">
                  <p>
                    <strong className="c-on-base">
                      {<FormattedMessage id="order.deliveryAddress" />}
                    </strong>
                  </p>
                  {isLoading ? (
                    <div className="tc">
                      <Spinner />
                    </div>
                  ) : (
                    <EXPERIMENTAL_Table
                      measures={measuresDeliveryAddress}
                      columns={tableSchemaDeliveryAddress}
                      items={itensDeliveryAddress}
                    />
                  )}
                </div>

                <div className="w-100 pa2">
                  <p>
                    <strong className="c-on-base">
                      {<FormattedMessage id="order.otherInformations" />}
                    </strong>
                  </p>
                  {isLoading ? (
                    <div className="tc">
                      <Spinner />
                    </div>
                  ) : (
                    <EXPERIMENTAL_Table
                      measures={measuresOthersInformations}
                      columns={tableSchemaOtherInformations}
                      items={itensOthersInformations}
                    />
                  )}
                </div>
              </div>
            )}

            <div className="t-heading-4 mt6 mb5">
              {<FormattedMessage id="order.purchaseData" />}
            </div>

            <div className="overflow-auto mt7 mb7">
            {isLoading ? (
              <div className="tc">
                <Spinner />
              </div>
            ) : (
              <EXPERIMENTAL_Table
                measures={measuresProducts}
                columns={tableSchemaProducts}
                items={dataOrder.itens}
              />
            )}
            </div>

            {!isErrorDataOrder && (
            <div className="order_-summary tr">
              <div className="w-100 mw6 dib">
                <table className="f6 w-100 ba b--black-10">
                  <tbody className="lh-copy">
                    <tr>
                      <td className="fw5 pv3 pr3 bb tl b--black-10">
                        Sub-total:
                      </td>
                      <td className="pv3 pr3 bb tr b--black-10">
                        <FormattedCurrency
                          value={
                            dataOrder.valorTotalPedido -
                            dataOrder.valorFrete
                          }
                        />
                      </td>
                    </tr>
                    <tr>
                      <td className="fw5 pv3 pr3 bb tl b--black-10">
                        {<FormattedMessage id="table.freight" />}:
                      </td>
                      <td className="pv3 pr3 bb tr b--black-10">
                        <FormattedCurrency value={dataOrder.valorFrete} />
                      </td>
                    </tr>
                    <tr>
                      <td className="fw5 pv3 pr3 bb tl b--black-10">
                        {<FormattedMessage id="table.orderTotal" />}:
                      </td>
                      <td className="pv3 pr3 bb tr b--black-10">
                        <FormattedCurrency
                          value={dataOrder.valorTotalPedido}
                        />
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            )}

            <div className="t-heading-4 mt6 mb5">
              {<FormattedMessage id="title.serviceTax" />}
            </div>

            {isErrorDataFile ? (
              <div className="flex items-center h-100 c-muted-2 pa7-l">
                <div className="w-80 w-60-l center tc">
                  <span className="t-heading-4 mt0">Nothing to show.</span>
                </div>
              </div>
            ) : (
            <ul className="pa0 ma0">
              {dataFiles.itens?.map((item: any, index: number) => (
                <li key={index} className="pa3 dib">
                  <Link href={item.url} target="_blank">
                    {item.descricao}
                  </Link>
                </li>
              ))}
            </ul>
            )}
          </div>
        </div>
      )}
    </ContentWrapper>
  )
}

type Props = {
  match: {
    params: {
      param: string
      order: string
    }
  }
}

export default OrderDatails

```


[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 omnichannel-order-status/react/components/OrderDetails/tableStructure.tsx from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from "react"
import { FormattedMessage } from 'react-intl'
import { FormattedCurrency } from 'vtex.format-currency'

export const tableSchemaProducts = [
  {
    id: 'descricaoDoProduto',
    title: <FormattedMessage id='table.name' />
  },
  {
    id: 'valorUnitario',
    title: <FormattedMessage id='table.price' />,
    cellRenderer: ({ data }: any) => {
      return <FormattedCurrency value={data} />
    }
  },
  {
    id: 'quantidade',
    title: <FormattedMessage id='table.quantity' />
  },
  {
    id: 'valorTotal',
    title: 'Total',
    cellRenderer: ({ data }: any) => {
      return <FormattedCurrency value={data} />
    },
  }
]

export const tableSchemaBillingAddress = [
  {
    id: 'deliveryAddressCorpname',
    title: <FormattedMessage id='order.deliveryAddress' />
  },
  {
    id: 'billingAddressFormattedAddres',
    title: <FormattedMessage id='table.address' />
  },
  {
    id: 'billingAddressCity',
    title: <FormattedMessage id='table.city' />
  },
  {
    id: 'billingAddressState',
    title: <FormattedMessage id='table.state' />
  },
  {
    id: 'billingAddresszipcode',
    title: <FormattedMessage id='table.zipCode' />
  }
]

export const tableSchemaDeliveryAddress = [
  {
    id: 'deliveryAddressCorpname',
    title: <FormattedMessage id='order.deliveryAddress' />
  },
  {
    id: 'billingAddressCity',
    title: <FormattedMessage id='table.city' />
  },
  {
    id: 'billingAddressState',
    title: <FormattedMessage id='table.state' />
  },
  {
    id: 'billingAddresszipcode',
    title: <FormattedMessage id='table.zipCode' />
  },
]

export const tableSchemaOtherInformations = [
  {
    id: 'paymentMethod',
    title: <FormattedMessage id='table.methodPayment' />
  },
  {
    id: 'paymentOptions',
    title: <FormattedMessage id='table.optionPayment' />
  },
  {
    id: 'deliveryMethod',
    title: <FormattedMessage id='table.deliveryMethod' />
  },
  {
    id: 'linkTransportadora',
    title: <FormattedMessage id='table.carrierLink' />
  },
]

```


[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 omnichannel-order-status/react/components/OrderDetails/orderTracking.tsx from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FunctionComponent } from 'react'
import { FormattedMessage } from 'react-intl'

interface TrackingProps {
   status: number
}

const OrderTracking: FunctionComponent<TrackingProps> = ({status}) => {
	function orderStatusDot(meuNum: Number, status: Number){
		if(meuNum <= status){
				return "milestone--reached"
		}
		return ""
	}

	function orderStatusBar(status: number){
		if(status > 4){
			return "100%"
		}

		return `${(Number(17) * status)}%`
	}

	return (
		<div className="progress-bar" role="progressbar">
			<span className="progress" style={{"width": `${orderStatusBar(status)}`}}></span>
			<div className="isMobile">
				<div className={`milestone ${orderStatusDot(1, status)}`}>
					<label className="c-on-base">{<FormattedMessage id="order.commercialRelease" />}</label>
				</div>
			</div>
			<div className="isMobile">
				<div className={`milestone ${orderStatusDot(2, status)}`}>
					<label className="c-on-base"><FormattedMessage id="order.financeRelease" /></label>
				</div>
			</div>
			<div className="isMobile">
				<div className={`milestone ${orderStatusDot(3, status)}`}>
					<label className="c-on-base"><FormattedMessage id="order.separation" /></label>
				</div>
			</div>
			<div className="isMobile">
				<div className={`milestone ${orderStatusDot(4, status)}`}>
					<label className="c-on-base"><FormattedMessage id="order.dispatch" /></label>
				</div>
			</div>
			<div className="isMobile">
				<div className={`milestone ${orderStatusDot(5, status)}`}>
					<label className="c-on-base"><FormattedMessage id="order.delivery" /></label>
				</div>
			</div>
		</div>
	)
}

export default OrderTracking
```


[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 omnichannel-order-status/react/components/OrderDetails/style.global.css from the omnichannel-order-status VTEX app.

[Assistant]
Here's the implementation:

```css
.progress-bar {
  margin: 40px 0 60px 0;
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  max-width: 800px;
  height: 10px;
  background-color: #cdd0d0;
  border-radius: 99em;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  position: relative;
}

.progress {
  background-color: #006a71;
  top: 0;
  left: 0;
  bottom: 0;
  position: absolute;
  border-radius: 99em;
}

.milestone {
  position: relative;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #cdd0d0;
  color: #fff;
}
.milestone--reached {
  background-color: #006a71;
}
.milestone label{
  position: absolute;
  top: 35px;
  width: 130px;
  text-align: center;
}

@media (max-width: 768px){
  .progress-bar{
    max-width: initial;
    height: initial;
    background-color: initial;
    flex-direction: column;
    margin: 40px 0 20px 0;
  }

  .progress{
    display: none;
  }

  .milestone label {
    top: 27px;
  }

  .isMobile{
    height: 75px;
  }
}

```