[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 return-app/react/common/components/ReturnDetails/ItemDetails/ItemDetailsList.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { Table } from 'vtex.styleguide'
import type {
  ReturnRequestItem,
  RefundData,
  Status,
  Maybe,
} from 'vtex.return-app'
import { useCssHandles } from 'vtex.css-handles'
import { useRuntime } from 'vtex.render-runtime'
import { useIntl } from 'react-intl'

import { useReturnDetails } from '../../../hooks/useReturnDetails'
import { itemDetailsSchema } from './itemDetailsSchema'
import { ItemDetailsCard } from './ItemDetailsCard'

type ItemStatus = 'new' | 'denied' | 'approved' | 'partiallyApproved'

const CSS_HANDLES = [
  'itemDetailsListContainer',
  'itemDetailsListWrapper',
] as const

export interface ItemStatusInterface {
  status: ItemStatus
  quantity: number
  quantityRefunded: number
}

const calculateStatus = (
  status: Status,
  returnQuantity: number,
  refundedQuantity: number
): ItemStatus => {
  switch (status) {
    case 'denied': {
      return 'denied'
    }

    case 'packageVerified': {
      return refundedQuantity === 0
        ? 'denied'
        : returnQuantity > refundedQuantity
        ? 'partiallyApproved'
        : 'approved'
    }

    case 'amountRefunded': {
      return refundedQuantity === 0
        ? 'denied'
        : returnQuantity > refundedQuantity
        ? 'partiallyApproved'
        : 'approved'
    }

    default: {
      return 'new'
    }
  }
}

const getItemVerificationStatus = (
  items: ReturnRequestItem[],
  refundData: Maybe<RefundData | undefined>,
  status: Status
) => {
  const refundItemsMap = new Map<number, number>()

  for (const item of refundData?.items ?? []) {
    refundItemsMap.set(item.orderItemIndex, item.quantity)
  }

  const itemVerificationStatusMap = new Map<number, ItemStatusInterface>()

  for (const item of items) {
    const { quantity } = item
    const quantityRefunded = refundItemsMap.get(item.orderItemIndex) ?? 0

    itemVerificationStatusMap.set(item.orderItemIndex, {
      status: calculateStatus(status, quantity, quantityRefunded),
      quantity,
      quantityRefunded,
    })
  }

  return itemVerificationStatusMap
}

export const ItemDetailsList = () => {
  const handles = useCssHandles(CSS_HANDLES)

  const { formatMessage } = useIntl()
  const { data } = useReturnDetails()
  const {
    hints: { phone },
  } = useRuntime()

  if (!data) return null

  const { items, status, refundData, cultureInfoData } =
    data.returnRequestDetails

  const itemsVerificationStatus = getItemVerificationStatus(
    items,
    refundData,
    status
  )

  const { currencyCode } = cultureInfoData

  if (phone) {
    return (
      <section
        className={`${handles.itemDetailsListWrapper} mv4 flex flex-column`}
      >
        {items?.map((item) => {
          return (
            <ItemDetailsCard
              currencyCode={currencyCode}
              key={item.orderItemIndex}
              item={item}
              itemsVerificationStatus={itemsVerificationStatus}
            />
          )
        })}
      </section>
    )
  }

  return (
    <section className={handles.itemDetailsListContainer}>
      <Table
        fullWidth
        dynamicRowHeight
        items={items}
        schema={itemDetailsSchema({
          itemsVerificationStatus,
          currencyCode,
          formatMessage,
          isSmallScreen: phone,
        })}
      />
    </section>
  )
}

```


[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 return-app/react/common/components/ReturnDetails/ItemDetails/ItemVerificationStatus.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import {
  IconFailure,
  IconSuccess,
  IconWarning,
  IconClock,
} from 'vtex.styleguide'
import { FormattedMessage } from 'react-intl'
import { useCssHandles } from 'vtex.css-handles'

import type { ItemStatusInterface } from './ItemDetailsList'

const CSS_HANDLES = [
  'itemVerificationDeniedContainer',
  'itemVerificationApprovedContainer',
  'itemVerificationPartiallyContainer',
  'itemVerificationNewContainer',
] as const

export const ItemVerificationStatus = (props: ItemStatusInterface) => {
  const { status, quantity, quantityRefunded } = props
  const handles = useCssHandles(CSS_HANDLES)

  switch (status) {
    case 'denied': {
      return (
        <div
          className={`${handles.itemVerificationDeniedContainer} c-danger flex items-center`}
        >
          <span className="mr2 flex">
            <IconFailure size={14} />
          </span>
          <FormattedMessage id="store/return-app.return-request-details.table.verification-status.denied" />
        </div>
      )
    }

    case 'approved': {
      return (
        <div
          className={`${handles.itemVerificationApprovedContainer} c-success flex items-center`}
        >
          <span className="mr2 flex">
            <IconSuccess size={14} />
          </span>
          <FormattedMessage id="store/return-app.return-request-details.table.verification-status.approved" />
        </div>
      )
    }

    case 'partiallyApproved': {
      return (
        <div
          className={`${handles.itemVerificationPartiallyContainer} c-warning flex items-center`}
        >
          <span className="mr2 flex">
            <IconWarning size={14} />
          </span>
          <FormattedMessage
            id="store/return-app.return-request-details.table.verification-status.partially-approved"
            values={{ quantityRefunded, quantity }}
          />
        </div>
      )
    }

    default: {
      return (
        <div
          className={`${handles.itemVerificationNewContainer} c-warning flex items-center`}
        >
          <span className="mr2 flex">
            <IconClock size={14} />
          </span>
          <FormattedMessage id="store/return-app.return-request-details.table.verification-status.new" />
        </div>
      )
    }
  }
}

```


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

[User] Show me the implementation of return-app/react/common/components/ReturnDetails/ReturnValues/ApprovedValues.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { useCssHandles } from 'vtex.css-handles'

import { useReturnDetails } from '../../../hooks/useReturnDetails'
import { TotalWrapper } from './TotalWrapper'
import { TotalContainer } from './TotalContainer'

const CSS_HANDLES = ['approvedValuesContainer'] as const

export const ApprovedValues = () => {
  const handles = useCssHandles(CSS_HANDLES)
  const { data } = useReturnDetails()
  const { refundData, status } = data?.returnRequestDetails ?? {}

  if (!data || !refundData) return null

  const { items, invoiceValue, refundedShippingValue } = refundData

  const amountItemRefund = items.reduce((total, item) => {
    return total + item.price * item.quantity
  }, 0)

  const totalRestockFee = items.reduce((total, item) => {
    return total + item.restockFee
  }, 0)

  return (
    <div className={`${handles.approvedValuesContainer} mb5`}>
      {status === 'amountRefunded' ? (
        <h3>
          <FormattedMessage id="store/return-app.return-request-details.refund-total.header-refunded" />
        </h3>
      ) : null}
      {status === 'packageVerified' ? (
        <h3>
          <FormattedMessage id="store/return-app.return-request-details.refund-total.header-approved" />
        </h3>
      ) : null}
      <TotalContainer>
        <TotalWrapper
          title={
            <FormattedMessage id="store/return-app.return-request-details.refund-total.item-tax" />
          }
          value={amountItemRefund}
        />
        <TotalWrapper
          title={
            <FormattedMessage id="store/return-app.return-request-details.refund-total.restock-fee" />
          }
          value={totalRestockFee === 0 ? 0 : totalRestockFee * -1}
        />
        <TotalWrapper
          title={
            <FormattedMessage id="store/return-app.return-request-details.refund-total.shipping" />
          }
          value={refundedShippingValue}
        />
        <TotalWrapper
          title={
            <FormattedMessage id="store/return-app.return-request-details.refund-total.total" />
          }
          value={invoiceValue}
        />
      </TotalContainer>
    </div>
  )
}

```


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

[User] Show me the implementation of return-app/react/common/components/ReturnDetails/ReturnValues/TotalContainer.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FC } from 'react'
import React from 'react'
import { useCssHandles } from 'vtex.css-handles'

const CSS_HANDLES = ['totalContainer'] as const

export const TotalContainer: FC = ({ children }) => {
  const handles = useCssHandles(CSS_HANDLES)

  return (
    <div
      className={`${handles.totalContainer} w-100 flex flex-row-ns ba br3 b--muted-4 flex-column`}
    >
      {children}
    </div>
  )
}

```


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

[User] Show me the implementation of return-app/react/common/components/ReturnDetails/ReturnValues/RequestedValues.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { useCssHandles } from 'vtex.css-handles'

import { useReturnDetails } from '../../../hooks/useReturnDetails'
import { TotalWrapper } from './TotalWrapper'
import { TotalContainer } from './TotalContainer'

const CSS_HANDLES = ['requestedValuesContainer'] as const

export const RequestedValues = () => {
  const handles = useCssHandles(CSS_HANDLES)

  const { data } = useReturnDetails()

  if (!data) return null

  const { refundableAmountTotals, refundableAmount } = data.returnRequestDetails

  const totalRefundableItems =
    refundableAmountTotals.find(({ id }) => id === 'items')?.value ?? 0

  const totalRefundableTaxes =
    refundableAmountTotals.find(({ id }) => id === 'tax')?.value ?? 0

  const totalRefundableShipping =
    refundableAmountTotals.find(({ id }) => id === 'shipping')?.value ?? 0

  return (
    <div className={`${handles.requestedValuesContainer} mb5`}>
      <h3>
        <FormattedMessage id="store/return-app.return-request-details.request-total.header" />
      </h3>
      <TotalContainer>
        <TotalWrapper
          title={
            <FormattedMessage id="store/return-app.return-request-details.request-total.item-tax" />
          }
          value={totalRefundableItems + totalRefundableTaxes}
        />
        <TotalWrapper
          title={
            <FormattedMessage id="store/return-app.return-request-details.request-total.shipping" />
          }
          value={totalRefundableShipping}
        />
        <TotalWrapper
          title={
            <FormattedMessage id="store/return-app.return-request-details.request-total.total" />
          }
          value={refundableAmount}
        />
      </TotalContainer>
    </div>
  )
}

```


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

[User] Show me the implementation of return-app/react/common/components/ReturnDetails/ReturnValues/ReturnValues.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { useCssHandles } from 'vtex.css-handles'

import { useReturnDetails } from '../../../hooks/useReturnDetails'
import { ApprovedValues } from './ApprovedValues'
import { RequestedValues } from './RequestedValues'

const CSS_HANDLES = ['returnValuesContainer'] as const

export const ReturnValues = () => {
  const handles = useCssHandles(CSS_HANDLES)

  const { data } = useReturnDetails()

  if (!data) return null

  return (
    <section className={`${handles.returnValuesContainer} mv4`}>
      <RequestedValues />
      <ApprovedValues />
    </section>
  )
}

```


[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 return-app/react/common/components/ReturnDetails/ReturnValues/TotalWrapper.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { ReactElement } from 'react'
import React from 'react'
import { FormattedNumber } from 'react-intl'
import { useCssHandles } from 'vtex.css-handles'

import { useReturnDetails } from '../../../hooks/useReturnDetails'

const CSS_HANDLES = ['totalWrapperContainer'] as const

interface Props {
  title: ReactElement
  value: number
}

export const TotalWrapper = (props: Props) => {
  const handles = useCssHandles(CSS_HANDLES)

  const { title, value } = props

  const { data } = useReturnDetails()

  if (!data) return null

  const { cultureInfoData } = data?.returnRequestDetails

  return (
    <div
      className={`${handles.totalWrapperContainer} flex flex-column pa4 b--muted-4 flex-auto bb bb-0-ns br-ns`}
    >
      <div>
        <div className="c-muted-2 f6">{title}</div>
        <div className="w-100 mt2">
          <div className="f4 fw5 c-on-base">
            <FormattedNumber
              value={value / 100}
              style="currency"
              currency={cultureInfoData.currencyCode}
            />
          </div>
        </div>
      </div>
    </div>
  )
}

```


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

[User] Show me the implementation of return-app/react/common/components/returnList/MobileList/index.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable jsx-a11y/img-redundant-alt */
import React, { useMemo, useState } from 'react'
import { useCssHandles } from 'vtex.css-handles'
import { FormattedMessage } from 'react-intl'

import { GridCard } from '../../GridCard'
import SingleGridIcon from './icons/SingleGrid'
import DoubleGridIcon from './icons/DoubleGrid'

import './styles.css'

interface MobileListProps {
  cardTypeByPage?: 'my-returns' | 'request-return'
  items: any
}

const CSS_HANDLES = [
  'mobileReturnListContainer',
  'controlGridVisibility',
  'controlGridVisibilityButtons',
  'returnList',
  'returnListSingle',
  'returnListDouble',
  'emptyList',
] as const

const MobileList = ({
  cardTypeByPage = 'my-returns',
  items = [],
}: MobileListProps) => {
  const [showDoubleGridVisibility, setShowDoubleGridVisibility] = useState(true)

  const handles = useCssHandles(CSS_HANDLES)
  const hasItems = useMemo(() => items?.length > 0, [items])

  return (
    <div className={handles.mobileReturnListContainer}>
      {!hasItems && (
        <span className={handles.emptyList}>
          <FormattedMessage id="store/return-app.return-request-list.table.emptyState" />
        </span>
      )}

      {hasItems && (
        <>
          <div className={handles.controlGridVisibility}>
            <span>
              <FormattedMessage id="store/return-app.return-request-list.table.view" />
            </span>
            <div className={handles.controlGridVisibilityButtons}>
              <button onClick={() => setShowDoubleGridVisibility(false)}>
                <SingleGridIcon filled={!showDoubleGridVisibility} />
              </button>
              <button onClick={() => setShowDoubleGridVisibility(true)}>
                <DoubleGridIcon filled={showDoubleGridVisibility} />
              </button>
            </div>
          </div>

          <div
            className={`${handles.returnList} ${
              showDoubleGridVisibility
                ? handles.returnListDouble
                : handles.returnListSingle
            }`}
          >
            {items?.map((item) => (
              <GridCard
                key={item?.orderId ?? ''}
                cardTypeByPage={cardTypeByPage}
                item={item}
              />
            ))}
          </div>
        </>
      )}
    </div>
  )
}

export default MobileList

```


[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 return-app/react/common/components/returnList/MobileList/styles.css from the return-app VTEX app.

[Assistant]
Here's the implementation:

```css
.mobileReturnListContainer{
  transition: all 400ms ease;
}

.controlGridVisibility{
  display: flex;
  align-items: center;

  gap: 7px;
}

.controlGridVisibility > span {
  font-size: .875rem;
  color: #464646;
  font-weight: 500;
}

.controlGridVisibilityButtons{
  display: flex;
  align-items: center;

  gap: 7px;
}

.controlGridVisibilityButtons button {
  background: none;
  border: none;
}

.returnList {
  display: grid;
  grid-template-rows: 1fr;
  gap: 17px;

  margin: 26px 0 0;
}

.returnListSingle {
  grid-template-columns: 1fr;
  grid-template-areas:
    ".";
}

.returnListDouble {
  grid-template-columns: minmax(139px, 1fr) minmax(139px, 1fr);
  grid-template-areas:
    ". .";
}

.returnListItem{
  display: flex;
  flex-direction: column;
  justify-content: center;

  padding: 12px 0px;
  gap: 12px;

  border-radius: 6px;

  background: #fff;
  box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1);
}

.returnListItemHeader{
  display: flex;
  align-items: center;

  gap: 6px;

  padding-left: 2px;
}

.returnListItemHeader > span {
  font-size: .75rem;
  color: #464646;
}

.returnListItemHeader > span:first-child {
  font-weight: 500;
}

.returnListItemImage {
  width: 100%;
  height: 100%;
  max-height: 200px;
}

.returnListItemImage img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.returnListItemInfo {
  display: flex;
  flex-direction: column;

  gap: 12px;
  padding-left: 10px;
}

.returnListItemInfoDate {
  font-size: .75rem;
  color: #464646;
  font-weight: 400;
}

.returnListItemInfoIdContainer {
  display: flex;
  align-items: center;

  gap: 10px;
}

.returnListItemInfoIdContainer > span {
  font-size: .875rem;
  color: #464646;
  font-weight: 400;
}

.returnListItemInfoIdContainer > span:first-child {
  font-weight: 500;
}

.returnListItemInfoStatus {
  display: flex;
  align-items: center;

  gap: 10px;
}

.emptyList {
  font-size: 1rem;
  font-weight: 500;

}
```


[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 return-app/react/common/components/returnList/MobileList/icons/DoubleGrid.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'

interface DoubleGridIconProps {
  filled?: boolean
}

const DoubleGridIcon = ({ filled = false }: DoubleGridIconProps) => {
  return (
    <svg
      width="16"
      height="20"
      viewBox="0 0 16 20"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <rect
        x="0.5"
        y="0.5"
        width="6"
        height="19"
        fill={filled ? '#FF3333' : 'none'}
        stroke="#FF3333"
      />
      <rect
        x="9.5"
        y="0.5"
        width="6"
        height="19"
        fill={filled ? '#FF3333' : 'none'}
        stroke="#FF3333"
      />
    </svg>
  )
}

export default DoubleGridIcon

```


[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 return-app/react/common/components/returnList/MobileList/icons/SingleGrid.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'

interface SingleGridIconProps {
  filled?: boolean
}

const SingleGridIcon = ({ filled = false }: SingleGridIconProps) => {
  return (
    <svg
      width="16"
      height="20"
      viewBox="0 0 16 20"
      fill={filled ? '#FF3333' : 'none'}
      xmlns="http://www.w3.org/2000/svg"
    >
      <rect
        x="0.5"
        y="0.5"
        width="15"
        height="19"
        fill={filled ? '#FF3333' : 'none'}
        stroke="#FF3333"
        strokeOpacity="0.4"
      />
    </svg>
  )
}

export default SingleGridIcon

```


[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 return-app/react/store/createReturnRequest/OrderListContainer.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useState, useEffect } from 'react'
import { useQuery } from 'react-apollo'
import type {
  Maybe,
  OrdersToReturnList,
  OrderToReturnSummary,
  QueryOrdersAvailableToReturnArgs,
} from 'vtex.return-app'
import { ContentWrapper, BaseLoading } from 'vtex.my-account-commons'
import { FormattedMessage } from 'react-intl'

import ORDERS_AVAILABLE_TO_RETURN from './graphql/getOrdersAvailableToReturn.gql'
import { OrderList } from './components/OrderList'
import { OrderListStructureLoader } from './components/loaders/OrderListStructureLoader'

const headerConfig = {
  namespace: 'vtex-account__return-order-list',
  title: <FormattedMessage id="store/return-app.request-return.page.header" />,
  titleId: 'store/return-app.request-return.page.header',
  backButton: {
    titleId: 'store/return-app.link',
    path: '/my-returns',
  },
}

export const OrderListContainer = () => {
  const [ordersToReturn, setOrdersToReturn] = useState<OrdersToReturnList[]>([])
  const [currentPage, setCurrentPage] = useState<number>(1)
  const [mobileOrdersToReturnList, setMobileOrdersToReturnList] = useState<
    Array<Maybe<OrderToReturnSummary>>
  >([])

  const { data, loading, error, fetchMore, refetch } = useQuery<
    { ordersAvailableToReturn: OrdersToReturnList },
    QueryOrdersAvailableToReturnArgs
  >(ORDERS_AVAILABLE_TO_RETURN, {
    variables: {
      page: 1,
    },
    fetchPolicy: 'no-cache',
  })

  const handlePagination = async (
    page: number,
    operation: 'next' | 'previous'
  ): Promise<void> => {
    const alreadyFetched = ordersToReturn.find((ordersItem) => {
      return ordersItem.paging?.currentPage === page
    })

    if (!alreadyFetched) {
      await fetchMore({
        variables: {
          page,
        },
        updateQuery: (prevResult, { fetchMoreResult }) => {
          if (!fetchMoreResult) return prevResult

          setOrdersToReturn((prevState) => [
            ...prevState,
            fetchMoreResult.ordersAvailableToReturn,
          ])

          setCurrentPage(
            Number(fetchMoreResult.ordersAvailableToReturn.paging?.currentPage)
          )

          return prevResult
        },
      })

      return
    }

    operation === 'next' && setCurrentPage(page)
    operation === 'previous' && setCurrentPage(page)
  }

  const verifyIfItemAlreadyExists = (
    array: Array<Maybe<OrderToReturnSummary>>,
    item: OrderToReturnSummary | null | undefined
  ) => {
    if (!item) return false

    return (
      array.findIndex((arrayItem) => arrayItem?.orderId === item?.orderId) !==
      -1
    )
  }

  useEffect(() => {
    if (data) {
      setOrdersToReturn([data.ordersAvailableToReturn])
      setMobileOrdersToReturnList((current) => {
        const newList = data?.ordersAvailableToReturn?.list ?? []
        const alreadyExist = verifyIfItemAlreadyExists(current, newList?.[0])

        if (alreadyExist) return [...current]

        return [...current, ...(data?.ordersAvailableToReturn?.list ?? [])]
      })
    }
  }, [data])

  return (
    <>
      {loading || error || !ordersToReturn.length ? (
        <BaseLoading
          queryData={{ loading, error, refetch }}
          headerConfig={headerConfig}
        >
          <OrderListStructureLoader />
        </BaseLoading>
      ) : (
        <ContentWrapper {...headerConfig}>
          {() => (
            <OrderList
              orders={ordersToReturn[currentPage - 1]}
              mobileList={mobileOrdersToReturnList}
              handlePagination={handlePagination}
              refetch={refetch}
            />
          )}
        </ContentWrapper>
      )}
    </>
  )
}

```


[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 return-app/react/store/createReturnRequest/CreateReturnRequest.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useEffect, useState } from 'react'
import type { RouteComponentProps } from 'react-router'
import { useQuery } from 'react-apollo'
import type {
  OrderToReturnSummary,
  QueryOrderToReturnSummaryArgs,
} from 'vtex.return-app'
import { PageHeader, PageBlock } from 'vtex.styleguide'
import { FormattedMessage } from 'react-intl'
import { useRuntime } from 'vtex.render-runtime'

import { StoreSettingsPovider } from '../provider/StoreSettingsProvider'
import { OrderToReturnProvider } from '../provider/OrderToReturnProvider'
import { ReturnDetails } from './components/ReturnDetails'
import { ConfirmAndSubmit } from './components/ConfirmAndSubmit'
import { useReturnRequest } from '../hooks/useReturnRequest'
import ORDER_TO_RETURN_SUMMARY from './graphql/getOrderToReturnSummary.gql'
import { formatItemsToReturn } from '../utils/formatItemsToReturn'
import { setInitialPickupAddress } from '../utils/setInitialPickupAddress'
import { useStoreSettings } from '../hooks/useStoreSettings'
import { OrderDetailsLoader } from './components/loaders/OrderDetailsLoader'

export type Page = 'form-details' | 'submit-form'

type RouteProps = RouteComponentProps<{ orderId: string }>

const createPageHeaderProps = (page: Page, navigate: any) => {
  if (page === 'submit-form') {
    return {
      title: (
        <FormattedMessage id="store/return-app.confirm-and-submit.page-header.title" />
      ),
    }
  }

  return {
    title: (
      <FormattedMessage id="store/return-app.return-order-details.page-header.title" />
    ),
    linkLabel: (
      <FormattedMessage id="store/return-app.return-order-details.page-header.link" />
    ),
    onLinkClick: () => {
      navigate({
        to: '#/my-returns/add',
      })
    },
  }
}

export const CreateReturnRequest = (props: RouteProps) => {
  const {
    match: {
      params: { orderId },
    },
  } = props

  const [page, setPage] = useState<Page>('form-details')
  const [items, setItemsToReturn] = useState<ItemToReturn[]>([])

  const {
    actions: { updateReturnRequest },
  } = useReturnRequest()

  const { data: storeSettings } = useStoreSettings()
  const { paymentOptions, options } = storeSettings ?? {}
  const { enablePaymentMethodSelection } = paymentOptions ?? {}
  const { enableHighlightFormMessage } = options ?? {}

  const { navigate } = useRuntime()

  const { data, loading, error } = useQuery<
    { orderToReturnSummary: OrderToReturnSummary },
    QueryOrderToReturnSummaryArgs
  >(ORDER_TO_RETURN_SUMMARY, {
    variables: { orderId },
    skip: !orderId,
    fetchPolicy: 'no-cache',
  })

  useEffect(() => {
    if (!data || !storeSettings) {
      return
    }

    const { orderToReturnSummary } = data
    const { orderId: id } = orderToReturnSummary

    const itemsToReturn = formatItemsToReturn(orderToReturnSummary)

    setItemsToReturn(itemsToReturn)

    const { clientProfileData, shippingData } = orderToReturnSummary

    const initialPickupAddress = setInitialPickupAddress(shippingData)

    updateReturnRequest({
      type: 'newReturnRequestState',
      payload: {
        orderId: id,
        customerProfileData: clientProfileData,
        pickupReturnData: initialPickupAddress,
        items: itemsToReturn.map(({ orderItemIndex }) => ({
          orderItemIndex,
          quantity: 0,
        })),
        refundPaymentData: enablePaymentMethodSelection
          ? undefined
          : {
              refundPaymentMethod: 'sameAsPurchase',
            },
      },
    })
  }, [data, storeSettings, updateReturnRequest, enablePaymentMethodSelection])

  const handlePageChange = (selectedPage: Page) => {
    setPage(selectedPage)
  }

  return (
    <div className="create-return-request__container">
      <PageBlock>
        <PageHeader {...createPageHeaderProps(page, navigate)} />
        <OrderDetailsLoader data={{ loading, error }}>
          {page === 'form-details' && data ? (
            <>
              <ReturnDetails
                {...props}
                onPageChange={handlePageChange}
                items={items}
                creationDate={data.orderToReturnSummary.creationDate}
                canRefundCard={
                  data?.orderToReturnSummary.paymentData.canRefundCard
                }
                shippingData={data.orderToReturnSummary.shippingData}
                showHighlightedMessage={enableHighlightFormMessage ?? false}
              />
            </>
          ) : null}
          {page === 'submit-form' ? (
            <ConfirmAndSubmit onPageChange={handlePageChange} items={items} />
          ) : null}
        </OrderDetailsLoader>
      </PageBlock>
    </div>
  )
}

export const CreateReturnRequestContainer = (props: RouteProps) => {
  return (
    <StoreSettingsPovider>
      <OrderToReturnProvider>
        <CreateReturnRequest {...props} />
      </OrderToReturnProvider>
    </StoreSettingsPovider>
  )
}

```


[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 return-app/react/store/ReturnRequest/StoreReturnDetails.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import type { RouteComponentProps } from 'react-router'
import { PageBlock, PageHeader } from 'vtex.styleguide'
import { useRuntime } from 'vtex.render-runtime'
import { FormattedMessage } from 'react-intl'
import { useCssHandles } from 'vtex.css-handles'

import { StoreReturnDetailsLoader } from './loaders/StoreReturnDetailsLoader'
import { ReturnDetailsProvider } from '../../common/provider/ReturnDetailsProvider'
import { useReturnDetails } from '../../common/hooks/useReturnDetails'
import { ItemDetailsList } from '../../common/components/ReturnDetails/ItemDetails/ItemDetailsList'
import { ReturnValues } from '../../common/components/ReturnDetails/ReturnValues/ReturnValues'
import { ContactDetails } from '../../common/components/ContactDetails'
import { PickupAddress } from '../../common/components/ReturnDetails/PickupAddress'
import { RefundMethodDetail } from '../../common/components/ReturnDetails/RefundMethodDetail'
import { StatusTimeline } from '../../common/components/ReturnDetails/StatusTimeline/StatusTimeline'
import { StatusHistory } from '../../common/components/ReturnDetails/StatusHistory'
import { OrderLink } from '../../common/components/ReturnDetails/OrderLink'
import { CurrentRequestStatus } from '../../common/components/ReturnDetails/CurrentRequestStatus'
import RequestCancellation from '../../common/components/ReturnDetails/RequestCancellation'
import { UpdateRequestStatusProvider } from '../../admin/provider/UpdateRequestStatusProvider'
import { AlertProvider } from '../../admin/provider/AlertProvider'

const CSS_HANDLES = ['contactPickupContainer'] as const

const StoreReturnDetails = () => {
  const { loading, error } = useReturnDetails()
  const { navigate } = useRuntime()
  const handles = useCssHandles(CSS_HANDLES)

  return (
    <div className="return-detail__container">
      <PageBlock>
        <PageHeader
          title={
            <FormattedMessage id="store/return-app.return-request-details.page-header.title" />
          }
          linkLabel={
            <FormattedMessage id="store/return-app.return-request-details.page-header.link-label" />
          }
          onLinkClick={() => {
            navigate({
              to: '#/my-returns',
            })
          }}
        >
          <AlertProvider>
            <UpdateRequestStatusProvider>
              <RequestCancellation />
            </UpdateRequestStatusProvider>
          </AlertProvider>
        </PageHeader>
        <StoreReturnDetailsLoader data={{ loading, error }}>
          <CurrentRequestStatus />
          <OrderLink />
          <ItemDetailsList />
          <ReturnValues />
          <div
            className={`${handles.contactPickupContainer} flex-ns flex-wrap flex-row`}
          >
            <ContactDetails />
            <PickupAddress />
          </div>
          <RefundMethodDetail />
          <StatusTimeline />
          <StatusHistory />
        </StoreReturnDetailsLoader>
      </PageBlock>
    </div>
  )
}

export const StoreReturnDetailsContainer = (
  props: RouteComponentProps<{ id: string }>
) => {
  return (
    <ReturnDetailsProvider requestId={props.match.params.id}>
      <StoreReturnDetails />
    </ReturnDetailsProvider>
  )
}

```


[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 return-app/react/store/ReturnRequest/StoreReturnList.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { Button } from 'vtex.styleguide'
import { ContentWrapper } from 'vtex.my-account-commons'
import { FormattedMessage, defineMessages, useIntl } from 'react-intl'
import { useRuntime } from 'vtex.render-runtime'

import ListTable from '../../common/components/returnList/ListTable'
import { useReturnRequestList } from '../../hooks/useReturnRequestList'

const messages = defineMessages({
  titleId: {
    id: 'store/return-app.return-request-list.page-header.title',
  },
  backButton: {
    id: 'store/return-app.return-request-list.page-header.goBack',
  },
})

export const StoreReturnList = () => {
  const {
    hints: { phone },
  } = useRuntime()

  const { formatMessage } = useIntl()
  const { returnRequestData } = useReturnRequestList()
  const { loading } = returnRequestData

  const headerContent = (
    <div className={`${phone ? 'mt4' : 'mt2'}`}>
      <Button
        variation="primary"
        size="small"
        disabled={loading}
        href="#/my-returns/add"
      >
        <FormattedMessage id="store/return-app.return-request-list.page-header.cta" />
      </Button>
    </div>
  )

  return (
    <ContentWrapper
      namespace="return-app"
      titleId={formatMessage(messages.titleId)}
      backButton={{
        path: '/',
        titleId: formatMessage(messages.backButton),
      }}
      headerContent={headerContent}
    >
      {() => <ListTable />}
    </ContentWrapper>
  )
}

```


[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 return-app/react/store/provider/OrderToReturnProvider.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { Dispatch, FC, SetStateAction } from 'react'
import React, { createContext, useReducer, useState } from 'react'
import { useRuntime } from 'vtex.render-runtime'

import type {
  ReturnRequestActions,
  OrderDetailsState,
} from './OrderToReturnReducer'
import {
  initialOrderToReturnState,
  orderToReturnReducer,
} from './OrderToReturnReducer'
import type { ErrorsValidation } from '../utils/validateNewReturnRequestFields'
import { validateNewReturnRequestFields } from '../utils/validateNewReturnRequestFields'
import { useStoreSettings } from '../hooks/useStoreSettings'

interface OrderToReturnContextInterface {
  returnRequest: OrderDetailsState
  inputErrors: ErrorsValidation[]
  termsAndConditions: boolean
  actions: {
    updateReturnRequest: Dispatch<ReturnRequestActions>
    areFieldsValid: () => boolean
    toogleTermsAndConditions: Dispatch<SetStateAction<boolean>>
  }
}

export const OrderToReturnContext =
  createContext<OrderToReturnContextInterface>(
    {} as OrderToReturnContextInterface
  )

export const OrderToReturnProvider: FC = ({ children }) => {
  const [returnRequest, updateReturnRequest] = useReducer(
    orderToReturnReducer,
    initialOrderToReturnState
  )

  const { data: storeSettings } = useStoreSettings()
  const { options } = storeSettings ?? {}
  const { enableSelectItemCondition } = options ?? {}

  const [termsAndConditions, setTermsAndConditions] = useState(false)

  const [inputErrors, setInputErrors] = useState<ErrorsValidation[]>([])

  const {
    culture: { locale },
  } = useRuntime()

  const areFieldsValid = (): boolean => {
    const { errors } = validateNewReturnRequestFields(returnRequest, {
      termsAndConditionsAccepted: termsAndConditions,
      locale,
      considerItemCondition: Boolean(enableSelectItemCondition),
    })

    if (errors) {
      setInputErrors(errors)

      return false
    }

    setInputErrors([])

    return true
  }

  return (
    <OrderToReturnContext.Provider
      value={{
        returnRequest,
        inputErrors,
        termsAndConditions,
        actions: {
          updateReturnRequest,
          areFieldsValid,
          toogleTermsAndConditions: setTermsAndConditions,
        },
      }}
    >
      {children}
    </OrderToReturnContext.Provider>
  )
}

```


[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 return-app/react/store/provider/StoreSettingsProvider.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FC } from 'react'
import React, { createContext, useState } from 'react'
import { useQuery } from 'react-apollo'
import { FormattedMessage } from 'react-intl'
import type { ReturnAppSettings } from 'vtex.return-app'
import { Alert } from 'vtex.styleguide'

import STORE_SETTING from '../graphql/getStoreSettings.gql'

interface SettingsContextInterface {
  data?: ReturnAppSettings
  loading: boolean
}

export const StoreSettingsContext = createContext<SettingsContextInterface>(
  {} as SettingsContextInterface
)

export const StoreSettingsPovider: FC = ({ children }) => {
  const { data, loading, error, refetch } = useQuery<{
    returnAppSettings: ReturnAppSettings
  }>(STORE_SETTING)

  const [refetching, setRefetching] = useState(false)

  const handleRefetching = async () => {
    setRefetching(true)

    try {
      await refetch()
    } catch (e) {
      console.error(e)
    } finally {
      setRefetching(false)
    }
  }

  return (
    <StoreSettingsContext.Provider
      value={{ data: data?.returnAppSettings, loading }}
    >
      {error && !refetching ? (
        <Alert
          type="error"
          action={{
            label: (
              <FormattedMessage id="store/return-app.return-order-details.setting-provider.error.retry-action" />
            ),
            onClick: () => handleRefetching(),
          }}
        >
          <FormattedMessage id="store/return-app.return-order-details.setting-provider.error" />
        </Alert>
      ) : (
        children
      )}
    </StoreSettingsContext.Provider>
  )
}

```


[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 return-app/react/store/provider/OrderToReturnReducer.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type {
  CustomerProfileDataInput,
  PickupReturnDataInput,
  RefundPaymentDataInput,
  ReturnRequestItemInput,
  Maybe,
} from 'vtex.return-app'

type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>

// When adding PartialBy in a field, it's necessary to the validation in the function isReturnRequestArgs
export interface OrderDetailsState {
  orderId: string
  items: Array<PartialBy<ReturnRequestItemInput, 'condition' | 'returnReason'>>
  customerProfileData: CustomerProfileDataInput
  pickupReturnData: PartialBy<PickupReturnDataInput, 'addressType'>
  refundPaymentData?: RefundPaymentDataInput
  userComment?: Maybe<string> | undefined
}

const initialPickupReturnData = {
  addressId: '',
  address: '',
  city: '',
  state: '',
  country: '',
  zipCode: '',
}

export const initialOrderToReturnState: OrderDetailsState = {
  orderId: '',
  items: [],
  customerProfileData: {
    name: '',
    email: '',
    phoneNumber: '',
  },
  pickupReturnData: initialPickupReturnData,
  userComment: null,
}

const costumerProfileDataAction = (
  customerProfileData: CustomerProfileDataInput
) => {
  return {
    type: 'updateCustomerProfileData' as const,
    payload: customerProfileData,
  }
}

const pickupReturnDataAction = (
  pickupReturnData: OrderDetailsState['pickupReturnData']
) => {
  return {
    type: 'updatePickupReturnData' as const,
    payload: pickupReturnData,
  }
}

const refundPaymentDataAction = (refundPaymentData: RefundPaymentDataInput) => {
  return {
    type: 'updateRefundPaymentData' as const,
    payload: refundPaymentData,
  }
}

const userCommentAction = (userComment: string) => {
  return {
    type: 'updateUserComment' as const,
    payload: userComment,
  }
}

const itemsAction = (items: OrderDetailsState['items']) => {
  return {
    type: 'updateItems' as const,
    payload: items,
  }
}

export const newReturnRequestState = ({
  orderId,
  customerProfileData,
  pickupReturnData,
  items,
  refundPaymentData,
}: OrderDetailsState) => {
  return {
    type: 'newReturnRequestState' as const,
    payload: {
      orderId,
      customerProfileData,
      pickupReturnData,
      items,
      refundPaymentData,
    },
  }
}

const resetAddress = () => ({
  type: 'resetAddress' as const,
})

export type ReturnRequestActions =
  | ReturnType<typeof costumerProfileDataAction>
  | ReturnType<typeof pickupReturnDataAction>
  | ReturnType<typeof refundPaymentDataAction>
  | ReturnType<typeof userCommentAction>
  | ReturnType<typeof newReturnRequestState>
  | ReturnType<typeof itemsAction>
  | ReturnType<typeof resetAddress>

export const orderToReturnReducer = (
  state: OrderDetailsState,
  action: ReturnRequestActions
) => {
  switch (action.type) {
    case 'updateCustomerProfileData': {
      return {
        ...state,
        customerProfileData: action.payload,
      }
    }

    case 'updatePickupReturnData': {
      return {
        ...state,
        pickupReturnData: action.payload,
      }
    }

    case 'resetAddress': {
      return {
        ...state,
        pickupReturnData: initialPickupReturnData,
      }
    }

    case 'updateRefundPaymentData': {
      return {
        ...state,
        refundPaymentData: action.payload,
      }
    }

    case 'updateUserComment': {
      return {
        ...state,
        userComment: action.payload,
      }
    }

    case 'updateItems': {
      return {
        ...state,
        items: action.payload,
      }
    }

    case 'newReturnRequestState': {
      return {
        orderId: action.payload.orderId,
        customerProfileData: action.payload.customerProfileData,
        pickupReturnData: action.payload.pickupReturnData,
        items: action.payload.items,
        refundPaymentData: action.payload.refundPaymentData,
      }
    }

    default: {
      return state
    }
  }
}

```


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

[User] Show me the implementation of return-app/react/store/utils/setInitialPickupAddress.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { ShippingData } from 'vtex.return-app'

import type { OrderDetailsState } from '../provider/OrderToReturnReducer'

export const setInitialPickupAddress = (
  shippingData: ShippingData
): OrderDetailsState['pickupReturnData'] => {
  const { geoCoordinates, ...shippingDataWithoutGeoCoordinates } = shippingData

  if (shippingData.addressType === 'CUSTOMER_ADDRESS') {
    return shippingDataWithoutGeoCoordinates
  }

  /**
   * If addressType is PICKUP_POINT, we set empty values to state.
   * This way, if the store doesn't accept pickup orders, user has to enter an address manually.
   */
  return {
    addressId: 'N/A', // This field is not needed or used anywhere else, but it was marked as required in the schema.
    address: '',
    city: '',
    state: '',
    country: '',
    zipCode: '',
  }
}

```


[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 return-app/react/store/utils/generateCustomReasonOptions.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { CustomReturnReason } from 'vtex.return-app'

import { isWithinMaxDaysToReturn } from '../../../node/utils/dateHelpers'

interface Option {
  value: string
  label: string
}

export function generateCustomReasonOptions(
  customReturnReasons: CustomReturnReason[],
  locale: string,
  creationDate: string
) {
  return customReturnReasons.reduce(
    (filteredOptions: Option[], customReason: CustomReturnReason) => {
      if (!isWithinMaxDaysToReturn(creationDate, customReason.maxDays)) {
        return filteredOptions
      }

      const localizedOption = customReason?.translations?.find(
        (element) => element.locale === locale
      )

      const reason = localizedOption?.translation ?? customReason.reason

      const newOption = {
        value: reason,
        label: reason,
      }

      filteredOptions.push(newOption)

      return filteredOptions
    },
    []
  )
}

```


[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 return-app/react/store/utils/parseReturnRequestError.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { ApolloError } from 'apollo-client'
import { defineMessages } from 'react-intl'
import type { OrderToReturnValidation } from 'vtex.return-app'

import { ORDER_TO_RETURN_VALIDATON } from './constants'

export type CodeError =
  | 'UNKNOWN_ERROR'
  | 'E_HTTP_404'
  | 'FORBIDDEN'
  | OrderToReturnValidation

const { ORDER_NOT_INVOICED, OUT_OF_MAX_DAYS } = ORDER_TO_RETURN_VALIDATON

const errorMessages = defineMessages({
  [ORDER_NOT_INVOICED]: {
    id: 'store/return-app.return-order-details.error.order-not-invoiced',
  },
  [OUT_OF_MAX_DAYS]: {
    id: 'store/return-app.return-order-details.error.out-of-max-days',
  },
  E_HTTP_404: {
    id: 'store/return-app.return-order-details.error.order-not-found',
  },
  FORBIDDEN: {
    id: 'store/return-app.return-order-details.error.forbidden',
  },
  UNKNOWN_ERROR: {
    id: 'store/return-app.return-order-details.error.unknown',
  },
})

export const parseReturnRequestError = (error: ApolloError): { id: string } => {
  const { graphQLErrors } = error

  if (!graphQLErrors.length) {
    return errorMessages.UNKNOWN_ERROR
  }

  const [{ extensions }] = graphQLErrors

  const { code } = extensions?.exception ?? {}

  const knownErrors = [
    ORDER_NOT_INVOICED,
    OUT_OF_MAX_DAYS,
    // order not found
    'E_HTTP_404',
    // userId on session doesn't match with userId on order profile
    'FORBIDDEN',
  ] as const

  const knownError = knownErrors.find((errorCode) => errorCode === code)

  const errorCode = knownError ?? 'UNKNOWN_ERROR'

  return errorMessages[errorCode]
}

```


[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 return-app/react/store/utils/defaultPaymentMethodsMessages.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

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

export const defaultPaymentMethodsMessages = defineMessages({
  card: {
    id: 'store/return-app.return-order-details.payment-options.card',
  },
  giftCard: {
    id: 'store/return-app.return-order-details.payment-options.gift-card',
  },
  bank: {
    id: 'store/return-app.return-order-details.payment-options.bank',
  },
  sameAsPurchase: {
    id: 'store/return-app.confirm-payment-methods.refund-method.p-same-as-purchase',
  },
})

```


[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 return-app/react/store/utils/formatItemsToReturn.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { OrderToReturnSummary } from 'vtex.return-app'

export function formatItemsToReturn(
  orderToReturn: OrderToReturnSummary
): ItemToReturn[] {
  const { invoicedItems, excludedItems, processedItems } = orderToReturn

  const excludedItemsIndexMap = new Map()

  for (const excludedItem of excludedItems) {
    excludedItemsIndexMap.set(excludedItem.itemIndex, true)
  }

  const processedItemsQuantityIndexMap = new Map()

  for (const processedItem of processedItems) {
    processedItemsQuantityIndexMap.set(
      processedItem.itemIndex,
      processedItem.quantity
    )
  }

  return invoicedItems.map((invoicedItem, index) => {
    const quantityAvailable =
      invoicedItem.quantity - (processedItemsQuantityIndexMap.get(index) ?? 0)

    return {
      ...invoicedItem,
      isExcluded: excludedItemsIndexMap.get(index) || false,
      // Quantity available can be negative when the store invoices the return outside the return app and doesnot apply the .
      quantityAvailable: quantityAvailable > 0 ? quantityAvailable : 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 return-app/react/store/utils/constants.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { OrderToReturnValidation } from 'vtex.return-app'

export const ORDER_TO_RETURN_VALIDATON: Record<
  OrderToReturnValidation,
  OrderToReturnValidation
> = {
  OUT_OF_MAX_DAYS: 'OUT_OF_MAX_DAYS',
  ORDER_NOT_INVOICED: 'ORDER_NOT_INVOICED',
}

```


[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 return-app/react/store/utils/validateNewReturnRequestFields.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type {
  ReturnRequestItemInput,
  ReturnRequestInput,
} from 'vtex.return-app'

import type { OrderDetailsState } from '../provider/OrderToReturnReducer'
import { isValidIBANNumber } from './isValidIBANNumber'

const hasValidReasonOrCondition = (
  item: OrderDetailsState['items'][number],
  considerItemCondition: boolean
): boolean => {
  const isOtherReason = item.returnReason?.reason === 'otherReason'
  const hasRequiredUserInput = isOtherReason
    ? Boolean(item.returnReason?.otherReason)
    : true

  const validReason = Boolean(item.returnReason) && hasRequiredUserInput

  if (considerItemCondition) {
    return Boolean(item.condition) && validReason
  }

  return validReason
}

export type ErrorsValidation =
  | 'terms-and-conditions'
  | 'no-item-selected'
  | 'reason-or-condition'
  | 'customer-data'
  | 'pickup-data'
  | 'refund-payment-data'
  | 'bank-details'

interface ValidationError {
  errors: ErrorsValidation[]
  validatedFields?: never
}

interface ValidationSuccess {
  errors?: never
  validatedFields: ReturnRequestInput
}
interface ValidationData {
  termsAndConditionsAccepted: boolean
  locale: string
  // If the item condition should be considered along the return reason
  considerItemCondition: boolean
}

export const validateNewReturnRequestFields = (
  returnRequest: OrderDetailsState,
  validationData: ValidationData
): ValidationError | ValidationSuccess => {
  const { items, pickupReturnData, customerProfileData, refundPaymentData } =
    returnRequest

  const { termsAndConditionsAccepted, locale, considerItemCondition } =
    validationData

  const errors: ErrorsValidation[] = []

  if (!termsAndConditionsAccepted) {
    errors.push('terms-and-conditions')

    // return the error on checkbox to make sure this error is the only one when happening
    return { errors }
  }

  const itemsToReturn = items.filter((item) => item.quantity > 0)

  if (itemsToReturn.length === 0) {
    errors.push('no-item-selected')
  }

  const validatedItems = itemsToReturn.filter((item) =>
    hasValidReasonOrCondition(item, considerItemCondition)
  ) as ReturnRequestItemInput[]

  if (itemsToReturn.length !== validatedItems.length) {
    errors.push('reason-or-condition')
  }

  for (const field of Object.keys(customerProfileData)) {
    if (!customerProfileData[field]) {
      errors.push('customer-data')
    }
  }

  for (const field of Object.keys(pickupReturnData)) {
    if (!pickupReturnData[field]) {
      errors.push('pickup-data')
    }
  }

  const { refundPaymentMethod } = refundPaymentData ?? {}

  if (!refundPaymentData || !refundPaymentMethod) {
    errors.push('refund-payment-data')

    return { errors }
  }

  if (refundPaymentMethod === 'bank') {
    const { iban, accountHolderName } = refundPaymentData

    if (!iban || !accountHolderName || !isValidIBANNumber(iban)) {
      errors.push('bank-details')
    }
  }

  if (!pickupReturnData.addressType) {
    /**
     * This is an app error, not a user one.
     * Tracking it here so we can notify dev AND validate it for TS. This is why the logic has to be the last one.
     */
    console.error('Missing address type')

    // We return here to satisfy TS condition for addressType check
    return { errors }
  }

  if (errors.length) {
    return { errors }
  }

  const { addressType } = pickupReturnData

  const validatedFields: ReturnRequestInput = {
    ...returnRequest,
    items: validatedItems,
    pickupReturnData: { ...pickupReturnData, addressType },
    refundPaymentData,
    locale,
  }

  return { validatedFields }
}

```


[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 return-app/react/store/utils/defaultReturnReasonsMessages.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

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

export const defaultReturnReasonsMessages = defineMessages({
  reasonAccidentalOrder: {
    id: 'store/return-app.return-order-details.dropdown-reasons.accidental-order',
  },
  reasonBetterPrice: {
    id: 'store/return-app.return-order-details.dropdown-reasons.better-price',
  },
  reasonPerformance: {
    id: 'store/return-app.return-order-details.dropdown-reasons.performance',
  },
  reasonIncompatible: {
    id: 'store/return-app.return-order-details.dropdown-reasons.incompatible',
  },
  reasonItemDamaged: {
    id: 'store/return-app.return-order-details.dropdown-reasons.item-damaged',
  },
  reasonMissedDelivery: {
    id: 'store/return-app.return-order-details.dropdown-reasons.missed-delivery',
  },
  reasonMissingParts: {
    id: 'store/return-app.return-order-details.dropdown-reasons.missing-parts',
  },
  reasonBoxDamaged: {
    id: 'store/return-app.return-order-details.dropdown-reasons.box-damaged',
  },
  reasonDifferentProduct: {
    id: 'store/return-app.return-order-details.dropdown-reasons.different-product',
  },
  reasonDefective: {
    id: 'store/return-app.return-order-details.dropdown-reasons.defective',
  },
  reasonArrivedInAddition: {
    id: 'store/return-app.return-order-details.dropdown-reasons.arrived-in-addition',
  },
  reasonNoLongerNeeded: {
    id: 'store/return-app.return-order-details.dropdown-reasons.no-longer-needed',
  },
  reasonUnauthorizedPurchase: {
    id: 'store/return-app.return-order-details.dropdown-reasons.unauthorized-purchase',
  },
  reasonDifferentFromWebsite: {
    id: 'store/return-app.return-order-details.dropdown-reasons.different-from-website',
  },
  reasonOtherReason: {
    id: 'store/return-app.return-order-details.dropdown-reasons.other-reason',
  },
  reasonSelectReason: {
    id: 'store/return-app.return-order-details.dropdown-reasons.placeholder.select-reason',
  },
})

```


[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 return-app/react/store/utils/createItemsSummary.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { OrderToReturnSummary } from 'vtex.return-app'

import { formatItemsToReturn } from './formatItemsToReturn'

export function createItemsSummary(orderToReturn: OrderToReturnSummary): {
  quantityAvailable: number
  quantity: number
} {
  const itemsToReturn = formatItemsToReturn(orderToReturn)

  const quantity = itemsToReturn.reduce((acc, value) => {
    return acc + value.quantity
  }, 0)

  const quantityAvailable = itemsToReturn.reduce((acc, value) => {
    return value.isExcluded ? acc : acc + value.quantityAvailable
  }, 0)

  return { quantity, quantityAvailable }
}

```


[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 return-app/react/store/utils/isValidIBANNumber.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
function mod97(string: string) {
  let checksum = string.slice(0, 2) as string | number
  let fragment

  for (let offset = 2; offset < string.length; offset += 7) {
    fragment = `${String(checksum)}${string.substring(offset, offset + 7)}`
    checksum = parseInt(fragment, 10) % 97
  }

  return checksum
}

export function isValidIBANNumber(input) {
  type CodeLengths = {
    [key: string]: number
  }

  const CODE_LENGTHS: CodeLengths = {
    AD: 24,
    AE: 23,
    AT: 20,
    AZ: 28,
    BA: 20,
    BE: 16,
    BG: 22,
    BH: 22,
    BR: 29,
    CH: 21,
    CR: 21,
    CY: 28,
    CZ: 24,
    DE: 22,
    DK: 18,
    DO: 28,
    EE: 20,
    ES: 24,
    FI: 18,
    FO: 18,
    FR: 27,
    GB: 22,
    GI: 23,
    GL: 18,
    GR: 27,
    GT: 28,
    HR: 21,
    HU: 28,
    IE: 22,
    IL: 23,
    IS: 26,
    IT: 27,
    JO: 30,
    KW: 30,
    KZ: 20,
    LB: 28,
    LI: 21,
    LT: 20,
    LU: 20,
    LV: 21,
    MC: 27,
    MD: 24,
    ME: 22,
    MK: 19,
    MR: 27,
    MT: 31,
    MU: 30,
    NL: 18,
    NO: 15,
    PK: 24,
    PL: 28,
    PS: 29,
    PT: 25,
    QA: 29,
    RO: 24,
    RS: 22,
    SA: 24,
    SE: 24,
    SI: 19,
    SK: 24,
    SM: 27,
    TN: 24,
    TR: 26,
    AL: 28,
    BY: 28,
    EG: 29,
    GE: 22,
    IQ: 23,
    LC: 32,
    SC: 31,
    ST: 25,
    SV: 28,
    TL: 23,
    UA: 29,
    VA: 22,
    VG: 24,
    XK: 20,
  }

  const iban = String(input)
    .toUpperCase()
    .replace(/[^A-Z0-9]/g, '')

  const code = iban.match(/^([A-Z]{2})(\d{2})([A-Z\d]+)$/)

  if (!code || iban.length !== CODE_LENGTHS[code[1]]) {
    return false
  }

  const dig = code[3] + code[1] + code[2]
  const digits = dig.replace(/[A-Z]/g, (letter) => {
    const returnVar = letter.charCodeAt(0) - 55

    return returnVar.toString()
  })

  // If the IBAN is correct the result should be 1 if not any number higher than 1.
  return mod97(digits) === 1
}

```


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

[User] Show me the implementation of return-app/react/store/graphql/getStoreSettings.gql from the return-app VTEX app.

[Assistant]
Here's the implementation:

```graphql
query storeAppSettings {
  returnAppSettings @context(provider: "vtex.return-app") {
    termsUrl
    customReturnReasons {
      reason
      maxDays
      translations {
        locale
        translation
      }
    }
    paymentOptions {
      enablePaymentMethodSelection
      allowedPaymentTypes {
        bank
        card
        giftCard
      }
    }
    options {
      enableOtherOptionSelection
      enablePickupPoints
      enableSelectItemCondition
      enableHighlightFormMessage
    }
  }
}

```


[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 return-app/react/store/hooks/useReturnRequest.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

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

import { OrderToReturnContext } from '../provider/OrderToReturnProvider'

export const useReturnRequest = () => useContext(OrderToReturnContext)

```


[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 return-app/react/store/hooks/useStoreSettings.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

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

import { StoreSettingsContext } from '../provider/StoreSettingsProvider'

export const useStoreSettings = () => useContext(StoreSettingsContext)

```


[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 return-app/react/store/createReturnRequest/components/ConfirmPaymentMethods.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage, useIntl } from 'react-intl'
import type { RefundPaymentDataInput } from 'vtex.return-app'
import { useCssHandles } from 'vtex.css-handles'
import { useRuntime } from 'vtex.render-runtime'

import { defaultPaymentMethodsMessages } from '../../utils/defaultPaymentMethodsMessages'

interface Props {
  refundPaymentData: RefundPaymentDataInput
}

const CSS_HANDLES = [
  'confirmPaymentContainer',
  'confirmPaymentTitle',
  'accountHolderWrapper',
  'ibanWrapper',
  'accountHolderText',
  'confirmPaymentValue',
  'ibanText',
  'refundPaymentText',
] as const

export const ConfirmPaymentMethods = ({ refundPaymentData }: Props) => {
  const { formatMessage } = useIntl()
  const handles = useCssHandles(CSS_HANDLES)
  const {
    hints: { phone },
  } = useRuntime()

  return (
    <div
      className={`${handles.confirmPaymentContainer} ${
        phone ? 'w-100' : 'w-40'
      }`}
    >
      <h2 className={`${handles.confirmPaymentTitle} mt0 mb6`}>
        <FormattedMessage id="store/return-app.confirm-and-submit.refund-method.title" />
      </h2>
      {refundPaymentData?.refundPaymentMethod === 'bank' ? (
        <>
          <div className={`${handles.accountHolderWrapper} flex`}>
            <p className={`${handles.accountHolderText} f6 mr2 gray b`}>
              <FormattedMessage id="store/return-app.confirm-payment-methods.refund-method.p-account-holder-name" />
            </p>
            <p className={`${handles.confirmPaymentValue} f6 gray`}>
              {refundPaymentData.accountHolderName}
            </p>
          </div>
          <div className={`${handles.ibanWrapper} flex`}>
            <p className={`${handles.ibanText} f6 mr2 gray b`}>
              <FormattedMessage id="store/return-app.confirm-payment-methods.refund-method.p-iban" />
            </p>
            <p className={`${handles.confirmPaymentValue} f6 gray `}>
              {refundPaymentData.iban}
            </p>
          </div>
        </>
      ) : (
        <p className={`${handles.confirmPaymentValue} f6 gray `}>
          {formatMessage(
            defaultPaymentMethodsMessages[
              refundPaymentData?.refundPaymentMethod
            ]
          )}
        </p>
      )}
    </div>
  )
}

```


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

[User] Show me the implementation of return-app/react/store/createReturnRequest/components/UserCommentDetails.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import type { ChangeEvent } from 'react'
import { FormattedMessage } from 'react-intl'
import { Textarea } from 'vtex.styleguide'
import { useCssHandles } from 'vtex.css-handles'

import { useReturnRequest } from '../../hooks/useReturnRequest'

const CSS_HANDLES = ['userCommentDetailsContainer'] as const

export const UserCommentDetails = () => {
  const {
    returnRequest,
    actions: { updateReturnRequest },
  } = useReturnRequest()

  const handles = useCssHandles(CSS_HANDLES)

  const { userComment } = returnRequest

  const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target

    updateReturnRequest({
      type: 'updateUserComment',
      payload: value,
    })
  }

  return (
    <div className={`${handles.userCommentDetailsContainer} mt4 ph4`}>
      <p>
        <FormattedMessage id="store/return-app.return-order-details.title.extra-comment" />
      </p>
      <div>
        <Textarea
          name="extraComment"
          resize="none"
          onChange={handleInputChange}
          maxLength="300"
          value={userComment ?? ''}
        />
      </div>
    </div>
  )
}

```


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

[User] Show me the implementation of return-app/react/store/createReturnRequest/components/ConfirmContactDetails.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage } from 'react-intl'
import type { CustomerProfileDataInput } from 'vtex.return-app'
import { useCssHandles } from 'vtex.css-handles'
import { useRuntime } from 'vtex.render-runtime'

interface Props {
  contactDetails: CustomerProfileDataInput
}

const CSS_HANDLES = [
  'confirmContactContainer',
  'confirmContactTitle',
  'confirmContactText',
] as const

export const ConfirmContactDetails = ({ contactDetails }: Props) => {
  const handles = useCssHandles(CSS_HANDLES)

  const {
    hints: { phone },
  } = useRuntime()

  return (
    <div
      className={`${handles.confirmContactContainer} ${
        phone ? 'w-100' : 'w-40'
      }`}
    >
      <h2 className={`${handles.confirmContactTitle} mt0 mb6`}>
        <FormattedMessage id="store/return-app.confirm-and-submit.contact-details.title" />
      </h2>
      <p className={`${handles.confirmContactText} f6 gray`}>
        {contactDetails.name}
      </p>
      <p className={`${handles.confirmContactText} f6 gray`}>
        {contactDetails.email}
      </p>
      <p className={`${handles.confirmContactText} f6 gray`}>
        {contactDetails.phoneNumber}
      </p>
    </div>
  )
}

```


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

[User] Show me the implementation of return-app/react/store/createReturnRequest/components/ConfirmComment.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { useRuntime } from 'vtex.render-runtime'

interface Props {
  userComment?: string | null
}

export const ConfirmComment = ({ userComment }: Props) => {
  const {
    hints: { phone },
  } = useRuntime()

  return (
    <>
      {!userComment ? null : (
        <div className={`${phone ? 'w-100' : 'w-40'}`}>
          <h2 className="mt0 mb6 pr6">
            <FormattedMessage id="store/return-app.confirm-and-submit.user-comment.title" />
          </h2>
          <p className="f6 gray pr6">{userComment}</p>
        </div>
      )}
    </>
  )
}

```


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

[User] Show me the implementation of return-app/react/store/createReturnRequest/components/ReturnInformationTable.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage, useIntl } from 'react-intl'
import type { ReturnRequestItemInput } from 'vtex.return-app'
import { useCssHandles } from 'vtex.css-handles'
import { useRuntime } from 'vtex.render-runtime'

import { defaultReturnConditionsMessages } from '../../../common/utils/defaultReturnConditionsMessages'

interface Props {
  items: ItemToReturn[]
  selectedItems: ReturnRequestItemInput[]
}

const CSS_HANDLES = [
  'returnInfoTableContainer',
  'returnInfoTheadContainer',
  'returnInfoTableText',
  'returnInfoBodyContainer',
  'returnInfoTrBodyWrapper',
  'returnInfoBodyImgWrapper',
  'returnInfoReasonConditionWrapper',
] as const

export const ReturnInformationTable = ({ items, selectedItems }: Props) => {
  const { formatMessage } = useIntl()
  const handles = useCssHandles(CSS_HANDLES)

  const {
    hints: { phone },
  } = useRuntime()

  return (
    <table className={`${handles.returnInfoTableContainer} w-100`}>
      <thead
        className={`${handles.returnInfoTheadContainer} w-100 ph4 truncate overflow-x-hidden c-muted-2 f6`}
      >
        <tr className="w-100 truncate overflow-x-hidden">
          <th
            className={`${handles.returnInfoTableText} v-mid pv0 tl bb b--muted-4 normal bg-base bt ph3 z1 pv3-s tc`}
          >
            <FormattedMessage id="store/return-app.return-order-details.table-header.product" />
          </th>
          <th
            className={`${handles.returnInfoTableText} v-mid pv0 tl bb b--muted-4 normal bg-base bt ph3 z1 pv3-s tc`}
          >
            <FormattedMessage id="store/return-app.return-order-details.table-header.quantity-to-return" />
          </th>
        </tr>
      </thead>
      <tbody className={`${handles.returnInfoBodyContainer} v-mid`}>
        {selectedItems.map(
          ({ quantity, orderItemIndex, condition, returnReason }, key) => {
            const { reason } = returnReason

            if (!quantity) {
              return null
            }

            const { imageUrl, localizedName, name } = items[orderItemIndex]

            return (
              <tr
                key={key}
                className={`${handles.returnInfoTrBodyWrapper} ph5`}
              >
                <td className={`pv5 ${phone ? 'w-80' : 'w-50'}`}>
                  <div className="flex items-center">
                    <div className={`${handles.returnInfoBodyImgWrapper} mr3`}>
                      <img src={imageUrl} alt="Product" />
                    </div>
                    <div className={handles.returnInfoReasonConditionWrapper}>
                      <p className="b">{localizedName ?? name}</p>
                      {!condition ? null : (
                        <div className="flex">
                          <p className="f6 mt0 mr3 gray b">
                            <FormattedMessage id="store/return-app.return-information-table.table-row.p-condition" />
                          </p>
                          <p className="f6 mt0 gray ">
                            {formatMessage(
                              defaultReturnConditionsMessages[condition]
                            )}
                          </p>
                        </div>
                      )}
                      <div className="flex">
                        <p className="f6 mv0 mr3 gray b">
                          {' '}
                          <FormattedMessage id="store/return-app.return-information-table.table-row.p-reason" />{' '}
                        </p>
                        <p className="f6 mv0 gray ">
                          {returnReason?.otherReason
                            ? returnReason?.otherReason
                            : reason}
                        </p>
                      </div>
                    </div>
                  </div>
                </td>
                <td className={`tc pv5 ${phone ? 'w-20' : 'w-50'}`}>
                  <p>{quantity}</p>
                </td>
              </tr>
            )
          }
        )}
      </tbody>
    </table>
  )
}

```


[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 return-app/react/store/createReturnRequest/components/OrderList.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useCallback, useEffect, useState } from 'react'
import type {
  Maybe,
  OrdersToReturnList,
  OrderToReturnSummary,
  QueryOrdersAvailableToReturnArgs,
} from 'vtex.return-app'
import { FormattedMessage, FormattedDate } from 'react-intl'
import { useRuntime } from 'vtex.render-runtime/'
import { Table, Button } from 'vtex.styleguide'
import type { ApolloQueryResult } from 'apollo-client'

import { createItemsSummary } from '../../utils/createItemsSummary'
import MobileList from '../../../common/components/returnList/MobileList'

type Operation = 'next' | 'previous'
interface Props {
  orders: OrdersToReturnList
  handlePagination: (page: number, operation: Operation) => Promise<void>
  mobileList: Array<Maybe<OrderToReturnSummary>>
  refetch: (
    variables?: QueryOrdersAvailableToReturnArgs | undefined
  ) => Promise<
    ApolloQueryResult<{ ordersAvailableToReturn: OrdersToReturnList }>
  >
}

interface RowData {
  rowData: OrderToReturnSummary
}

type OrderListTableSchemaProps = {
  navigate: (to: { to: string }) => void
  isSmallScreen: boolean
}
const OrderListTableSchema = ({
  navigate,
  isSmallScreen,
}: OrderListTableSchemaProps) => {
  const properties = {
    orderId: {
      title: (
        <FormattedMessage id="store/return-app.return-order-list.table-header.order-id" />
      ),
      minWidth: 150,
    },
    creationDate: {
      title: (
        <FormattedMessage id="store/return-app.return-order-list.table-header.creation-date" />
      ),
      cellRenderer: function formatDate({ cellData }: { cellData: string }) {
        return (
          <FormattedDate
            value={cellData}
            day="2-digit"
            month="2-digit"
            year="numeric"
          />
        )
      },
      minWidth: 120,
    },
    status: {
      title: (
        <FormattedMessage id="store/return-app.return-order-list.table-header.items-to-return" />
      ),
      cellRenderer: function availableProducts({ rowData }: RowData) {
        const { quantityAvailable, quantity } = createItemsSummary(rowData)

        return <p>{`${quantityAvailable} / ${quantity}`}</p>
      },
    },
    selectOrder: {
      title: (
        <FormattedMessage id="store/return-app.return-order-list.table-header.select-order" />
      ),
      cellRenderer: function SelectOrderButton({ rowData }: RowData) {
        const { quantityAvailable } = createItemsSummary(rowData)

        return (
          <div>
            <Button
              {...(!quantityAvailable
                ? null
                : {
                    onClick: () =>
                      navigate({
                        to: `#/my-returns/add/${rowData.orderId}`,
                      }),
                  })}
              variation="tertiary"
              collapseLeft
              disabled={!quantityAvailable}
            >
              <FormattedMessage id="store/return-app.return-order-list.table-header.select-order" />
            </Button>
          </div>
        )
      },
      minWidth: 150,
    },
  }

  const mobileOrder = {
    orderId: null,
    selectOrder: null,
  }

  return {
    properties: isSmallScreen
      ? Object.assign(mobileOrder, properties)
      : properties,
  }
}

export const OrderList = ({
  orders,
  handlePagination,
  mobileList,
  refetch,
}: Props) => {
  const {
    navigate,
    hints: { phone, mobile },
  } = useRuntime()

  const [fetchMoreState, setFetchMoreState] = useState<'IDLE' | 'LOADING'>(
    'IDLE'
  )

  const { paging } = orders
  const currentPage = paging?.currentPage ?? 1
  const perPage = paging?.perPage ?? 0
  const totalItems = paging?.total ?? 0

  const handlePaginationClick = async (operation: Operation) => {
    if (currentPage === 1 && operation === 'previous') {
      return
    }

    const newPage =
      operation === 'next' ? Number(currentPage) + 1 : Number(currentPage) - 1

    setFetchMoreState('LOADING')
    await handlePagination(newPage, 'next')
    setFetchMoreState('IDLE')
  }

  const handleFetchMoreProducts = useCallback(async () => {
    const maxPages = paging?.pages ?? 1

    const { scrollHeight } = document.documentElement
    const { scrollTop } = document.documentElement
    const { clientHeight } = document.documentElement

    const userReachedEndOfPage = scrollTop + clientHeight === scrollHeight

    if (!userReachedEndOfPage) return

    if (currentPage < maxPages) {
      try {
        await refetch({ page: currentPage + 1 })
      } catch (err) {
        console.error('Error while fetching more items', err)
      }
    }
  }, [currentPage, paging?.pages, refetch])

  useEffect(() => {
    if (!phone) return

    if (window) {
      window.addEventListener('scroll', handleFetchMoreProducts)
    }

    return () => {
      if (window) {
        window.removeEventListener('scroll', handleFetchMoreProducts)
      }
    }
  }, [phone, handleFetchMoreProducts])

  return (
    <>
      <div className="flex items-center t-body lh-copy mb3 ml3 w-two-thirds-ns w-100 blue">
        <FormattedMessage id="store/return-app.request-return.page.header.subtitle" />
      </div>

      {mobile ? (
        <MobileList cardTypeByPage="request-return" items={mobileList ?? []} />
      ) : (
        <Table
          fullWidth
          emptyStateLabel={
            <FormattedMessage id="store/return-app.return-order-list.table-empty-state-label.no-orders-available" />
          }
          schema={OrderListTableSchema({
            navigate,
            isSmallScreen: phone,
          })}
          items={orders.list}
          loading={fetchMoreState === 'LOADING'}
          pagination={{
            onNextClick: () => handlePaginationClick('next'),
            onPrevClick: () => handlePaginationClick('previous'),
            currentItemFrom: perPage * currentPage - perPage + 1,
            currentItemTo:
              perPage * currentPage > totalItems
                ? totalItems
                : perPage * currentPage,
            textOf: (
              <FormattedMessage id="store/return-app.return-order-list.table-pagination.text-of" />
            ),
            totalItems,
          }}
        />
      )}
    </>
  )
}

```


[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 return-app/react/store/createReturnRequest/components/ItemsDetails.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import type { ItemCondition } from 'vtex.return-app'
import { NumericStepper, Box } from 'vtex.styleguide'
import { useCssHandles } from 'vtex.css-handles'
import { FormattedMessage } from 'react-intl'
import { useRuntime } from 'vtex.render-runtime'

import { useReturnRequest } from '../../hooks/useReturnRequest'
import { CustomMessage } from './layout/CustomMessage'
import { RenderConditionDropdown } from './RenderConditionDropdown'
import { RenderReasonDropdown } from './RenderReasonDropdown'
import { useStoreSettings } from '../../hooks/useStoreSettings'

interface Props {
  itemToReturn: ItemToReturn
  creationDate?: string
}

const CSS_HANDLES = [
  'detailsRowContainer',
  'detailsTdWrapper',
  'productSectionWrapper',
  'productText',
  'productImageWrapper',
  'productImage',
  'itemsDetailText',
  'cardWrapper',
  'productDetailsWrapper',
  'productText',
  'quantityWrapper',
  'quantityKey',
  'quantityValue',
  'availableToReturnWrapper',
  'availableToReturnKey',
  'availableToReturnValue',
  'quantitySelectorWrapper',
  'reasonWrapper',
  'conditionWrapper',
] as const

export const ItemsDetails = (props: Props) => {
  const {
    itemToReturn: {
      quantity,
      quantityAvailable,
      isExcluded,
      orderItemIndex,
      imageUrl,
      name,
      localizedName,
    },
    creationDate,
  } = props

  const {
    hints: { phone },
  } = useRuntime()

  const handles = useCssHandles(CSS_HANDLES)

  const { data: storeSettings } = useStoreSettings()
  const { options } = storeSettings ?? {}
  const { enableSelectItemCondition } = options ?? {}

  const {
    returnRequest,
    inputErrors,
    actions: { updateReturnRequest },
  } = useReturnRequest()

  const { items } = returnRequest

  const currentItem = items.find(
    ({ orderItemIndex: index }) => index === orderItemIndex
  )

  const handleQuantityChange = (value: number) => {
    if (!currentItem) return
    const updatedItems = items.map((item) => {
      if (item.orderItemIndex !== orderItemIndex) {
        return item
      }

      return {
        ...item,
        quantity: value,
      }
    })

    updateReturnRequest({
      type: 'updateItems',
      payload: updatedItems,
    })
  }

  const handleReasonChange = (reason: string, otherReason = '') => {
    if (!currentItem) return
    const updatedItems = items.map((item) => {
      if (item.orderItemIndex !== orderItemIndex) {
        return item
      }

      return {
        ...item,
        returnReason: {
          reason,
          ...(reason === 'otherReason' ? { otherReason } : null),
        },
      }
    })

    updateReturnRequest({
      type: 'updateItems',
      payload: updatedItems,
    })
  }

  const handleConditionChange = (condition: ItemCondition) => {
    if (!currentItem) return
    const updatedItems = items.map((item) => {
      if (item.orderItemIndex !== orderItemIndex) {
        return item
      }

      return {
        ...item,
        condition,
      }
    })

    updateReturnRequest({
      type: 'updateItems',
      payload: updatedItems,
    })
  }

  const noReasonOrCondition = inputErrors.some(
    (error) => error === 'reason-or-condition'
  )

  const selected = !isExcluded && currentItem?.quantity

  const reasonError = noReasonOrCondition && selected

  const emptyTextareaError =
    currentItem?.returnReason?.reason === 'otherReason' &&
    !currentItem?.returnReason?.otherReason

  const reasonErrorEmptyValue =
    !currentItem?.returnReason?.reason || emptyTextareaError

  const conditionError =
    noReasonOrCondition && selected && !currentItem?.condition

  const availableToReturn = isExcluded ? 0 : quantityAvailable

  const ItemQuantityDataCell = (
    <>
      <td className={`${handles.detailsTdWrapper} pa4`}>
        <p className={`${handles.itemsDetailText} tc`}>{quantity}</p>
      </td>
      <td className={`${handles.detailsTdWrapper} pa4`}>
        <p className={`${handles.itemsDetailText} tc`}>{availableToReturn}</p>
      </td>
    </>
  )

  if (phone) {
    return (
      <div className={`${handles.cardWrapper} mb4`}>
        <Box>
          <div className={`${handles.productImageWrapper} flex`}>
            <img
              className={`${handles.productImage}`}
              src={imageUrl}
              alt="Product"
            />
          </div>
          <div className={`${handles.productDetailsWrapper} flex flex-column`}>
            <p className={`${handles.productText}`}>{localizedName ?? name}</p>
            <div className={`${handles.quantityWrapper} flex flex-row mb4`}>
              <span className={`${handles.quantityKey} mr2`}>
                <FormattedMessage id="store/return-app.return-order-details.table-header.quantity" />
                :
              </span>
              <span className={`${handles.quantityValue}`}>{quantity}</span>
            </div>
            <div
              className={`${handles.availableToReturnWrapper} flex flex-row mb4`}
            >
              <span className={`${handles.availableToReturnKey} mr2`}>
                <FormattedMessage id="store/return-app.return-order-details.table-header.available-to-return" />
                :
              </span>
              <span className={`${handles.availableToReturnValue}`}>
                {availableToReturn}
              </span>
            </div>
            {isExcluded ? (
              <CustomMessage
                status="warning"
                message={
                  <FormattedMessage id="store/return-app.return-item-details.excluded-items.warning" />
                }
              />
            ) : null}
            <div className={`${handles.quantitySelectorWrapper} mb4`}>
              <NumericStepper
                size="small"
                maxValue={availableToReturn}
                value={currentItem?.quantity ?? 0}
                onChange={(e: { value: number }) =>
                  handleQuantityChange(e.value)
                }
              />
            </div>
            <div className={`${handles.reasonWrapper} mb4`}>
              <RenderReasonDropdown
                isExcluded={isExcluded}
                reason={currentItem?.returnReason?.reason ?? ''}
                otherReason={currentItem?.returnReason?.otherReason ?? ''}
                onReasonChange={handleReasonChange}
                creationDate={creationDate}
              />
              {reasonError && reasonErrorEmptyValue ? (
                <CustomMessage
                  status="error"
                  message={
                    <FormattedMessage id="store/return-app.return-item-details.dropdown-reason.error" />
                  }
                />
              ) : null}
            </div>
            {!enableSelectItemCondition ? null : (
              <div className={`${handles.conditionWrapper}`}>
                <RenderConditionDropdown
                  isExcluded={isExcluded}
                  condition={currentItem?.condition ?? ''}
                  onConditionChange={handleConditionChange}
                />
                {conditionError ? (
                  <CustomMessage
                    status="error"
                    message={
                      <FormattedMessage id="store/return-app.return-item-details.dropdown-condition.error" />
                    }
                  />
                ) : null}
              </div>
            )}
          </div>
        </Box>
      </div>
    )
  }

  return (
    <tr className={`${handles.detailsRowContainer}`}>
      <td className={`${handles.detailsTdWrapper} pa4`}>
        <section className={`${handles.productSectionWrapper} flex`}>
          <div
            className={`${handles.productImageWrapper} flex`}
            style={{ flexBasis: '50%' }}
          >
            <img
              className={`${handles.productImage}`}
              src={imageUrl}
              alt="Product"
            />
          </div>
          <p
            className={`${handles.productText} t-body fw5 ml3`}
            style={{ flexBasis: '100%' }}
          >
            {localizedName ?? name}
          </p>
          {isExcluded ? (
            <CustomMessage
              status="warning"
              message={
                <FormattedMessage id="store/return-app.return-item-details.excluded-items.warning" />
              }
            />
          ) : null}
        </section>
      </td>
      {ItemQuantityDataCell}
      <td className={`${handles.detailsTdWrapper} pa4`}>
        <NumericStepper
          size="small"
          maxValue={availableToReturn}
          value={currentItem?.quantity ?? 0}
          onChange={(e: { value: number }) => handleQuantityChange(e.value)}
        />
      </td>
      <td className={`${handles.detailsTdWrapper} pa4`}>
        <RenderReasonDropdown
          isExcluded={isExcluded}
          reason={currentItem?.returnReason?.reason ?? ''}
          otherReason={currentItem?.returnReason?.otherReason ?? ''}
          onReasonChange={handleReasonChange}
          creationDate={creationDate}
        />
        {reasonError && reasonErrorEmptyValue ? (
          <CustomMessage
            status="error"
            message={
              <FormattedMessage id="store/return-app.return-item-details.dropdown-reason.error" />
            }
          />
        ) : null}
      </td>
      {!enableSelectItemCondition ? null : (
        <td className={`${handles.detailsTdWrapper} pa4`}>
          <RenderConditionDropdown
            isExcluded={isExcluded}
            condition={currentItem?.condition ?? ''}
            onConditionChange={handleConditionChange}
          />
          {conditionError ? (
            <CustomMessage
              status="error"
              message={
                <FormattedMessage id="store/return-app.return-item-details.dropdown-condition.error" />
              }
            />
          ) : null}
        </td>
      )}
    </tr>
  )
}

```


[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 return-app/react/store/createReturnRequest/components/ContactDetails.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import type { ChangeEvent } from 'react'
import { useIntl, defineMessages, FormattedMessage } from 'react-intl'
import { Input } from 'vtex.styleguide'
import { useCssHandles } from 'vtex.css-handles'

import { useReturnRequest } from '../../hooks/useReturnRequest'
import { CustomMessage } from './layout/CustomMessage'

const messages = defineMessages({
  nameInput: {
    id: 'store/return-app.return-order-details.inputs.name-input',
  },
  emailInput: {
    id: 'store/return-app.return-order-details.inputs.email-input',
  },
  phoneInput: {
    id: 'store/return-app.return-order-details.inputs.phone-input',
  },
})

const CSS_HANDLES = [
  'contactDetailsContainer',
  'contactDetailsTitle',
  'contactNameInputWrapper',
  'contactEmailInputWrapper',
  'contactPhoneInputWrapper',
] as const

export const ContactDetails = () => {
  const handles = useCssHandles(CSS_HANDLES)

  const {
    returnRequest: { customerProfileData },
    inputErrors,
    actions: { updateReturnRequest },
  } = useReturnRequest()

  const { name, email, phoneNumber } = customerProfileData

  const { formatMessage } = useIntl()

  const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { name: fieldName, value } = event.target

    updateReturnRequest({
      type: 'updateCustomerProfileData',
      payload: {
        ...customerProfileData,
        [fieldName]: value,
      },
    })
  }

  const contactError = inputErrors.some((error) => error === 'customer-data')

  return (
    <div
      className={`${handles.contactDetailsContainer} flex-ns flex-wrap flex-auto flex-column pa4`}
    >
      <p className={`${handles.contactDetailsContainer}`}>
        <FormattedMessage id="store/return-app.return-order-details.title.contact-details" />
      </p>
      <div className={`${handles.contactNameInputWrapper} mb4`}>
        <Input
          name="name"
          required
          placeholder={formatMessage(messages.nameInput)}
          onChange={handleInputChange}
          value={name}
        />
        {contactError && !name ? (
          <CustomMessage
            status="error"
            message={
              <FormattedMessage id="store/return-app.return-contact-details.name-input.error" />
            }
          />
        ) : null}
      </div>
      <div className={`${handles.contactEmailInputWrapper} mb4`}>
        <Input
          readOnly
          name="email"
          placeholder={formatMessage(messages.emailInput)}
          onChange={handleInputChange}
          value={email}
        />
      </div>
      <div className={`${handles.contactPhoneInputWrapper} mb4`}>
        <Input
          name="phoneNumber"
          required
          placeholder={formatMessage(messages.phoneInput)}
          onChange={handleInputChange}
          value={phoneNumber}
          maxLength={50}
        />
        {contactError && !phoneNumber ? (
          <CustomMessage
            status="error"
            message={
              <FormattedMessage id="store/return-app.return-contact-details.phone-input.error" />
            }
          />
        ) : null}
      </div>
    </div>
  )
}

```


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

[User] Show me the implementation of return-app/react/store/createReturnRequest/components/PickupPointSelector.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useState, useRef } from 'react'
import type { ChangeEvent } from 'react'
import { useQuery } from 'react-apollo'
import type {
  QueryNearestPickupPointsArgs,
  NearPickupPointQueryResponse,
  PickupPoint,
} from 'vtex.return-app'
import { useCssHandles } from 'vtex.css-handles'
import { Dropdown, Spinner } from 'vtex.styleguide'
import { FormattedMessage } from 'react-intl'

import NEAREST_PICKUP_POINTS from '../graphql/nearestPickupPoints.gql'
import { useReturnRequest } from '../../hooks/useReturnRequest'

interface Props {
  geoCoordinates: GeoCoordinates
}

interface PickupPointsDropdownOptions {
  value: string
  label: string
}

const CSS_HANDLES = ['pickupPointContainer'] as const

export const PickupPointSelector = ({ geoCoordinates }: Props) => {
  const [lat, long] = geoCoordinates.toString().split(',')
  const handles = useCssHandles(CSS_HANDLES)

  const {
    returnRequest: { pickupReturnData },
    actions: { updateReturnRequest },
  } = useReturnRequest()

  const [pickupPointsDropdownOptions, setPickupPointsDropdownOptions] =
    useState<PickupPointsDropdownOptions[]>([])

  const pickupPointsRef = useRef<Map<string, PickupPoint> | null>(null)

  const { loading, error } = useQuery<
    {
      nearestPickupPoints: NearPickupPointQueryResponse
    },
    QueryNearestPickupPointsArgs
  >(NEAREST_PICKUP_POINTS, {
    variables: {
      lat,
      long,
    },
    onCompleted: (dataOnComplete) => {
      const { nearestPickupPoints } = dataOnComplete
      const dropdownOptions = nearestPickupPoints.items.map((item) => {
        const { friendlyName, address } = item.pickupPoint
        const { street, number, postalCode, addressId } = address

        return {
          value: addressId ?? '',
          label: `${friendlyName ?? ''} ${street ?? ''} ${number ?? ''} ${
            postalCode ?? ''
          }`,
        }
      })

      const pickupPointsMap = new Map<string, PickupPoint>()

      for (const { pickupPoint } of nearestPickupPoints.items) {
        const {
          address: { addressId },
        } = pickupPoint

        pickupPointsMap.set(addressId, pickupPoint)
      }

      setPickupPointsDropdownOptions(dropdownOptions)
      pickupPointsRef.current = pickupPointsMap
    },
  })

  const handlePickupPointSelected = (e: ChangeEvent<HTMLInputElement>) => {
    const pickupPointId = e.currentTarget.value

    const pickupPoint = pickupPointsRef.current?.get(pickupPointId)

    if (loading || !pickupPoint) return

    const { address } = pickupPoint
    const { street, number, city, country, state, postalCode, addressId } =
      address

    const pickupPointReturnData = {
      address: `${street ?? ''} ${number ?? ''}`,
      city: city ?? '',
      state: state ?? '',
      zipCode: postalCode ?? '',
      country: country ?? '',
      addressId,
    }

    updateReturnRequest({
      type: 'updatePickupReturnData',
      payload: {
        ...pickupPointReturnData,
        addressType: 'PICKUP_POINT',
      },
    })
  }

  return (
    <div className={`${handles.pickupPointContainer} mb4`}>
      {loading ? (
        <div className="h2">
          <Spinner />
        </div>
      ) : (
        <FormattedMessage id="store/return-app.return-order-details.pickup-address.drop-off-points.dropdown.placehoder">
          {(placehoder) => (
            <Dropdown
              label=""
              error={Boolean(error)}
              errorMessage={
                error ? (
                  <FormattedMessage id="store/return-app.return-order-details.pickup-address.drop-off-points.dropdown.error" />
                ) : undefined
              }
              placeholder={placehoder}
              options={pickupPointsDropdownOptions}
              value={pickupReturnData.addressId}
              onChange={handlePickupPointSelected}
              preventTruncate
            />
          )}
        </FormattedMessage>
      )}
    </div>
  )
}

```