[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/typings/vtex.return-app.d.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface ItemToReturn {
  id: string
  quantity: number
  quantityAvailable: number
  isExcluded: boolean
  name: string
  localizedName?: string | null
  imageUrl: string
  orderItemIndex: number
}

type MaybeGlobal<T> = T | null

type GeoCoordinates = Array<MaybeGlobal<number>>

```


[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/admin/AdminLoader.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import type { FC, ReactElement } from 'react'
import type { ApolloError } from 'apollo-client'
import { EmptyState, Spinner } from 'vtex.styleguide'

interface Props {
  error?: ApolloError
  loading: boolean
  data?: unknown
  errorMessages: {
    errorTitle: ReactElement
    errorDescription?: ReactElement
  }
}

export const AdminLoader: FC<Props> = ({
  error,
  loading,
  data,
  errorMessages,
  children,
}) => {
  if (error) {
    return (
      <EmptyState title={errorMessages.errorTitle}>
        {errorMessages.errorDescription}
      </EmptyState>
    )
  }

  if (loading || !data) {
    return <Spinner />
  }

  return <>{children}</>
}

```


[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/admin/AdminReturnDetails.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'

import { ReturnDetailsContainer } from './ReturnDetails/ReturnDetailsContainer'
import { AlertProvider } from './provider/AlertProvider'
import { ReturnDetailsProvider } from '../common/provider/ReturnDetailsProvider'
import { UpdateRequestStatusProvider } from './provider/UpdateRequestStatusProvider'

interface CustomRouteProps {
  params: {
    id: string
  }
}

export const AdminReturnDetails = ({ params }: CustomRouteProps) => {
  return (
    <AlertProvider>
      <ReturnDetailsProvider requestId={params.id}>
        <UpdateRequestStatusProvider>
          <ReturnDetailsContainer />
        </UpdateRequestStatusProvider>
      </ReturnDetailsProvider>
    </AlertProvider>
  )
}

```


[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/admin/AdminReturnSettings.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'

import { RMASettings } from './settings/RMASettings'
import { SettingsProvider } from './settings/provider/SettingsProvider'
import { AlertProvider } from './provider/AlertProvider'

export const RMASettingsWrapper = () => {
  return (
    <AlertProvider>
      <SettingsProvider>
        <RMASettings />
      </SettingsProvider>
    </AlertProvider>
  )
}

```


[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/admin/AdminReturnList.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { AdminReturnList } from './ReturnList/ReturnListContainer'

export default AdminReturnList

```


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

[Assistant]
Here's the implementation:

```typescript
import type {
  Status,
  RefundStatusData,
  RefundStatusComment,
} from 'vtex.return-app'
import { defineMessages } from 'react-intl'

const statusSequence: Status[] = [
  'new',
  'processing',
  'pickedUpFromClient',
  'pendingVerification',
  'packageVerified',
  'amountRefunded',
]

export const statusAllowed: Record<Status, Status[]> = {
  new: ['new', 'processing', 'denied', 'cancelled'],
  processing: ['processing', 'pickedUpFromClient', 'denied', 'cancelled'],
  pickedUpFromClient: ['pickedUpFromClient', 'pendingVerification', 'denied'],
  // In this step, when sending the items to the resolver, it will assign the status denied or packageVerified based on the items sent.
  pendingVerification: ['pendingVerification'],
  packageVerified: ['packageVerified', 'amountRefunded'],
  amountRefunded: ['amountRefunded'],
  denied: ['denied'],
  cancelled: ['cancelled'],
}

export const statusMessageIdAdmin = defineMessages({
  new: { id: 'store/return-app-status.new' },
  processing: { id: 'store/return-app-status.processing' },
  pickedUpFromClient: { id: 'store/return-app-status.pickedup-from-client' },
  pendingVerification: { id: 'store/return-app-status.pending-verification' },
  packageVerified: { id: 'store/return-app-status.package-verified' },
  amountRefunded: { id: 'store/return-app-status.refunded' },
  denied: { id: 'store/return-app-status.denied' },
  cancelled: { id: 'store/return-app-status.cancelled' },
})

export const timelineStatusMessageId = defineMessages({
  new: { id: 'store/return-app-status.timeline.new' },
  processing: { id: 'store/return-app-status.timeline.processing' },
  pickedUpFromClient: {
    id: 'store/return-app-status.timeline.pickedup-from-client',
  },
  pendingVerification: {
    id: 'store/return-app-status.timeline.pending-verification',
  },
  packageVerified: { id: 'store/return-app-status.timeline.package-verified' },
  amountRefunded: { id: 'store/return-app-status.timeline.refunded' },
  denied: { id: 'store/return-app-status.timeline.denied' },
  cancelled: { id: 'store/return-app-status.timeline.cancelled' },
})

type Comments = RefundStatusComment[]
interface VisitedStatus {
  status: Status
  visited: boolean
  comments?: Comments
  createdAt?: string
  submittedBy?: string | null
}

export const createStatusTimeline = (
  currentStatus: Status,
  refundStatusData: RefundStatusData[]
): VisitedStatus[] => {
  const refundStatusMap = new Map<Status, VisitedStatus>()

  for (const status of refundStatusData ?? []) {
    const { status: statusName, comments, createdAt, submittedBy } = status

    refundStatusMap.set(statusName as Status, {
      status: statusName as Status,
      visited: true,
      comments,
      createdAt,
      submittedBy,
    })
  }

  const statusTimeline: VisitedStatus[] = []

  const isDenied = currentStatus === 'denied'
  const isCancelled = currentStatus === 'cancelled'

  for (const statusName of statusSequence) {
    const status = refundStatusMap.get(statusName)

    if (!status && !isDenied && !isCancelled) {
      statusTimeline.push({ status: statusName, visited: false })
      continue
    }

    if (status) {
      statusTimeline.push(status as VisitedStatus)
    }
  }

  if (isDenied || isCancelled) {
    const status = refundStatusMap.get(isDenied ? 'denied' : 'cancelled')

    if (status) {
      statusTimeline.push(status)
    }
  }

  return statusTimeline
}

```


[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/graphql/getReturnRequestList.gql from the return-app VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getReturnRequestList($filter: ReturnRequestFilters, $page: Int!) {
  returnRequestList(filter: $filter, page: $page)
    @context(provider: "vtex.return-app") {
    list {
      id
      sequenceNumber
      createdIn
      status
      orderId
      items {
        id
        imageUrl
      }
    }
    paging {
      total
      pages
      currentPage
      perPage
    }
  }
}

```


[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/graphql/createLabel.gql from the return-app VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation CreateLabel(
  $street1: String
  $street2: String
  $city: String
  $state: String
  $zip: String
  $country: String
  $name: String
  $phone: String
) {
  createLabel(
    street1: $street1
    street2: $street2
    city: $city
    state: $state
    zip: $zip
    country: $country
    name: $name
    phone: $phone
  ) @context(provider: "vtex.easypost") {
    labelUrl
  }
}

```


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

[Assistant]
Here's the implementation:

```typescript
import { useQuery } from 'react-apollo'
import type {
  ReturnRequestList as ReturnRequestListResponse,
  QueryReturnRequestListArgs,
} from 'vtex.return-app'

import RETURN_REQUEST_LIST from '../graphql/getReturnRequestList.gql'

export const useReturnRequestList = () => {
  const { data, loading, error, refetch } = useQuery<
    {
      returnRequestList: ReturnRequestListResponse
    },
    QueryReturnRequestListArgs
  >(RETURN_REQUEST_LIST, {
    variables: {
      page: 1,
    },
    notifyOnNetworkStatusChange: true,
    fetchPolicy: 'no-cache',
  })

  return { returnRequestData: { data, loading, error, refetch } }
}

```


[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/StoreMyReturnsPage.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
export { StoreReturnList } from './ReturnRequest/StoreReturnList'
export { StoreReturnDetailsContainer } from './ReturnRequest/StoreReturnDetails'

```


[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/StoreReturnAppRouter.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { Route, Switch } from 'vtex.my-account-commons/Router'

import {
  StoreReturnList,
  StoreReturnDetailsContainer,
} from './StoreMyReturnsPage'
import {
  OrderListContainer,
  CreateReturnRequestContainer,
} from './StoreMyReturnsAdd'

export const AppRouter = () => {
  return (
    <Switch>
      <Route exact path="/my-returns" component={StoreReturnList} />
      <Route
        exact
        path="/my-returns/details/:id"
        component={StoreReturnDetailsContainer}
      />
      <Route exact path="/my-returns/add" component={OrderListContainer} />
      <Route
        exact
        path="/my-returns/add/:orderId"
        component={CreateReturnRequestContainer}
      />
    </Switch>
  )
}

export default AppRouter

```


[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/StoreMyReturnsAdd.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
export { OrderListContainer } from './createReturnRequest/OrderListContainer'
export { CreateReturnRequestContainer } from './createReturnRequest/CreateReturnRequest'

```


[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/typings/vtex.my-account-commons/index.d.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.my-account-commons' {
  export const BaseLoading
  export const SkeletonPiece
  export const SkeletonBox
  export const ContentWrapper
  export const GenericError
}

```


[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/admin/settings/RMASettings.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useState, useEffect, useRef } from 'react'
import type { FormEvent, ReactElement } from 'react'
import type {
  PaymentOptions as PaymentOptionsInterface,
  PaymentType,
} from 'vtex.return-app'
import { FormattedMessage } from 'react-intl'
import {
  Layout,
  PageHeader,
  PageBlock,
  Divider,
  Button,
  Spinner,
  EmptyState,
} from 'vtex.styleguide'

import { CustomReasons } from './components/CustomReasons'
import { ExcludedCategories } from './components/ExcludedCategories'
import { GeneralOptions } from './components/GeneralOptions'
import { PaymentOptions } from './components/PaymentOptions'
import { RequiredOptions } from './components/RequiredOptions'
import { WarningModal } from './components/WarningModal'
import { useSettings } from './hooks/useSettings'

export interface ModalWarningState {
  openModal: boolean
  customMaxDays: number
  attemptNewSave: boolean
}

export interface CheckboxProps {
  label: ReactElement
  checked: boolean
  name: string
}

const validateOptions = (paymentOptions: PaymentOptionsInterface) => {
  const { enablePaymentMethodSelection, allowedPaymentTypes } = paymentOptions

  // If the user has not enabled the payment method selection, then the allowed payment types can be all unselected.
  if (!enablePaymentMethodSelection) return true

  let result = false

  for (const paymentType of Object.keys(allowedPaymentTypes)) {
    // If we have at least one payment method selected, then the payment options are valid.
    if (allowedPaymentTypes[paymentType] && paymentType !== '__typename') {
      result = true
      break
    }
  }

  return result
}

export const RMASettings = () => {
  const {
    appSettings,
    loading,
    error,
    savingAppSettings,
    actions: { handleSaveAppSettings, dispatch },
  } = useSettings()

  const [maxDaysWarning, setWarning] = useState<ModalWarningState>({
    openModal: false,
    customMaxDays: 0,
    attemptNewSave: false,
  })

  const [hasPaymentMethodError, setHasPaymentMethodError] = useState(false)

  const paymentMethodsRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!maxDaysWarning.attemptNewSave) return

    handleSaveAppSettings()

    setWarning({
      ...maxDaysWarning,
      attemptNewSave: false,
    })
  }, [handleSaveAppSettings, maxDaysWarning])

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()

    const { customReturnReasons, maxDays, paymentOptions } = appSettings

    const maxCustomOptionsDays = customReturnReasons?.reduce(
      (maxDay, option) => (maxDay > option.maxDays ? maxDay : option.maxDays),
      0
    )

    if (maxCustomOptionsDays && maxCustomOptionsDays < maxDays) {
      setWarning({
        ...maxDaysWarning,
        openModal: true,
        customMaxDays: maxCustomOptionsDays,
      })

      return
    }

    if (!validateOptions(paymentOptions)) {
      setHasPaymentMethodError(true)
      paymentMethodsRef.current?.scrollIntoView()

      return
    }

    setHasPaymentMethodError(false)

    handleSaveAppSettings()
  }

  const handleOptionSelection = (options: { string: CheckboxProps }) => {
    const paymentOptions = Object.keys(options)

    const updatedPaymentOptions = paymentOptions.reduce<PaymentType>(
      (acc, paymentOption) => {
        return {
          ...acc,
          [paymentOption]: options[paymentOption].checked,
        }
      },
      {}
    )

    const paymentOptionsPayload = {
      ...appSettings.paymentOptions,
      allowedPaymentTypes: updatedPaymentOptions,
    }

    dispatch({
      type: 'updatePaymentOptions',
      payload: {
        ...appSettings.paymentOptions,
        allowedPaymentTypes: updatedPaymentOptions,
      },
    })

    if (!validateOptions(paymentOptionsPayload)) {
      setHasPaymentMethodError(true)

      return
    }

    setHasPaymentMethodError(false)
  }

  return (
    <Layout
      pageHeader={
        <PageHeader
          title={
            <FormattedMessage id="admin/return-app.settings.navigation.label" />
          }
        />
      }
    >
      <PageBlock variation="full">
        {error ? (
          <EmptyState
            title={
              <FormattedMessage id="admin/return-app.settings.error.header" />
            }
          >
            <p>
              <FormattedMessage id="admin/return-app.settings.error.description" />
            </p>
          </EmptyState>
        ) : loading ? (
          <Spinner />
        ) : (
          <>
            {maxDaysWarning.openModal && (
              <WarningModal
                setWarning={setWarning}
                customMaxDays={maxDaysWarning.customMaxDays}
              />
            )}
            <form onSubmit={handleSubmit}>
              <RequiredOptions />
              <Divider />
              <ExcludedCategories />
              <Divider />
              <PaymentOptions
                handleOptionSelection={handleOptionSelection}
                hasError={hasPaymentMethodError}
                ref={paymentMethodsRef}
              />
              <Divider />
              <CustomReasons />
              <Divider />
              <GeneralOptions />
              <Divider />
              <div className="flex flex-column mt6">
                <Button
                  disabled={savingAppSettings}
                  variation="primary"
                  type="submit"
                >
                  {savingAppSettings ? (
                    <Spinner size={20} />
                  ) : (
                    <FormattedMessage id="admin/return-app.settings.save.button" />
                  )}
                </Button>
              </div>
            </form>
          </>
        )}
      </PageBlock>
    </Layout>
  )
}

```


[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/admin/provider/AlertProvider.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FC, ReactElement } from 'react'
import React, { createContext, useState, useCallback, useEffect } from 'react'
import { Alert } from 'vtex.styleguide'

type AlertStatus = 'success' | 'error'

interface AlertContextInterface {
  openAlert: (status: AlertStatus, message: string | ReactElement) => void
}

export const AlertContext = createContext<AlertContextInterface>(
  {} as AlertContextInterface
)

export const AlertProvider: FC = ({ children }) => {
  const [alertStatus, setAlertStatus] = useState<AlertStatus | ''>('')
  const [message, setMessage] = useState<string | ReactElement>('')

  const openAlert = (
    status: AlertStatus,
    alertMessage: string | ReactElement
  ) => {
    setAlertStatus(status)
    setMessage(alertMessage)
  }

  const handleClose = useCallback(() => {
    if (alertStatus) {
      setAlertStatus('')
      setMessage('')
    }
  }, [alertStatus])

  useEffect(() => {
    const timeout = setTimeout(() => {
      handleClose()
    }, 5000)

    return () => {
      clearTimeout(timeout)
    }
  }, [handleClose, alertStatus])

  return (
    <AlertContext.Provider value={{ openAlert }}>
      {alertStatus ? (
        <div className="w-100 fixed z-max overflow-hidden">
          <div
            className="mt7"
            style={{ maxWidth: '520px', margin: '2rem auto' }}
          >
            <Alert type={alertStatus} onClose={handleClose}>
              {message}
            </Alert>
          </div>
        </div>
      ) : null}
      {children}
    </AlertContext.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/admin/provider/UpdateRequestStatusProvider.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FC } from 'react'
import React, { createContext } from 'react'
import type {
  Status,
  ReturnRequestCommentInput,
  RefundDataInput,
  ReturnRequestResponse,
  MutationUpdateReturnRequestStatusArgs,
} from 'vtex.return-app'
import { useMutation } from 'react-apollo'
import { FormattedMessage } from 'react-intl'

import UPDATE_RETURN_STATUS from '../graphql/updateReturnRequestStatus.gql'
import { useAlert } from '../hooks/userAlert'
import { useReturnDetails } from '../../common/hooks/useReturnDetails'

interface HandleStatusUpdateArgs {
  status: Status
  id: string
  comment?: ReturnRequestCommentInput
  cleanUp?: () => void
  refundData?: RefundDataInput
}

interface UpdateRequestInterface {
  handleStatusUpdate: (args: HandleStatusUpdateArgs) => Promise<void>
  submitting: boolean
}

export const UpdateRequestStatusContext = createContext<UpdateRequestInterface>(
  {} as UpdateRequestInterface
)

export const UpdateRequestStatusProvider: FC = ({ children }) => {
  const { openAlert } = useAlert()
  const { _handleUpdateQuery } = useReturnDetails()

  const [updateReturnStatus, { loading: submitting }] = useMutation<
    {
      updateReturnRequestStatus: ReturnRequestResponse
    },
    MutationUpdateReturnRequestStatusArgs
  >(UPDATE_RETURN_STATUS)

  const handleStatusUpdate = async (args: HandleStatusUpdateArgs) => {
    const { id, status, comment, cleanUp, refundData } = args

    try {
      const { errors, data: mutationData } = await updateReturnStatus({
        variables: {
          requestId: id,
          status,
          ...(comment ? { comment } : {}),
          ...(refundData ? { refundData } : {}),
        },
      })

      if (errors) {
        throw new Error('Error updating return request status')
      }

      openAlert(
        'success',
        <FormattedMessage id="admin/return-app.return-request-details.update-status.alert.success" />
      )

      cleanUp?.()
      if (!mutationData) return
      _handleUpdateQuery(mutationData.updateReturnRequestStatus)
    } catch {
      openAlert(
        'error',
        <FormattedMessage id="admin/return-app.return-request-details.update-status.alert.error" />
      )
    }
  }

  return (
    <UpdateRequestStatusContext.Provider
      value={{ handleStatusUpdate, submitting }}
    >
      {children}
    </UpdateRequestStatusContext.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/admin/ReturnDetails/ReturnDetailsContainer.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useState } from 'react'
import { Layout, PageHeader, PageBlock } from 'vtex.styleguide'
import { FormattedMessage } from 'react-intl'
import { useRuntime } from 'vtex.render-runtime'

import { UpdateRequestStatus } from './components/UpdateRequestStatus'
import { useReturnDetails } from '../../common/hooks/useReturnDetails'
import { VerifyItemsPage } from './components/VerifyItems/VerifyItemsPage'
import { ItemDetailsList } from '../../common/components/ReturnDetails/ItemDetails/ItemDetailsList'
import { ContactDetails } from '../../common/components/ContactDetails'
import { PickupAddress } from '../../common/components/ReturnDetails/PickupAddress'
import { RefundMethodDetail } from '../../common/components/ReturnDetails/RefundMethodDetail'
import { AdminLoader } from '../AdminLoader'
import { ReturnValues } from '../../common/components/ReturnDetails/ReturnValues/ReturnValues'
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'

type Pages = 'return-details' | 'verify-items'

export const ReturnDetailsContainer = () => {
  const [detailsPage, setDetailsPage] = useState<Pages>('return-details')
  const returnDetails = useReturnDetails()

  const { navigate } = useRuntime()

  const handleViewVerifyItems = (page: Pages) => {
    setDetailsPage(page)
  }

  return (
    <Layout
      fullWidth
      pageHeader={
        <PageHeader
          title={
            <FormattedMessage id="admin/return-app.return-request-details.page-header.title" />
          }
          linkLabel={
            <FormattedMessage id="admin/return-app.return-request-details.page-header.link-label" />
          }
          onLinkClick={() => {
            navigate({
              to: '/admin/app/returns/requests',
            })
          }}
        >
          <RequestCancellation />
        </PageHeader>
      }
    >
      <PageBlock variation="full" fit="fill">
        <AdminLoader
          {...returnDetails}
          errorMessages={{
            errorTitle: (
              <FormattedMessage id="admin/return-app.return-request-details.error.title" />
            ),
            errorDescription: (
              <FormattedMessage id="admin/return-app.return-request-details.error.description" />
            ),
          }}
        >
          <>
            {detailsPage !== 'return-details' ? null : (
              <>
                <CurrentRequestStatus />
                <OrderLink />
                <ItemDetailsList />
                <ReturnValues />
                <div className="flex-ns flex-wrap flex-row">
                  <ContactDetails />
                  <PickupAddress />
                </div>
                <RefundMethodDetail />
                <StatusTimeline />
                <UpdateRequestStatus
                  onViewVerifyItems={() =>
                    handleViewVerifyItems('verify-items')
                  }
                />
                <StatusHistory />
              </>
            )}
            {detailsPage !== 'verify-items' ? null : (
              <VerifyItemsPage
                onViewVerifyItems={() =>
                  handleViewVerifyItems('return-details')
                }
              />
            )}
          </>
        </AdminLoader>
      </PageBlock>
    </Layout>
  )
}

```


[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/admin/graphql/updateReturnRequestStatus.gql from the return-app VTEX app.

[Assistant]
Here's the implementation:

```graphql
#import '../../common/graphql/returnDetailsFragment.gql'

mutation updateReturnRequestStatus(
  $requestId: ID!
  $status: Status!
  $comment: ReturnRequestCommentInput
  $refundData: RefundDataInput
) {
  updateReturnRequestStatus(
    requestId: $requestId
    status: $status
    comment: $comment
    refundData: $refundData
  ) @context(provider: "vtex.return-app") {
    ...ReturnDetailsAdminFragment
  }
}

```


[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/admin/hooks/userAlert.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

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

import { AlertContext } from '../provider/AlertProvider'

export const useAlert = () => useContext(AlertContext)

```


[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/admin/hooks/useUpdateRequestStatus.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

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

import { UpdateRequestStatusContext } from '../provider/UpdateRequestStatusProvider'

export const useUpdateRequestStatus = () =>
  useContext(UpdateRequestStatusContext)

```


[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/admin/ReturnList/ReturnListContainer.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { Layout, PageHeader, PageBlock } from 'vtex.styleguide'
import { FormattedMessage } from 'react-intl'

import ListTable from '../../common/components/returnList/ListTable'

export const AdminReturnList = () => {
  return (
    <Layout
      fullWidth
      pageHeader={
        <PageHeader
          title={
            <FormattedMessage id="admin/return-app.return-request-list.page-header.title" />
          }
          subtitle={
            <FormattedMessage id="admin/return-app.return-request-list.page-header.subTitle" />
          }
        />
      }
    >
      <PageBlock variation="full" fit="fill">
        <ListTable />
      </PageBlock>
    </Layout>
  )
}

```


[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/admin/settings/provider/SettingsProvider.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { ApolloError } from 'apollo-client'
import type { FC, Dispatch } from 'react'
import React, { createContext, useReducer, useEffect } from 'react'
import { useQuery, useMutation } from 'react-apollo'
import { FormattedMessage } from 'react-intl'
import type { ReturnAppSettings, ReturnAppSettingsInput } from 'vtex.return-app'

import APP_SETTINGS from '../graphql/getAppSettings.gql'
import SAVE_APP_SETTINGS from '../graphql/saveAppSettings.gql'
import { useAlert } from '../../hooks/userAlert'
import type { Actions } from './settingsReducer'
import { settingsReducer, initialSettingsState } from './settingsReducer'

interface SettingsContextInterface {
  appSettings: ReturnAppSettings
  actions: {
    dispatch: Dispatch<Actions>
    handleSaveAppSettings: () => Promise<void>
  }
  loading: boolean
  error?: ApolloError
  savingAppSettings: boolean
}

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

export const SettingsProvider: FC = ({ children }) => {
  const [appSettings, dispatch] = useReducer(
    settingsReducer,
    initialSettingsState
  )

  const { openAlert } = useAlert()

  const { data, loading, error } = useQuery<{
    returnAppSettings: ReturnAppSettings
  }>(APP_SETTINGS)

  const [saveAppSettings, { loading: savingAppSettings }] = useMutation<
    { saveReturnAppSettings: boolean },
    { settings: ReturnAppSettingsInput }
  >(SAVE_APP_SETTINGS)

  useEffect(() => {
    if (data?.returnAppSettings) {
      dispatch({
        type: 'updateInitialState',
        payload: data.returnAppSettings,
      })
    }
  }, [data])

  const handleSaveAppSettings = async () => {
    try {
      const { paymentOptions } = appSettings

      const { automaticallyRefundPaymentMethod } = paymentOptions

      const adjustedPaymentOptions = paymentOptions.enablePaymentMethodSelection
        ? paymentOptions
        : {
            ...paymentOptions,
            automaticallyRefundPaymentMethod: Boolean(
              automaticallyRefundPaymentMethod
            ),
          }

      const { data: mutationResult, errors } = await saveAppSettings({
        variables: {
          settings: { ...appSettings, paymentOptions: adjustedPaymentOptions },
        },
      })

      if (errors) {
        throw new Error('Error saving app settings')
      }

      if (mutationResult?.saveReturnAppSettings) {
        openAlert(
          'success',
          <FormattedMessage id="admin/return-app.settings.alert.save.success" />
        )
      }
    } catch {
      openAlert(
        'error',
        <FormattedMessage id="admin/return-app.settings.alert.save.error" />
      )
    }
  }

  return (
    <SettingsContext.Provider
      value={{
        appSettings,
        loading,
        error,
        savingAppSettings,
        actions: { dispatch, handleSaveAppSettings },
      }}
    >
      {children}
    </SettingsContext.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/admin/settings/provider/settingsReducer.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type {
  CustomReturnReason,
  PaymentOptions,
  ReturnAppSettings,
  ReturnOption,
} from 'vtex.return-app'

export const initialSettingsState: ReturnAppSettings = {
  maxDays: 0,
  excludedCategories: [],
  termsUrl: '',
  paymentOptions: {
    enablePaymentMethodSelection: false,
    allowedPaymentTypes: {
      bank: false,
      card: false,
      giftCard: false,
    },
  },
  customReturnReasons: [],
  options: {
    enableOtherOptionSelection: false,
    enablePickupPoints: false,
    enableProportionalShippingValue: false,
    enableSelectItemCondition: false,
  },
}

export const maxDaysAction = (maxDays: number) => {
  return {
    type: 'updateMaxDays' as const,
    payload: maxDays,
  }
}

export const excludedCategoriesAction = (excludedCategories: string[]) => {
  return {
    type: 'updateExcludedCategories' as const,
    payload: excludedCategories,
  }
}

export const termsUrlAction = (termsUrl: string) => {
  return {
    type: 'updateTermsUrl' as const,
    payload: termsUrl,
  }
}

export const paymentOptionsAction = (paymentOptions: PaymentOptions) => {
  return {
    type: 'updatePaymentOptions' as const,
    payload: paymentOptions,
  }
}

export const customReturnReasonsAction = (
  customReturnReasons: CustomReturnReason[]
) => {
  return {
    type: 'updateCustomReturnReasons' as const,
    payload: customReturnReasons,
  }
}

export const optionsAction = (options: ReturnOption) => {
  return {
    type: 'updateOptions' as const,
    payload: options,
  }
}

export const initialStateAction = (initialState: ReturnAppSettings) => {
  return {
    type: 'updateInitialState' as const,
    payload: initialState,
  }
}

export type Actions =
  | ReturnType<typeof maxDaysAction>
  | ReturnType<typeof excludedCategoriesAction>
  | ReturnType<typeof termsUrlAction>
  | ReturnType<typeof paymentOptionsAction>
  | ReturnType<typeof customReturnReasonsAction>
  | ReturnType<typeof optionsAction>
  | ReturnType<typeof initialStateAction>

export const settingsReducer = (state: ReturnAppSettings, action: Actions) => {
  switch (action.type) {
    case 'updateMaxDays': {
      return {
        ...state,
        maxDays: action.payload,
      }
    }

    case 'updateExcludedCategories': {
      return {
        ...state,
        excludedCategories: action.payload,
      }
    }

    case 'updateTermsUrl': {
      return {
        ...state,
        termsUrl: action.payload,
      }
    }

    case 'updatePaymentOptions': {
      return {
        ...state,
        paymentOptions: action.payload,
      }
    }

    case 'updateCustomReturnReasons': {
      return {
        ...state,
        customReturnReasons: action.payload,
      }
    }

    case 'updateOptions': {
      return {
        ...state,
        options: action.payload,
      }
    }

    case 'updateInitialState': {
      return action.payload
    }

    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/admin/settings/components/WarningModal.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { ReactElement } from 'react'
import React from 'react'
import { ModalDialog } from 'vtex.styleguide'
import { FormattedMessage } from 'react-intl'

import { useSettings } from '../hooks/useSettings'
import type { ModalWarningState } from '../RMASettings'

interface WarningModalContentProps {
  maxDays: number
  customMaxDays: number
}

interface WarningModalProps {
  setWarning: React.Dispatch<React.SetStateAction<ModalWarningState>>
  customMaxDays: number
}

const StrongChunk = (chunks: ReactElement) => <b>{chunks}</b>

const WarningModalContent = (props: WarningModalContentProps) => {
  const { maxDays, customMaxDays } = props

  return (
    <div>
      <p className="f3 f3-ns fw3 gray">
        <FormattedMessage id="admin/return-app.settings.modal-warning.title" />
      </p>
      <p>
        <FormattedMessage
          id="admin/return-app.settings.modal-warning.first-paragraph"
          values={{
            b: StrongChunk,
            maxDays,
          }}
        />
      </p>
      <p>
        <FormattedMessage id="admin/return-app.settings.modal-warning.second-paragraph" />
      </p>
      <p>
        <FormattedMessage
          id="admin/return-app.settings.modal-warning.third-paragraph"
          values={{
            b: StrongChunk,
            maxDays,
            customMaxDays,
          }}
        />
      </p>
    </div>
  )
}

export const WarningModal = (props: WarningModalProps) => {
  const { customMaxDays, setWarning } = props

  const {
    appSettings,
    actions: { dispatch },
  } = useSettings()

  const handleWarningModal = (overrideAndSave: boolean) => {
    overrideAndSave &&
      dispatch({
        type: 'updateMaxDays',
        payload: customMaxDays,
      })

    setWarning({
      openModal: false,
      customMaxDays: 0,
      attemptNewSave: overrideAndSave,
    })
  }

  return (
    <ModalDialog
      centered
      confirmation={{
        onClick: () => {
          handleWarningModal(true)
        },
        label: (
          <FormattedMessage id="admin/return-app.settings.modal-warning.confirm" />
        ),
        isDangerous: true,
      }}
      cancelation={{
        onClick: () => {
          handleWarningModal(false)
        },
        label: (
          <FormattedMessage id="admin/return-app.settings.modal-warning.cancel" />
        ),
      }}
      isOpen
      onClose={() => {
        handleWarningModal(false)
      }}
    >
      <WarningModalContent
        maxDays={appSettings.maxDays}
        customMaxDays={customMaxDays}
      />
    </ModalDialog>
  )
}

export default WarningModal

```


[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/admin/settings/components/ExcludedCategories.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useMemo } from 'react'
import { useQuery } from 'react-apollo'
import { useIntl, FormattedMessage } from 'react-intl'
import { AutocompleteInput, IconWarning, IconDeny } from 'vtex.styleguide'
import type { CategoryInfo } from 'vtex.return-app'

import GET_CATEGORY_TREE_INFO from '../graphql/getCategoryTreeName.gql'
import { useSettings } from '../hooks/useSettings'

interface FilterSearchCategoriesArgs {
  categoryList?: CategoryInfo[]
  term: string
  excludedCategories: string[]
}

interface LabelFormat {
  /**
   * The category name.
   */
  label: string
  /**
   * The category id.
   */
  value: string
}

const AUTO_COMPLETE_LIST_SIZE = 10

const filterSearchCategories = ({
  categoryList,
  term,
  excludedCategories,
}: FilterSearchCategoriesArgs): LabelFormat[] => {
  if (!categoryList) {
    return []
  }

  const removeExcluded = categoryList.filter(({ id }) => {
    if (!id) return false

    return !excludedCategories.includes(id)
  })

  const formattedLabels = removeExcluded.map(({ id, name }) => {
    return {
      label: `${id} - ${name}`,
      value: id as string,
    }
  })

  return formattedLabels.filter(({ label }) =>
    label.toLowerCase().includes(term.toLowerCase())
  )
}

export const ExcludedCategories = () => {
  const [searchedCategory, setSearchedCategory] = React.useState('')
  const {
    appSettings: { excludedCategories },
    actions: { dispatch },
  } = useSettings()

  const intl = useIntl()
  const { data, loading, error } = useQuery<{
    categoryTreeName: CategoryInfo[]
  }>(GET_CATEGORY_TREE_INFO)

  const categoryNamesMap = useMemo(() => {
    if (!data) {
      return {}
    }

    const { categoryTreeName } = data

    return categoryTreeName.reduce((categoryMap, { id, name }) => {
      if (id) {
        categoryMap[id] = name
      }

      return categoryMap
    }, {})
  }, [data])

  const listOfOptions = filterSearchCategories({
    categoryList: data?.categoryTreeName,
    term: searchedCategory,
    excludedCategories,
  })

  const handleCategorySelection = (e: LabelFormat) => {
    dispatch({
      type: 'updateExcludedCategories',
      payload: [...excludedCategories, e.value],
    })
    setSearchedCategory('')
  }

  const handleDeleteExcludedCategory = (categoryId: string) => {
    dispatch({
      type: 'updateExcludedCategories',
      payload: excludedCategories.filter((id) => id !== categoryId),
    })
  }

  return (
    <div className="flex flex-column mb6">
      <div className="flex flex-column w-100">
        <h3>
          <FormattedMessage id="admin/return-app.settings.excluded-categories.label" />
        </h3>
        <AutocompleteInput
          id="excluded-categories"
          input={{
            placeholder: intl.formatMessage({
              id: 'admin/return-app.settings.search-categories.placeholder',
            }),
            onChange: (term: string) => setSearchedCategory(term),
            onClear: () => setSearchedCategory(''),
            value: searchedCategory,
          }}
          options={{
            onSelect: handleCategorySelection,
            value: !searchedCategory.length
              ? []
              : listOfOptions.slice(0, AUTO_COMPLETE_LIST_SIZE),
            loading:
              loading ||
              (searchedCategory.length > 0 &&
                listOfOptions.length > AUTO_COMPLETE_LIST_SIZE),
            customMessage: !error ? null : (
              <div className="w-100 pa4 f6 br2 br--bottom bg-base flex items-center">
                <div className="ph3 c-danger flex">
                  <IconWarning />
                </div>
                <p className="c-danger">
                  <FormattedMessage id="admin/return-app.settings.section-excluded-categories.fetch-data-error" />
                </p>
              </div>
            ),
          }}
        />
      </div>

      {!excludedCategories.length ? null : (
        <ul>
          {excludedCategories.map((categoryId) => {
            const categoryName = categoryNamesMap[categoryId]

            return (
              <li key={categoryId}>
                <span className="flex items-center">
                  <p>{`${categoryId} - ${categoryName}`}</p>
                  <button
                    className="pointer mh4 bg-transparent c-danger"
                    style={{
                      border: 'none',
                    }}
                    type="button"
                    onClick={() => handleDeleteExcludedCategory(categoryId)}
                  >
                    <IconDeny size={12} />
                  </button>
                </span>
              </li>
            )
          })}
        </ul>
      )}
    </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/admin/settings/components/GeneralOptions.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { ChangeEvent } from 'react'
import React from 'react'
import { defineMessages, FormattedMessage, useIntl } from 'react-intl'
import { Toggle, Divider } from 'vtex.styleguide'

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

const generalOptions = [
  'enableOtherOptionSelection',
  'enablePickupPoints',
  'enableProportionalShippingValue',
  'enableSelectItemCondition',
  'enableHighlightFormMessage',
] as const

const messages = defineMessages({
  'enableOtherOptionSelection-label': {
    id: 'admin/return-app.settings.section.general-options.enable-other-option-selection.label',
  },
  'enableOtherOptionSelection-description': {
    id: 'admin/return-app.settings.section.general-options.enable-other-option-selection.description',
  },
  'enablePickupPoints-label': {
    id: 'admin/return-app.settings.section.general-options.enable-pickup-points.label',
  },
  'enablePickupPoints-description': {
    id: 'admin/return-app.settings.section.general-options.enable-pickup-points.description',
  },
  'enableProportionalShippingValue-label': {
    id: 'admin/return-app.settings.section.general-options.enable-proportional-shipping-value.label',
  },
  'enableProportionalShippingValue-description': {
    id: 'admin/return-app.settings.section.general-options.enable-proportional-shipping-value.description',
  },
  'enableSelectItemCondition-label': {
    id: 'admin/return-app.settings.section.general-options.enable-select-item-condition.label',
  },
  'enableSelectItemCondition-description': {
    id: 'admin/return-app.settings.section.general-options.enable-select-item-condition.description',
  },
  'enableHighlightFormMessage-label': {
    id: 'admin/return-app.settings.section.general-options.enable-highlight-form-message.label',
  },
  'enableHighlightFormMessage-description': {
    id: 'admin/return-app.settings.section.general-options.enable-highlight-form-message.description',
  },
})

export const GeneralOptions = () => {
  const {
    appSettings,
    actions: { dispatch },
  } = useSettings()

  const intl = useIntl()

  const handleToggle = (e: ChangeEvent<HTMLInputElement>) => {
    const { name, checked } = e.target

    const selectedOption = appSettings.options ?? {}
    const updatedSelection = { ...selectedOption, [name]: checked }

    dispatch({ type: 'updateOptions', payload: updatedSelection })
  }

  return (
    <section>
      <h3>
        <FormattedMessage id="admin/return-app.settings.section.general-options.header" />
      </h3>
      <div className="mb4 mh4">
        {generalOptions.map((option, i, self) => {
          return (
            <div className="mt4" key={option}>
              <Toggle
                name={option}
                semantic
                label={intl.formatMessage(messages[`${option}-label`])}
                helpText={intl.formatMessage(messages[`${option}-description`])}
                onChange={handleToggle}
                checked={appSettings.options?.[option]}
              />
              {i === self.length - 1 ? null : (
                <div className="mv4">
                  <Divider />
                </div>
              )}
            </div>
          )
        })}
      </div>
    </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/admin/settings/components/RequiredOptions.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { ChangeEvent } from 'react'
import React from 'react'
import { Input } from 'vtex.styleguide'
import { FormattedMessage } from 'react-intl'

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

export const RequiredOptions = () => {
  const {
    appSettings,
    actions: { dispatch },
  } = useSettings()

  const handleMaxDaysInput = (e: ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target
    const maxDays = Number(value)

    if (Number.isNaN(maxDays) || maxDays < 0) {
      return
    }

    dispatch({ type: 'updateMaxDays', payload: maxDays })
  }

  const handleTermsAndConditionInput = (e: ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target

    dispatch({ type: 'updateTermsUrl', payload: value })
  }

  return (
    <section className="mb6 flex flex-column">
      <div className="flex flex-row">
        <div className="w-50 ph1">
          <Input
            // logic to avoid leading zero to be persistent in the input
            value={appSettings.maxDays === 0 ? '' : appSettings.maxDays}
            type="number"
            size="regular"
            label={
              <FormattedMessage id="admin/return-app.settings.max-days.label" />
            }
            onChange={handleMaxDaysInput}
            errorMessage=""
            required
          />
        </div>
        <div className="w-50 ph1">
          <Input
            value={appSettings.termsUrl}
            type="url"
            size="regular"
            label={
              <FormattedMessage id="admin/return-app.settings.terms.label" />
            }
            onChange={handleTermsAndConditionInput}
            errorMessage=""
            required
          />
        </div>
      </div>
    </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/admin/settings/components/PaymentOptions.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { ChangeEvent, ComponentPropsWithoutRef } from 'react'
import React, { forwardRef } from 'react'
import type { IntlShape } from 'react-intl'
import { defineMessages, FormattedMessage, useIntl } from 'react-intl'
import type { PaymentType } from 'vtex.return-app'
import { Toggle, CheckboxGroup } from 'vtex.styleguide'

import { useSettings } from '../hooks/useSettings'
import type { CheckboxProps } from '../RMASettings'

const messages = defineMessages({
  bank: {
    id: 'admin/return-app.settings.section.payment-options.available-payment-methods.bank',
  },
  card: {
    id: 'admin/return-app.settings.section.payment-options.available-payment-methods.card',
  },
  giftCard: {
    id: 'admin/return-app.settings.section.payment-options.available-payment-methods.gift-card',
  },
})

const createOptionsLabel = (
  paymentsTypeOptions: PaymentType,
  intl: IntlShape
) => {
  if (!paymentsTypeOptions) return null

  const paymentTypes = Object.keys(paymentsTypeOptions)
  const createCheckoutOptions = paymentTypes.reduce(
    (checkoutOptions, paymentType) => {
      // This handles the field __typename that comes from the GraphQL query
      if (!messages[paymentType]) return checkoutOptions

      return {
        ...checkoutOptions,
        [paymentType]: {
          label: intl.formatMessage(messages[paymentType]),
          checked: paymentsTypeOptions[paymentType],
          name: paymentType,
        },
      }
    },
    {} as { string: CheckboxProps }
  )

  return createCheckoutOptions
}

interface PaymentOptionsProps extends ComponentPropsWithoutRef<'div'> {
  handleOptionSelection: (options: { string: CheckboxProps }) => void
  hasError: boolean
}

export const PaymentOptions = forwardRef<HTMLDivElement, PaymentOptionsProps>(
  ({ handleOptionSelection, hasError }, ref) => {
    const {
      appSettings,
      actions: { dispatch },
    } = useSettings()

    const intl = useIntl()

    const optionsLabel = createOptionsLabel(
      appSettings?.paymentOptions?.allowedPaymentTypes,
      intl
    )

    const handleEnablePaymentMethodSelection = (
      e: ChangeEvent<HTMLInputElement>
    ) => {
      const { checked } = e.target

      dispatch({
        type: 'updatePaymentOptions',
        payload: {
          ...appSettings?.paymentOptions,
          enablePaymentMethodSelection: checked,
          allowedPaymentTypes: appSettings.paymentOptions.allowedPaymentTypes,
          // Always return to the default state when use checks / unchecks the checkbox. This way we avaiod a confusing state where buttons is disable but set to on.
          automaticallyRefundPaymentMethod: false,
        },
      })
    }

    const handleAutomaticallyRefundOption = (
      e: ChangeEvent<HTMLInputElement>
    ) => {
      const { checked } = e.target

      dispatch({
        type: 'updatePaymentOptions',
        payload: {
          ...appSettings?.paymentOptions,
          automaticallyRefundPaymentMethod: checked,
        },
      })
    }

    const { enablePaymentMethodSelection, automaticallyRefundPaymentMethod } =
      appSettings.paymentOptions ?? {}

    return (
      <section>
        <h3>
          <FormattedMessage id="admin/return-app.settings.section.return-payment-options.header" />
        </h3>
        <div className="mb4 mh4">
          <div className="mb4">
            <Toggle
              label={
                enablePaymentMethodSelection ? (
                  <FormattedMessage id="admin/return-app.settings.section.payment-options.enable-payment-method-selection.label.check" />
                ) : (
                  <FormattedMessage id="admin/return-app.settings.section.payment-options.enable-payment-method-selection.label.uncheck" />
                )
              }
              checked={enablePaymentMethodSelection}
              semantic
              onChange={handleEnablePaymentMethodSelection}
              helpText={
                <FormattedMessage id="admin/return-app.settings.section.payment-options.enable-payment-method-selection.description" />
              }
            />
          </div>
          <div className="mb4">
            <Toggle
              label={
                <FormattedMessage id="admin/return-app.settings.section.payment-options.refund-method-strategy.checkbox.label" />
              }
              checked={automaticallyRefundPaymentMethod}
              semantic
              helpText={
                <FormattedMessage id="admin/return-app.settings.section.payment-options.refund-method-strategy.checkbox.description" />
              }
              onChange={handleAutomaticallyRefundOption}
              disabled={enablePaymentMethodSelection}
            />
          </div>
          {enablePaymentMethodSelection && optionsLabel ? (
            <div ref={ref}>
              <h4>
                <FormattedMessage id="admin/return-app.settings.section.payment-options.available-payment-methods.header" />
              </h4>
              <CheckboxGroup
                name="paymentMethods"
                label={
                  <FormattedMessage id="admin/return-app.settings.section.payment-options.available-payment-methods.label" />
                }
                checkedMap={optionsLabel}
                onGroupChange={handleOptionSelection}
              />
              {!hasError ? null : (
                <p className="c-danger i t-small mt3 lh-title">
                  <FormattedMessage id="admin/return-app.settings.section.payment-options.enable-payment-method-selection.error" />
                </p>
              )}
            </div>
          ) : null}
        </div>
      </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/admin/settings/graphql/getCategoryTreeName.gql from the return-app VTEX app.

[Assistant]
Here's the implementation:

```graphql
query categoryTreeName {
  categoryTreeName @context(provider: "vtex.return-app") {
    id
    name
  }
}

```


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

[User] Show me the implementation of return-app/react/admin/settings/graphql/getAppSettings.gql from the return-app VTEX app.

[Assistant]
Here's the implementation:

```graphql
query returnAppSettings {
  returnAppSettings @context(provider: "vtex.return-app") {
    maxDays
    excludedCategories
    paymentOptions {
      enablePaymentMethodSelection
      allowedPaymentTypes {
        bank
        card
        giftCard
      }
      automaticallyRefundPaymentMethod
    }
    termsUrl
    customReturnReasons {
      reason
      maxDays
      translations {
        locale
        translation
      }
    }
    options {
      enableOtherOptionSelection
      enablePickupPoints
      enableProportionalShippingValue
      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/admin/settings/graphql/saveAppSettings.gql from the return-app VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation saveAppSettings($settings: ReturnAppSettingsInput!) {
  saveReturnAppSettings(settings: $settings)
    @context(provider: "vtex.return-app")
}

```


[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/admin/settings/hooks/useSettings.ts from the return-app VTEX app.

[Assistant]
Here's the implementation:

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

import { SettingsContext } from '../provider/SettingsProvider'

export const useSettings = () => useContext(SettingsContext)

```


[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/admin/settings/components/CustomReasons/CustomReasons.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { ReactElement } from 'react'
import React, { useState } from 'react'
import { FormattedMessage } from 'react-intl'
import type { CustomReturnReason } from 'vtex.return-app'
import {
  ButtonWithIcon,
  IconPlusLines,
  Table,
  ModalDialog,
} from 'vtex.styleguide'

import { useSettings } from '../../hooks/useSettings'
import { CustomReasonModal } from './CustomReasonModal'
import { TranslationsModal } from './TranslationsModal'

const addIndexToCustomReason = (
  customReturnReasons: CustomReturnReason[] | undefined | null
) =>
  customReturnReasons?.map((reason, i) => ({
    ...reason,
    index: i,
  })) ?? []

const tableSchema = {
  properties: {
    reason: {
      title: (
        <FormattedMessage id="admin/return-app.settings.section.custom-reasons.table.header.reason" />
      ),
    },
    maxDays: {
      title: (
        <FormattedMessage id="admin/return-app.settings.section.custom-reasons.table.header.max-days" />
      ),
    },
  },
}

interface LineActionsArgs {
  handleDeleteCustomReason: (reason: number) => void
  handleEditCustomReason: (customReason: CustomReasonWithIndex) => void
  handleOpenTranslations: (customReason: CustomReasonWithIndex) => void
}

export type CustomReasonWithIndex = ReturnType<
  typeof addIndexToCustomReason
>[number]

interface RowData {
  rowData: CustomReasonWithIndex
}

const lineActions = ({
  handleDeleteCustomReason,
  handleEditCustomReason,
  handleOpenTranslations,
}: LineActionsArgs) => {
  return [
    {
      label: () => 'Edit',
      onClick: ({ rowData }: RowData) => {
        handleEditCustomReason(rowData)
      },
    },
    {
      label: () => 'Delete',
      isDangerous: true,
      onClick: ({ rowData }: RowData) => {
        handleDeleteCustomReason(rowData.index)
      },
    },
    {
      label: () => 'Translations',
      onClick: ({ rowData }: RowData) => {
        handleOpenTranslations(rowData)
      },
    },
  ]
}

export const CustomReasons = () => {
  const [modalOpen, setModalOpen] = useState<
    'add' | 'edit' | 'translations' | ''
  >('')

  const [indexToDelete, setIndexToDelete] = useState<number | null>(null)
  const [customReasonToEdit, setCustomReasonToEdit] =
    useState<CustomReasonWithIndex | null>(null)

  const {
    appSettings: { customReturnReasons },
    actions: { dispatch },
  } = useSettings()

  const handleDeleteCustomReason = (reasonIndex: number) => {
    setIndexToDelete(reasonIndex)
  }

  const handleEditCustomReason = (customReason: CustomReasonWithIndex) => {
    setCustomReasonToEdit(customReason)
    setModalOpen('edit')
  }

  const handleOpenTranslations = (customReason: CustomReasonWithIndex) => {
    setCustomReasonToEdit(customReason)
    setModalOpen('translations')
  }

  const handleStateCleanup = () => {
    setCustomReasonToEdit(null)
    setModalOpen('')
  }

  const confirmDelete = () => {
    const newCustomReturnReasons = customReturnReasons?.filter(
      (_, i) => i !== indexToDelete
    )

    setIndexToDelete(null)

    dispatch({
      type: 'updateCustomReturnReasons',
      payload: newCustomReturnReasons ?? [],
    })
  }

  return (
    <section>
      <div className="flex items-end justify-between">
        <h3>
          <FormattedMessage id="admin/return-app.settings.section.custom-return-reasons.header" />
        </h3>
        <span>
          <ButtonWithIcon
            onClick={() => setModalOpen('add')}
            icon={<IconPlusLines />}
          >
            <FormattedMessage id="admin/return-app.settings.section.custom-reasons.add.button" />
          </ButtonWithIcon>
        </span>
      </div>
      <div>
        <Table
          fullWidth
          schema={tableSchema}
          // Add index to custom reasons so it can be used on edit and delete operations
          items={addIndexToCustomReason(customReturnReasons)}
          lineActions={lineActions({
            handleDeleteCustomReason,
            handleEditCustomReason,
            handleOpenTranslations,
          })}
          emptyStateLabel={
            <FormattedMessage id="admin/return-app.settings.section.custom-reasons.empty-custom-reasons" />
          }
          emptyStateChildren={
            <>
              <p>
                <FormattedMessage id="admin/return-app.settings.section.custom-reasons.empty-custom-reasons.how-to" />
              </p>
              <p>
                <FormattedMessage id="admin/return-app.settings.section.custom-reasons.empty-custom-reasons.reasons.disclaimer" />
              </p>
            </>
          }
        />
      </div>
      <CustomReasonModal
        isOpen={modalOpen === 'add' || modalOpen === 'edit'}
        modalOpen={modalOpen}
        onClose={handleStateCleanup}
        customReasonOnFocus={customReasonToEdit}
      />
      {/* Modal to confirm delete operation. It has to check === null because indexToDelete can be zero */}
      {indexToDelete === null ? null : (
        <ModalDialog
          centered
          isOpen={indexToDelete !== null}
          onClose={() => setIndexToDelete(null)}
          confirmation={{
            label: (
              <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.delete.custom-reason.confirm" />
            ),
            onClick: confirmDelete,
            isDangerous: true,
          }}
          cancelation={{
            label: (
              <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.delete.custom-reason.cancel" />
            ),
            onClick: () => setIndexToDelete(null),
          }}
        >
          <p className="f3 fw3 f3-ns">
            <FormattedMessage
              id="admin/return-app.settings.section.custom-reasons.modal.delete.custom-reason.message"
              values={{
                reason: customReturnReasons?.[indexToDelete]?.reason,
                // eslint-disable-next-line react/display-name
                b: (chunks: ReactElement) => <b>{chunks}</b>,
              }}
            />
          </p>
        </ModalDialog>
      )}
      <TranslationsModal
        customReasonOnFocus={customReasonToEdit}
        isOpen={modalOpen === 'translations'}
        onClose={handleStateCleanup}
      />
    </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/admin/settings/components/CustomReasons/CustomReasonModal.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { ChangeEvent, FormEvent } from 'react'
import React, { useState, useEffect } from 'react'
import { FormattedMessage, useIntl } from 'react-intl'
import type { CustomReturnReason } from 'vtex.return-app'
import { Modal, Input, Button } from 'vtex.styleguide'

import { useSettings } from '../../hooks/useSettings'
import type { CustomReasonWithIndex } from './CustomReasons'

interface CustomReasonModalProps {
  isOpen: boolean
  modalOpen: 'add' | 'edit' | 'translations' | ''
  onClose: () => void
  customReasonOnFocus: CustomReasonWithIndex | null
}

export const CustomReasonModal = ({
  isOpen,
  modalOpen,
  onClose,
  customReasonOnFocus,
}: CustomReasonModalProps) => {
  const {
    appSettings: { maxDays, customReturnReasons },
    actions: { dispatch },
  } = useSettings()

  const [tempReason, setTempReason] = useState<CustomReturnReason>(
    {} as CustomReturnReason
  )

  const intl = useIntl()

  useEffect(() => {
    if (customReasonOnFocus && modalOpen === 'edit') {
      // customReasonOnFocus has index property, not accepted by Graphql.
      setTempReason({
        reason: customReasonOnFocus.reason,
        maxDays: customReasonOnFocus.maxDays,
        translations: customReasonOnFocus.translations,
      })
    }
  }, [modalOpen, customReasonOnFocus])

  const handleTempReasonChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { value, name } = e.target

    setTempReason({
      ...tempReason,
      [name]: name === 'maxDays' ? Number(value) : value,
    })
  }

  const handleCloseModal = () => {
    setTempReason({} as CustomReturnReason)
    onClose()
  }

  const handleAddNewReason = (e: FormEvent) => {
    e.preventDefault()
    e.stopPropagation()

    let payload: CustomReturnReason[]

    if (modalOpen === 'edit' && customReasonOnFocus) {
      payload =
        customReturnReasons?.map((reason, i) => {
          if (i === customReasonOnFocus.index) {
            return tempReason
          }

          return reason
        }) ?? []
    } else {
      // Adding new one
      payload = customReturnReasons
        ? [...customReturnReasons, tempReason]
        : [tempReason]
    }

    dispatch({
      type: 'updateCustomReturnReasons',
      payload,
    })
    handleCloseModal()
  }

  return (
    <Modal isOpen={isOpen} onClose={handleCloseModal}>
      <div className="flex flex-column">
        <div className="w-100">
          <h4 className="f3 fw3 gray mt6 mb2">
            <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.custom-reason.header" />
          </h4>
        </div>
        <div className="w-100 mv4">
          <form
            onSubmit={handleAddNewReason}
            className="flex flex-column items-baseline"
          >
            <div className="w-100 mv3">
              <Input
                placeholder={intl.formatMessage({
                  id: 'admin/return-app.settings.section.custom-reasons.modal.custom-reason.placeholder',
                })}
                label={intl.formatMessage({
                  id: 'admin/return-app.settings.section.custom-reasons.modal.custom-reason.label',
                })}
                name="reason"
                size="large"
                required
                value={tempReason.reason ?? ''}
                onChange={handleTempReasonChange}
              />
            </div>
            <div className="w-100 mt3 mb6">
              <Input
                placeholder={intl.formatMessage({
                  id: 'admin/return-app.settings.section.custom-reasons.modal.custom-reason.max-days.placeholder',
                })}
                label={intl.formatMessage({
                  id: 'admin/return-app.settings.section.custom-reasons.modal.custom-reason.max-days.label',
                })}
                name="maxDays"
                size="large"
                type="number"
                min="1"
                max={maxDays}
                required
                value={tempReason.maxDays ?? ''}
                onChange={handleTempReasonChange}
              />
            </div>
            <Button type="submit">
              {modalOpen === 'edit' ? (
                <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.custom-reason.edit.button" />
              ) : null}
              {modalOpen === 'add' ? (
                <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.custom-reason.add-new.button" />
              ) : null}
            </Button>
          </form>
        </div>
      </div>
    </Modal>
  )
}

```


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

[User] Show me the implementation of return-app/react/admin/settings/components/CustomReasons/TranslationsModal.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { ChangeEvent, ReactElement } from 'react'
import React, { useEffect, useState } from 'react'
import { useQuery } from 'react-apollo'
import type { Tenant, Binding } from 'vtex.tenant-graphql'
import { ModalDialog, Table, Input, Spinner, EmptyState } from 'vtex.styleguide'
import type { CustomReturnReasonTranslation } from 'vtex.return-app'
import { FormattedMessage } from 'react-intl'

import TENANT_INFO from './graphql/tenant.gql'
import type { CustomReasonWithIndex } from './CustomReasons'
import { useSettings } from '../../hooks/useSettings'

const localesAvailable = (bindings: Binding[]): string[] => {
  const storefrontBindings = bindings.filter(
    (binding) => binding.targetProduct === 'vtex-storefront'
  )

  const localesMap = new Map()

  for (const binding of storefrontBindings) {
    const { defaultLocale, supportedLocales } = binding

    if (!localesMap.has(defaultLocale)) {
      localesMap.set(defaultLocale, true)
    }

    for (const locale of supportedLocales) {
      if (locale && !localesMap.has(locale)) {
        localesMap.set(locale, true)
      }
    }
  }

  return Array.from(localesMap.keys())
}

const createTranslationOptions = (
  availableLocales: string[],
  translation?: CustomReturnReasonTranslation[] | null
): CustomReturnReasonTranslation[] => {
  return availableLocales.map((availableLocale) => {
    const currentTranslation = translation?.find(
      ({ locale }) => locale === availableLocale
    )

    return currentTranslation ?? { locale: availableLocale, translation: '' }
  })
}

const tableSchema = (
  handleTranslationInput: (e: ChangeEvent<HTMLInputElement>) => void
) => ({
  properties: {
    locale: {
      title: (
        <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.translations.table.header.custom-reason-translation.locale" />
      ),
    },
    translation: {
      title: (
        <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.translations.table.header.custom-reason-translation.translation" />
      ),
      // eslint-disable-next-line react/display-name
      cellRenderer: ({
        rowData,
      }: {
        rowData: CustomReturnReasonTranslation
      }) => {
        const { translation, locale } = rowData

        return (
          <Input
            size="small"
            value={translation}
            name={locale}
            onChange={handleTranslationInput}
          />
        )
      },
    },
  },
})

interface TranslationsModalProps {
  isOpen: boolean
  onClose: () => void
  customReasonOnFocus: CustomReasonWithIndex | null
}

export const TranslationsModal = ({
  customReasonOnFocus,
  isOpen,
  onClose,
}: TranslationsModalProps) => {
  const [tempTranslations, setTempTranslations] = useState<
    CustomReturnReasonTranslation[]
  >([])

  const {
    appSettings: { customReturnReasons },
    actions: { dispatch },
  } = useSettings()

  const { data, loading, error } = useQuery<{ tenantInfo: Tenant }>(TENANT_INFO)

  useEffect(() => {
    if (customReasonOnFocus?.translations) {
      setTempTranslations(customReasonOnFocus.translations)
    }
  }, [customReasonOnFocus])

  const handleTranslationInput = (e: ChangeEvent<HTMLInputElement>) => {
    const { value, name } = e.target
    const hasLocale = tempTranslations.find(
      (translation) => translation.locale === name
    )

    if (hasLocale) {
      const newTranslations = tempTranslations.map((translation) => {
        if (translation.locale === name) {
          return { ...translation, translation: value }
        }

        return translation
      })

      setTempTranslations(newTranslations)

      return
    }

    const newTranslations = [
      ...tempTranslations,
      { locale: name, translation: value },
    ]

    setTempTranslations(newTranslations)
  }

  const handleCloseModal = () => {
    setTempTranslations([])
    onClose()
  }

  const handleConfirmation = () => {
    const updatedCustomReturnReasons = customReturnReasons?.map(
      (customReason, i) => {
        if (i === customReasonOnFocus?.index) {
          // filters our the ones where the translation is empty to avoid rendering an empty string to final user
          const translations = tempTranslations.filter(({ translation }) =>
            Boolean(translation)
          )

          return {
            ...customReason,
            translations,
          }
        }

        return customReason
      }
    )

    if (updatedCustomReturnReasons) {
      dispatch({
        type: 'updateCustomReturnReasons',
        payload: updatedCustomReturnReasons,
      })
    }

    handleCloseModal()
  }

  const availableLocales = localesAvailable(data?.tenantInfo?.bindings ?? [])

  return (
    <ModalDialog
      centered
      isOpen={isOpen}
      onClose={handleCloseModal}
      confirmation={{
        label: (
          <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.translations.confirm" />
        ),
        onClick: handleConfirmation,
      }}
      cancelation={{
        label: (
          <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.translations.cancel" />
        ),
        onClick: handleCloseModal,
      }}
    >
      <div>
        <div>
          <h4 className="f3 fw3 gray mt6 mb2">
            <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.translations.header.custom-reason-translation" />
          </h4>
          <p>
            <FormattedMessage
              id="admin/return-app.settings.section.custom-reasons.modal.translations.sub-header.custom-reason-translation"
              values={{
                reason: customReasonOnFocus?.reason,
                // eslint-disable-next-line react/display-name
                b: (chunks: ReactElement) => <b>{chunks}</b>,
              }}
            />
          </p>
        </div>
        {error ? (
          <EmptyState
            title={
              <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.translations.error.header" />
            }
          >
            <p>
              <FormattedMessage id="admin/return-app.settings.section.custom-reasons.modal.translations.error.description" />
            </p>
          </EmptyState>
        ) : loading ? (
          <Spinner />
        ) : (
          <div>
            <Table
              schema={tableSchema(handleTranslationInput)}
              items={createTranslationOptions(
                availableLocales,
                tempTranslations
              )}
              fullWidth
            />
          </div>
        )}
      </div>
    </ModalDialog>
  )
}

```


[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/admin/settings/components/CustomReasons/graphql/tenant.gql from the return-app VTEX app.

[Assistant]
Here's the implementation:

```graphql
query tenantInfo {
  tenantInfo @context(provider: "vtex.tenant-graphql") {
    bindings {
      defaultLocale
      supportedLocales
      targetProduct
    }
  }
}

```


[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/admin/ReturnDetails/components/UpdateRequestStatus.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FormEvent, ChangeEvent } from 'react'
import React, { useState } from 'react'
import type { IntlFormatters } from 'react-intl'
import { FormattedMessage, useIntl } from 'react-intl'
import {
  Dropdown,
  Textarea,
  Checkbox,
  Button,
  Tooltip,
  IconInfo,
} from 'vtex.styleguide'
import type { Status } from 'vtex.return-app'

import { useReturnDetails } from '../../../common/hooks/useReturnDetails'
import {
  statusAllowed,
  statusMessageIdAdmin,
} from '../../../utils/requestStatus'
import { useUpdateRequestStatus } from '../../hooks/useUpdateRequestStatus'

const createStatusOptions = (
  currentStatus: Status,
  formatMessage: IntlFormatters['formatMessage']
): Array<{ value: string; label: string }> => {
  const allowedStatus = statusAllowed[currentStatus]

  return allowedStatus.map((status) => ({
    value: status,
    label: formatMessage(statusMessageIdAdmin[status]),
  }))
}

interface Props {
  onViewVerifyItems: () => void
}

export const UpdateRequestStatus = ({ onViewVerifyItems }: Props) => {
  const [selectedStatus, setSelectedStatus] = useState<Status | ''>('')
  const [comment, setComment] = useState('')
  const [visibleForCustomer, setVisibleForCustomer] = useState(false)
  const { formatMessage } = useIntl()
  const { data } = useReturnDetails()
  const { submitting, handleStatusUpdate } = useUpdateRequestStatus()

  const cleanUp = () => {
    setComment('')
    setVisibleForCustomer(false)
  }

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (submitting || selectedStatus === '' || !data?.returnRequestDetails) {
      return
    }

    const newComment = !comment
      ? undefined
      : {
          value: comment,
          visibleForCustomer,
        }

    handleStatusUpdate({
      id: data.returnRequestDetails?.id,
      status: selectedStatus,
      comment: newComment,
      cleanUp,
    })
  }

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

    setSelectedStatus(value as Status)
  }

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

    setComment(value)
  }

  const handleVisibleToCustomerChange = (
    event: ChangeEvent<HTMLInputElement>
  ) => {
    const { checked } = event.target

    setVisibleForCustomer(checked)
  }

  const updateStatus =
    selectedStatus && selectedStatus !== data?.returnRequestDetails.status

  if (!data) return null

  return (
    <section className="mv4">
      <div className="flex items-center">
        <h3>
          <FormattedMessage id="admin/return-app.return-request-details.update-status.title" />
        </h3>
        <Tooltip
          label={
            <FormattedMessage id="admin/return-app.return-request-details.update-status.tooltip" />
          }
        >
          <span className="yellow pointer ml3 flex">
            <IconInfo />
          </span>
        </Tooltip>
      </div>
      <form
        className="flex flex-column items-stretch w-50"
        onSubmit={handleSubmit}
      >
        <div className="mb6">
          <FormattedMessage id="admin/return-app.return-request-details.update-status.dropdown.placeholder">
            {(placeholder) => (
              <Dropdown
                size="small"
                placeholder={placeholder}
                options={createStatusOptions(
                  data.returnRequestDetails.status,
                  formatMessage
                )}
                value={selectedStatus}
                onChange={handleStatusChange}
              />
            )}
          </FormattedMessage>
        </div>
        <div className="mb6">
          <Textarea
            label={
              <FormattedMessage id="admin/return-app.return-request-details.update-status.textarea.label" />
            }
            value={comment}
            onChange={handleCommentsChange}
          />
        </div>
        <div className="mb6">
          <Checkbox
            checked={visibleForCustomer}
            label={
              <FormattedMessage id="admin/return-app.return-request-details.update-status.checkbox.label" />
            }
            onChange={handleVisibleToCustomerChange}
          />
        </div>
        <div className="mb6">
          <Button
            type="submit"
            variation="primary"
            size="small"
            disabled={
              !selectedStatus ||
              (selectedStatus === data.returnRequestDetails.status && !comment)
            }
            isLoading={submitting}
          >
            {updateStatus ? (
              <FormattedMessage id="admin/return-app.return-request-details.update-status.button.update-status" />
            ) : (
              <FormattedMessage id="admin/return-app.return-request-details.update-status.button.comment" />
            )}
          </Button>
          {data.returnRequestDetails.status === 'pendingVerification' ? (
            <span className="ml4">
              <Button type="button" onClick={onViewVerifyItems} size="small">
                <FormattedMessage id="admin/return-app.return-request-details.verify-items.button" />
              </Button>
            </span>
          ) : null}
        </div>
      </form>
    </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/admin/ReturnDetails/components/AlignItemRight.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

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

export const AlignItemRight: FC = ({ children }) => (
  <span className="flex justify-end w-100">{children}</span>
)

```


[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/admin/ReturnDetails/components/VerifyItems/VerifyTotalsTable.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { Table } from 'vtex.styleguide'

import { verifyTotalsTableSchema } from './verifyTotalsTableSchema'
import type { UpdateRefundShipping } from './VerifyItemsPage'
import { useReturnDetails } from '../../../../common/hooks/useReturnDetails'

interface Props {
  refundableShipping: number
  shippingToRefund: number
  totalRefundItems: number
  onRefundShippingChange: UpdateRefundShipping
}

export const VerifyTotalsTable = ({
  refundableShipping,
  shippingToRefund,
  totalRefundItems,
  onRefundShippingChange,
}: Props) => {
  const { data } = useReturnDetails()

  if (!data) return null

  const { cultureInfoData } = data.returnRequestDetails

  return (
    <div>
      <h3>
        <FormattedMessage id="admin/return-app.return-request-details.verify-items.table.title.totals" />
      </h3>
      <Table
        fullWidth
        schema={verifyTotalsTableSchema(
          onRefundShippingChange,
          cultureInfoData
        )}
        items={[
          {
            refundableShipping,
            shippingToRefund,
            totalRefundItems,
            totalRefund: shippingToRefund + totalRefundItems,
          },
        ]}
      />
    </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/admin/ReturnDetails/components/VerifyItems/ProductActionStatus.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

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

type ActionStatus = 'deny' | 'approve' | 'partially-approve'

const getActionStatus = ({
  quantity,
  selectedQuantity,
}: {
  quantity: number
  selectedQuantity: number
}): ActionStatus =>
  selectedQuantity === 0
    ? 'deny'
    : selectedQuantity === quantity
    ? 'approve'
    : 'partially-approve'

export const ProductActionStatus = ({
  quantity,
  selectedQuantity,
}: {
  quantity: number
  selectedQuantity: number
}) => {
  const actionStatus = getActionStatus({ quantity, selectedQuantity })

  return (
    <>
      {actionStatus !== 'approve' ? null : (
        <div className="c-success flex items-center">
          <span className="mr2 flex">
            <IconSuccess size={14} />
          </span>
          <FormattedMessage id="admin/return-app.return-request-details.verify-items.action.approve" />
        </div>
      )}
      {actionStatus !== 'deny' ? null : (
        <div className="c-danger flex items-center">
          <span className="mr2 flex">
            <IconFailure size={14} />
          </span>
          <FormattedMessage id="admin/return-app.return-request-details.verify-items.action.deny" />
        </div>
      )}
      {actionStatus !== 'partially-approve' ? null : (
        <div className="c-warning flex items-center">
          <span className="mr2 flex">
            <IconWarning size={14} />
          </span>
          <FormattedMessage id="admin/return-app.return-request-details.verify-items.action.partially-approve" />
        </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/admin/ReturnDetails/components/VerifyItems/verifyItemsTableSchema.tsx from the return-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { ChangeEvent } from 'react'
import React from 'react'
import { FormattedMessage, FormattedNumber } from 'react-intl'
import type { ReturnRequestItem, CultureInfoData } from 'vtex.return-app'
import { NumericStepper, InputCurrency } from 'vtex.styleguide'

import type { RefundItemMap, UpdateItemsChange } from './VerifyItemsPage'
import { AlignItemRight } from '../AlignItemRight'
import { ProductActionStatus } from './ProductActionStatus'

export const verifyItemsTableSchema = (
  refundItemMap: RefundItemMap,
  updateChanges: UpdateItemsChange,
  cultureInfoData: CultureInfoData
) => ({
  properties: {
    name: {
      title: (
        <FormattedMessage id="admin/return-app.return-request-details.verify-items.table.header.product" />
      ),
      minWidth: 320,
    },
    sellingPrice: {
      title: (
        <FormattedMessage id="admin/return-app.return-request-details.verify-items.table.header.price" />
      ),
      width: 90,
      headerRight: true,
      cellRenderer: function SellingPriceHeader({
        cellData,
      }: {
        rowData: ReturnRequestItem
        cellData: ReturnRequestItem['sellingPrice']
      }) {
        return (
          <AlignItemRight>
            <FormattedNumber
              value={cellData / 100}
              style="currency"
              currency={cultureInfoData.currencyCode}
            />
          </AlignItemRight>
        )
      },
    },
    tax: {
      title: (
        <FormattedMessage id="admin/return-app.return-request-details.verify-items.table.header.tax" />
      ),
      width: 90,
      headerRight: true,
      cellRenderer: function TaxHeader({
        cellData,
      }: {
        rowData: ReturnRequestItem
        cellData: ReturnRequestItem['tax']
      }) {
        return (
          <AlignItemRight>
            <FormattedNumber
              value={cellData / 100}
              style="currency"
              currency={cultureInfoData.currencyCode}
            />
          </AlignItemRight>
        )
      },
    },
    totalPrice: {
      title: (
        <FormattedMessage id="admin/return-app.return-request-details.verify-items.table.header.total" />
      ),
      width: 90,
      headerRight: true,
      cellRenderer: function TotalPriceHeader({
        rowData,
      }: {
        rowData: ReturnRequestItem
      }) {
        const { sellingPrice, tax } = rowData

        return (
          <AlignItemRight>
            <FormattedNumber
              value={(sellingPrice + tax) / 100}
              style="currency"
              currency={cultureInfoData.currencyCode}
            />
          </AlignItemRight>
        )
      },
    },
    quantity: {
      title: (
        <FormattedMessage id="admin/return-app.return-request-details.verify-items.table.header.quantity" />
      ),
      width: 80,
      cellRenderer: function QuantityHeader({
        cellData,
      }: {
        rowData: ReturnRequestItem
        cellData: ReturnRequestItem['quantity']
      }) {
        return <span className="w-100 flex justify-center">{cellData}</span>
      },
    },
    verified: {
      title: (
        <FormattedMessage id="admin/return-app.return-request-details.verify-items.table.header.verified" />
      ),
      width: 160,
      cellRenderer: function VerifiedPQuantityHeader({
        rowData,
      }: {
        rowData: ReturnRequestItem
      }) {
        const { orderItemIndex, quantity } = rowData

        const handleChange = ({ value }: { value: number }) => {
          updateChanges({ quantity: value, orderItemIndex })
        }

        const selectedQuantity =
          refundItemMap.get(orderItemIndex)?.quantity ?? 0

        return (
          <NumericStepper
            value={selectedQuantity}
            maxValue={quantity}
            onChange={handleChange}
          />
        )
      },
    },
    restockFee: {
      title: (
        <FormattedMessage id="admin/return-app.return-request-details.verify-items.table.header.restock-fee" />
      ),
      width: 150,
      cellRenderer: function RestockFeeHeader({
        rowData,
      }: {
        rowData: ReturnRequestItem
      }) {
        const { sellingPrice, tax, orderItemIndex } = rowData

        const refundItem = refundItemMap.get(orderItemIndex)
        const restockFee = refundItem?.restockFee ?? 0
        const selectedQuantity = refundItem?.quantity ?? 0

        const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
          const { value } = event.target
          const restockFeeInput = Number(value)

          const restockFeeInputParsed = Number.isNaN(restockFeeInput)
            ? 0
            : restockFeeInput

          const restockFeeCents = parseFloat(
            (restockFeeInputParsed * 100).toFixed(0)
          )

          const maxRestockFee = (sellingPrice + tax) * selectedQuantity

          const restockFeeChecked =
            restockFeeCents > maxRestockFee ? maxRestockFee : restockFeeCents

          updateChanges({ restockFee: restockFeeChecked, orderItemIndex })
        }

        return (
          <InputCurrency
            value={restockFee / 100}
            currencyCode={cultureInfoData.currencyCode}
            locale={cultureInfoData.locale}
            onChange={handleChange}
            readOnly={selectedQuantity === 0}
          />
        )
      },
    },
    totalRefund: {
      title: (
        <FormattedMessage id="admin/return-app.return-request-details.verify-items.table.header.refund-product-total" />
      ),
      headerRight: true,
      width: 90,
      cellRenderer: function TotalProductRefundHeader({
        rowData,
      }: {
        rowData: ReturnRequestItem
      }) {
        const { sellingPrice, tax, orderItemIndex } = rowData

        const refundItem = refundItemMap.get(orderItemIndex)
        const selectedQuantity = refundItem?.quantity ?? 0
        const restockFee = refundItem?.restockFee ?? 0

        return (
          <AlignItemRight>
            <FormattedNumber
              value={
                ((sellingPrice + tax) * selectedQuantity - restockFee) / 100
              }
              style="currency"
              currency={cultureInfoData.currencyCode}
            />
          </AlignItemRight>
        )
      },
    },
    action: {
      title: (
        <FormattedMessage id="admin/return-app.return-request-details.verify-items.table.header.action" />
      ),
      cellRenderer: function VerifyActionHeader({
        rowData,
      }: {
        rowData: ReturnRequestItem
      }) {
        const { quantity, orderItemIndex } = rowData

        const selectedQuantity =
          refundItemMap.get(orderItemIndex)?.quantity ?? 0

        return (
          <ProductActionStatus
            quantity={quantity}
            selectedQuantity={selectedQuantity}
          />
        )
      },
    },
  },
})

```