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

[Assistant]
Here's the implementation:

```markdown
# VTEX Telemarketing

## Description

The VTEX Telemarketing app is a store component that enables a call center operator impersonate a costumer in the store, and this app is used by store theme.

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

## Release schedule

| Release |       Status        | Initial Release | Maintenance LTS Start | End-of-life | Store Compatibility |
| :-----: | :-----------------: | :-------------: | :-------------------: | :---------: | :-----------------: |
|  [2.x]  | **Current Release** |   2018-11-08    |                       |             |         2.x         |
|  [1.x]  | **Maintenance LTS** |   2018-08-15    |      2018-11-08       | March 2019  |         1.x         |

See our [LTS policy](https://github.com/vtex-apps/awesome-io#lts-policy) for more information.

## Table of Contents

- [Usage](#usage)
  - [Blocks API](#blocks-api)
    - [Configuration](#configuration)
  - [Styles API](#styles-api)
    - [CSS namespaces](#css-namespaces)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [Tests](#tests)

## Usage

This app uses our store builder with the blocks architecture. To know more about the Store Builder [click here](https://help.vtex.com/en/tutorial/understanding-storebuilder-and-stylesbuilder#structuring-and-configuring-our-store-with-object-object).

We add the telemarketing as a block in our [Store Header](https://github.com/vtex-apps/store-header/blob/master/store/interfaces.json).

To configure or customize this app, you need to import it in your dependencies in `manifest.json`.

```json
  dependencies: {
    "vtex.telemarketing": "2.x"
  }
```

Then, add `telemarketing` block into your app theme as we do in our [Store theme app](https://github.com/vtex-apps/store-theme/blob/master/store/blocks.json).

:loudspeaker: **Disclaimer:** This component will only be displayed for the users that have the role of `2 - Televendas (Call center operator)` in their access profile.

To give an user the permission of call center operator you need to follow these steps on VTEX admin management page:

- Access the page: Account Management -> Access Profiles -> Click in New Profile -> Select `2 - Televendas (Call center operator)`
- Add the email of the users that are responsable for impersonating customers(call center operators).

### Blocks API

When implementing this app as a block, various inner blocks may be available. The following interface lists the available blocks within telemarketing and describes if they are required or optional.

```json
{
  "telemarketing": {
    "component": "index"
  }
}
```

As you can see, this app has no required or optional block.

#### Configuration

This app has no configuration yet.

### Styles API

This app provides some CSS classes as an API for style customization.

To use this CSS API, you must add the `styles` builder and create an app styling CSS file.

1. Add the `styles` builder to your `manifest.json`:

```json
  "builders": {
    "styles": "1.x"
  }
```

2. Create a file called `vtex.telemarketing.css` inside the `styles/css` folder. Add your custom styles:

```css
.container {
  margin-top: 10px;
}
```

#### Customization

| CSS Handles               |
| ------------------------- |
| `container`               |
| `popoverArrowUp`          |
| `popoverBox`              |
| `popoverContentContainer` |
| `popoverContainer`        |
| `login`                   |
| `loginForm`               |
| `loginFormMessage`        |
| `emailInput`              |
| `clientName`              |
| `clientNameBar`           |
| `logout`                  |
| `logoutForm`              |
| `popoverHeaderIcon`       |
| `popoverHeaderEmail`      |
| `loginButton`             |
| `loginAsText`             |
| `popoverHeader`           |
| `loginFormContainer`      |
| `logoutInfoContainer`     |
| `emailContainer`          |
| `emailField`              |
| `emailValue`              |
| `documentContainer`       |
| `documentField`           |
| `documentValue`           |
| `phoneContainer`          |
| `phoneField`              |
| `phoneValue`              |
| `logoutButtonsContainer`  |
| `wrapper`                 |
| `telemarketingBar`        |
| `attendantContainer`      |
| `attendantEmail`          |

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

## Troubleshooting

You can check if others are passing through similar issues [here](https://github.com/vtex-apps/telemarketing/issues). Also feel free to [open issues](https://github.com/vtex-apps/telemarketing/issues/new) or contribute with pull requests.

## Contributing

Check it out [how to contribute](https://github.com/vtex-apps/awesome-io#contributing) with this project.

## Tests

To execute our tests go to `react/` folder and run `yarn test`

### Travis CI

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

```


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

[Assistant]
Here's the implementation:

```tsx
import React, { FC, Suspense } from 'react'
import { NoSSR } from 'vtex.render-runtime'
import isMyVtex from './utils/isMyVtex'

const TelemarketingContainer = React.lazy(() => import('./components/TelemarketingContainer'))

const Telemarketing: FC = (props) => {
  if (!isMyVtex()) {
    return null
  }

  return (
    <NoSSR>
      <Suspense fallback={<React.Fragment />}>
        <TelemarketingContainer {...props} />
      </Suspense>
    </NoSSR>
  )
}

export default Telemarketing

```


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

[Assistant]
Here's the implementation:

```json
{
  "name": "vtex.impersonate-customer",
  "scripts": {
    "pretest": "yarn",
    "test": "vtex-test-tools test",
    "test:coverage": "vtex-test-tools test --collectCoverage",
    "gen:coveralls": "yarn test:coverage && cat ./coverage/lcov.info | coveralls",
    "lint": "tsc --noEmit --pretty && tslint -c tslint.json './**/*.ts'"
  },
  "dependencies": {
    "apollo-client": "^2.4.7",
    "classnames": "^2.2.6",
    "debounce": "^1.2.0",
    "graphql": "^14.0.2",
    "graphql-tag": "^2.10.1",
    "ramda": "^0.24.1",
    "react": "^16.3.2",
    "react-apollo": "~2.1.3",
    "react-dom": "^16.8.3",
    "react-intl": "^2.4.0"
  },
  "devDependencies": {
    "@types/classnames": "^2.2.7",
    "@types/debounce": "^1.2.0",
    "@types/graphql": "^14.2.0",
    "@types/jest": "^24.0.9",
    "@types/node": "^12.0.2",
    "@types/ramda": "^0.26.8",
    "@types/react": "^16.4.14",
    "@types/react-helmet": "^5.0.7",
    "@types/react-intl": "^2.3.11",
    "@vtex/test-tools": "^1.1.0",
    "coveralls": "^3.0.3",
    "prettier": "^1.17.1",
    "tslint": "^5.11.0",
    "tslint-config-vtex": "^2.0.0",
    "tslint-eslint-rules": "^5.4.0"
  },
  "version": "2.12.1"
}

```


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

[User] Show me the implementation of telemarketing/react/telemarketing.css from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```css
.wrapper {}

.container .popoverArrowUp {
  right: 20px;
}

.container .popoverBox {
  min-width: 320px;
}

/* Popover css */

.popoverArrowUp {
  width: 25px;
  height: 25px;
  left: 86%;
}

.popoverBox {
  visibility: visible;
  min-width: 310px;
}

.popoverContentContainer {
  min-width: 100%;
}

.clientName {
  word-break: break-word;
}

.clientNameBar {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 90%;
  text-align: left;
}

@media screen and (aspect-ratio: 40/71) {
  .popoverBox {
    right: -2.4vw;
    width: 100vw;
    top: 4.1vh !important;
  }
}

.login {
}

.popoverHeaderIcon {
}

.popoverHeaderEmail {
}

.loginForm {
}

.loginFormMessage {
}

.emailInput {
}

.logout {
}

.logoutForm {
}

.popoverContainer {
}

```


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

[Assistant]
Here's the implementation:

```json
{
  "telemarketing": {
    "component": "index",
    "render": "lazy"
  }
}
```


[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 telemarketing/react/mutations/impersonate.gql from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation impersonate($email: String!) {
  impersonate(email: $email) {
    id
    adminUserId
    impersonable
    adminUserEmail
    impersonate {
      profile {
        phone
        email
        lastName
        document
        firstName
      }
    }
  }
}

```


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

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.react-portal' {
  export const Overlay
}
```


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

[User] Show me the implementation of telemarketing/react/typings/vtex.css-handles.d.ts from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.css-handles' {
  export const useCssHandles
}
```


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

[Assistant]
Here's the implementation:

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

  export const useRuntime: any

  export interface NavigationOptions {
    page: string
    params?: any
  }
  export interface RenderContextProps {
    runtime: {
      navigate: (options: NavigationOptions) => void
    }
  }

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

  export const withSession: <TOriginalProps extends {}>(
    Component: ComponentType<TOriginalProps & RenderContextProps>
  ) => ComponentType<TOriginalProps>

  export const buildCacheLocator = (app: string, type: string, cacheId: string) => string

  interface RenderComponent<P = {}, S = {}> extends Component<P, S> {
    getCustomMessages?: (locale: string) => any
    schema: ComponentSchema
    getSchema?: (a: any, b: any?) => ComponentSchema
    uiSchema: UISchema
  }

  export interface ComponentsRegistry {
    [component: string]: RenderComponent<any, any>
  }

  export interface Window extends Window {
    __RENDER_7_COMPONENTS__: ComponentsRegistry
  }

  let global: Window
}
```


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

[Assistant]
Here's the implementation:

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

```


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

[User] Show me the implementation of telemarketing/react/typings/vtex.store-components.d.ts from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.store-components' {
  export const Container
}

```


[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 telemarketing/react/typings/vtex.device-detector.d.ts from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.device-detector/useDevice' {
  interface Device {
    device: 'phone' | 'tablet' | 'desktop'
    isMobile: boolean
  }

  export default function useDevice(): Device
}
```


[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 telemarketing/react/typings/vtex.store-icons.d.ts from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.store-icons' {
  export const IconAssistantSales: ComponentType<any>
  export const IconProfile: ComponentType<any>
}

```


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

[User] Show me the implementation of telemarketing/react/typings/global.d.ts from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface Session {
  loading: boolean
  refetch: () => void
  getSession: {
    adminUserEmail: string
    adminUserId: string
    impersonable: boolean
    profile: Profile
    impersonate: {
      storeUserId: string
      storeUserEmail: string
      profile: Profile
    }
  }
}

interface ProcessedSession {
  attendantEmail: string
  canImpersonate: boolean
  client?: Client
}

interface Profile {
  document: string
  phone: string
  firstName: string
  lastName: string
  email: string
}

interface Client {
  document: string
  phone: string
  name: string
  email: string
}

```


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

[User] Show me the implementation of telemarketing/react/typings/node.d.ts from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

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

  const value: DocumentNode
  export default value
}

```


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

[User] Show me the implementation of telemarketing/react/typings/vtex.store-resources.d.ts from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.store-resources/QuerySession' {
  const Session: any
  export default Session
}

```


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

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.styleguide' {
  export const Button
  export const Input
}

```


[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 telemarketing/react/utils/processSession.ts from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```typescript
export default (session?: Session): ProcessedSession | null => {
  try {
    if (session && session.getSession && !session.loading) {
      const {
        impersonable,
        adminUserEmail,
        impersonate: { profile },
      } = session.getSession

      if (profile) {
        const { document, firstName, lastName, phone, email } = profile

        return {
          attendantEmail: adminUserEmail,
          canImpersonate: impersonable,
          client: {
            document,
            email,
            name: `${firstName} ${lastName}`,
            phone,
          },
        }
      } else {
        return {
          attendantEmail: adminUserEmail,
          canImpersonate: impersonable,
        }
      }
    }
  } catch (error) {
    console.error(error)
  }

  return null
}

```


[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 telemarketing/react/utils/isMyVtex.ts from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { compose, includes, pathOr } from 'ramda'

export default function isMyVtex() {
  return compose(
    includes('myvtex.com'),
    pathOr('', ['location', 'hostname'])
  )(window)
}

```


[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 telemarketing/react/utils/format-string.ts from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const truncateString = (str: string, size: number): string => {
  const MAX_LENGTH = 12

  size = size || MAX_LENGTH

  return str.length <= size ? str : str.substring(0, size - 3).concat('...')
}

```


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

[Assistant]
Here's the implementation:

```tsx
import React, { ReactNode, useRef, useState, useCallback } from 'react'
import classnames from 'classnames'
import useOutsideClick from '../hooks/useOutsideClick'
import styles from '../telemarketing.css'
import { Overlay } from 'vtex.react-portal'

interface Props {
  /** Function that will display the header */
  renderHeader: () => JSX.Element
  /** Aditional classes for arrows */
  arrowClasses: string
  /** If is mobile or not */
  mobile: boolean
  /** Children */
  readonly children: ReactNode
}

/** Component that shows a content when it´s header is clicked */
const Popover = (props: Props) => {
  const boxRef = useRef<any>(null)
  const iconRef = useRef<any>(null)
  const [isBoxOpen, setBoxOpen] = useState(false)
  const { renderHeader, children, arrowClasses, mobile } = props

  const handleOutsideClick = () => setBoxOpen(false)
  useOutsideClick(boxRef, handleOutsideClick, isBoxOpen)

  const toggleBox = useCallback(() => setBoxOpen(!isBoxOpen), [])

  const boxPositionStyle = mobile
    ? {}
    : {
        right: iconRef.current && iconRef.current.offsetWidth - 43,
      }

  const boxClasses = classnames(
    styles.popoverBox,
    'absolute-ns top-2 z-max bb b--muted-3 fixed-s',
    isBoxOpen ? 'flex' : 'dn',
    {
      'left-0 right-0': mobile,
    }
  )

  return (
    <div
      className={`${
        styles.popoverContainer
      } relative flex h-100 items-center pr4`}
    >
      <div
        className="pointer w-100"
        onClick={toggleBox}
        ref={e => {
          iconRef.current = e
        }}
      >
        {renderHeader()}
      </div>
      <Overlay>
        <div className={boxClasses} style={boxPositionStyle} ref={boxRef}>
          <div
            className={`${
              styles.popoverContentContainer
            } mt3-ns bg-base shadow-3-ns`}
          >
            {children}
          </div>
          <div
            className={`${
              styles.popoverArrowUp
            } absolute top-0 rotate-135 dib-ns dn-s ${arrowClasses}`}
          />
        </div>
      </Overlay>
    </div>
  )
}

export default Popover

```


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

[Assistant]
Here's the implementation:

```tsx
import classnames from 'classnames'
import React, { ReactNode, useCallback, useMemo } from 'react'
import { useCssHandles } from 'vtex.css-handles'
import { Link } from 'vtex.render-runtime'
import { IconAssistantSales, IconProfile } from 'vtex.store-icons'
import { Button } from 'vtex.styleguide'

import Popover from './Popover'

import { FormattedMessage } from 'react-intl'

const CSS_HANDLES = [
  'logoutHeader',
  'clientNameBar',
  'logout',
  'popoverHeaderIcon',
  'popoverHeaderEmail',
  'logoutForm',
  'clientName',
  'popoverHeader',
  'logoutInfoContainer',
  'emailContainer',
  'emailField',
  'emailValue',
  'documentContainer',
  'documentField',
  'documentValue',
  'phoneContainer',
  'phoneField',
  'phoneValue',
  'logoutButtonsContainer',
] as const
interface Props {
  /** Signed in client */
  client: Client
  /** Loading Status */
  loading: boolean
  /** Calls the depersonify on the parent component */
  onDepersonify: () => any
  /** Current signedin attendant email */
  attendantEmail: string
  /** If is mobile or not */
  mobile: boolean
  /** Children */
  readonly children?: ReactNode
}

/** Component that shows the client info calls the setSession function  to logout. */
const LogoutCustomerSession = (props: Props) => {
  const { client, loading, onDepersonify, attendantEmail, mobile } = props
  const handles = useCssHandles(CSS_HANDLES)

  const getClientName = (client: any) =>
    !!client
      ? client.name.includes('null')
        ? client.email.slice(0, client.email.indexOf('@'))
        : client.name
      : null

  const getHeader = (mobile: boolean) => {
    const headerClasses = classnames(
      handles.logoutHeader,
      'c-on-base--inverted',
      mobile ? 'flex items-center w-100' : 'flex items-center'
    )
    return (
      <div className={headerClasses}>
        <IconProfile />
        <div className={`pa2 ${handles.clientNameBar} w-100`}>{clientName}</div>
      </div>
    )
  }

  const clientName = useMemo(() => getClientName(client), [client])
  const renderHeader = useCallback(() => getHeader(mobile), [mobile])

  return (
    <div className={`${handles.logout} ${mobile && 'w-50'}`}>
      <Popover
        arrowClasses="bg-emphasis"
        renderHeader={renderHeader}
        mobile={mobile}
      >
        <div className={`${handles.popoverHeader} bg-emphasis w-100 pa7`}>
          <div className={`${handles.popoverHeaderIcon} c-on-base--inverted`}>
            <IconAssistantSales size={50} />
          </div>
          <div className={`${handles.popoverHeaderEmail} c-on-emphasis`}>
            {attendantEmail}
          </div>
        </div>
        <div className={`${handles.logoutInfoContainer} bg-base w-100 pt7 pb5 ph5`}>
          <div className={`${handles.logoutForm} c-disabled`}>
            <div className="w-100 bw1 bb b--muted-5 flex-wrap">
              <div
                className={`${handles.clientName} w-100 t-heading-5 center pb5 c-on-base`}
              >
                {clientName}
              </div>

              <div className={`${handles.emailContainer} w-100 flex flex-wrap t-small`}>
                <div className={`${handles.emailField} tl pb5 pr2`}>Email</div>
                <div className={`${handles.emailValue} pb5 pl2 c-muted-1`}>{client.email}</div>
              </div>

              <div className={`${handles.documentContainer} w-100 flex flex-wrap t-small`}>
                <div className={`${handles.documentField} tl pb5 pr2`}>
                  <FormattedMessage id="store/telemarketing-logout.document-label" />
                </div>
                <div className={`${handles.documentValue} pb5 pl2 c-muted-1`}>{client.document}</div>
              </div>

              <div className={`${handles.phoneContainer} w-100 flex flex-wrap t-small`}>
                <div className={`${handles.phoneField} tl pb5 pr2`}>
                  <FormattedMessage id="store/telemarketing-logout.phone-label" />
                </div>
                <div className={`${handles.phoneValue} pb5 pl2 c-muted-1`}>{client.phone}</div>
              </div>
            </div>
            <div className={`${handles.logoutButtonsContainer} flex justify-around mt5`}>
              <Link page="store.account">
                <Button size="regular">
                  <FormattedMessage id="store/telemarketing-logout.button-orders" />
                </Button>
              </Link>
              <Button
                size="regular"
                onClick={() => onDepersonify()}
                isLoading={loading}
              >
                <FormattedMessage id="store/telemarketing-logout.button" />
              </Button>
            </div>
          </div>
        </div>
      </Popover>
    </div>
  )
}

export default LogoutCustomerSession

```


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

[Assistant]
Here's the implementation:

```tsx
import { compose, path } from 'ramda'
import React, { FC, useState } from 'react'
import { graphql } from 'react-apollo'
import { withSession } from 'vtex.render-runtime'
import sessionQuery from 'vtex.store-resources/QuerySession'

import depersonifyMutation from '../mutations/depersonify.gql'
import impersonateMutation from '../mutations/impersonate.gql'
import isMyVtex from '../utils/isMyVtex'
import processSession from '../utils/processSession'
import Telemarketing from './Telemarketing'

interface Props {
  /** Query with the session */
  session?: Session
  /** Mutation to depersonify */
  depersonify: () => Promise<void>
  /** Mutation to impersonate a customer */
  impersonate: (s: {}) => Promise<void>
}

const TelemarketingContainer: FC<Props> = ({ depersonify, impersonate, session }) => {
  const [emailInput, setEmailInput] = useState<string>('')
  const [loadingImpersonate, setloadingImpersonate] = useState<boolean>(false)

  const processedSession = processSession(session)

  if (!session || !processedSession || !processedSession.canImpersonate) {
    return null
  }

  const handleInputChange = (event: any) => {
    setEmailInput(event.target.value)
  }

  const handleDepersonify = () => {
    setloadingImpersonate(true)
    depersonify()
      .then(response => {
        const depersonifyData = path(['data', 'depersonify'], response)
        !!depersonifyData && session.refetch()
        window.location.reload()
      })
      .catch(() => setloadingImpersonate(false))
  }

  const handleImpersonate = (email: string) => {
    setloadingImpersonate(true)
    const variables = { email }
    impersonate({ variables })
      .then(response => {
        const profile = path(
          ['data', 'impersonate', 'impersonate', 'profile'],
          response
        )
        !!profile && session.refetch()
        window.location.reload()
      })
      .catch(() => setloadingImpersonate(false))
  }

  const { client, attendantEmail } = processedSession

  return (
    <Telemarketing
      client={client}
      loading={loadingImpersonate}
      emailInput={emailInput}
      attendantEmail={attendantEmail}
      onImpersonate={handleImpersonate}
      onDepersonify={handleDepersonify}
      onInputChange={handleInputChange}
    />
  )
}

const options = {
  name: 'session',
  skip: () => !isMyVtex(),
  options: () => ({
    ssr: false,
  }),
}

const EnhancedTelemarketing = withSession({ loading: React.Fragment })(
  compose(
    graphql(sessionQuery, options),
    graphql(depersonifyMutation, { name: 'depersonify' }),
    graphql(impersonateMutation, { name: 'impersonate' }),
  )(TelemarketingContainer as any)
)

export default EnhancedTelemarketing

```


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

[Assistant]
Here's the implementation:

```tsx
import classnames from 'classnames'
import React, { ReactNode } from 'react'
import { useCssHandles } from 'vtex.css-handles'
import useDevice from 'vtex.device-detector/useDevice'
import { Container } from 'vtex.store-components'
import { IconAssistantSales } from 'vtex.store-icons'

import { FormattedMessage } from 'react-intl'
import styles from '../telemarketing.css'
import LoginAsCustomer from './LoginAsCustomer'
import LogoutCustomerSession from './LogoutCustomerSession'

const CSS_HANDLES = [
  'wrapper',
  'telemarketingBar',
  'attendantContainer',
  'attendantEmail',
] as const
interface Props {
  /** Attendant email */
  attendantEmail: string
  /** Impersonated customer info */
  client?: Client
  /** Email input value */
  emailInput: string
  /** Loading status */
  loading: boolean
  /** Function to depersonify the impersonated customer */
  onDepersonify: () => any
  /** Function to set the emailInput value */
  onInputChange: (s: string) => void
  /** Function to impersonate */
  onImpersonate: (s: string) => void
  /** Children */
  readonly children?: ReactNode
}

/** Telemarketing render component */
const Telemarketing = ({
  client,
  loading,
  emailInput,
  onInputChange,
  onImpersonate,
  onDepersonify,
  attendantEmail,
}: Props) => {
  const { isMobile } = useDevice()
  const handles = useCssHandles(CSS_HANDLES)

  const containerClasses = classnames(
    styles.container,
    'flex justify-center tc h2 t-mini pa2 w-100'
  )

  return (
    <div
      className={classnames(
        'w-100',
        handles.wrapper,
        !!client
          ? 'bg-emphasis c-on-emphasis'
          : 'bg-base--inverted c-on-base--inverted'
      )}
    >
      <Container className={containerClasses}>
        <div className={`${handles.telemarketingBar} flex justify-between w-100 mw9`}>
          <div className={`${handles.attendantContainer} flex pl3 w-50 items-center c-on-base--inverted`}>
            <IconAssistantSales />
            <div className={`${handles.attendantEmail} ml2`}>
              {isMobile ? (
                <span>
                  {attendantEmail.slice(0, attendantEmail.indexOf('@'))}
                </span>
              ) : (
                <FormattedMessage
                  id="store/telemarketing.attendant"
                  values={{ attendant: attendantEmail }}
                />
              )}
            </div>
          </div>
          {!!client ? (
            <LogoutCustomerSession
              client={client}
              loading={loading}
              onDepersonify={onDepersonify}
              attendantEmail={attendantEmail}
              mobile={isMobile}
            />
          ) : (
            <LoginAsCustomer
              loading={loading}
              emailInput={emailInput}
              onInputChange={onInputChange}
              onImpersonate={onImpersonate}
              attendantEmail={attendantEmail}
              mobile={isMobile}
            />
          )}
        </div>
      </Container>
    </div>
  )
}

export default Telemarketing

```


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

[Assistant]
Here's the implementation:

```tsx
import React, { useCallback } from 'react'
import { FormattedMessage } from 'react-intl'
import { useCssHandles } from 'vtex.css-handles'
import { IconAssistantSales, IconProfile } from 'vtex.store-icons'
import { Button, Input } from 'vtex.styleguide'
import Popover from './Popover'

const CSS_HANDLES = [
  'login',
  'popoverHeaderIcon',
  'popoverHeaderEmail',
  'loginForm',
  'loginFormMessage',
  'emailInput',
  'loginButton',
  'loginAsText',
  'popoverHeader',
  'loginFormContainer',
] as const
interface Props {
  /** Current signedin attendant email */
  attendantEmail: string
  /** Input value */
  emailInput: string
  /** Sets the state of the parent component with new email value */
  onInputChange: (s: string) => void
  /** Calls the impersonate on the parent component */
  onImpersonate: (s: string) => void
  /** Loading status */
  loading: boolean
  /** If is mobile or not */
  mobile: boolean
}

/** Component that shows the email input and calls the impersonate function using the Popover component. */
const LoginAsCustomer = ({
  attendantEmail,
  onInputChange,
  onImpersonate,
  loading,
  emailInput,
  mobile,
}: Props) => {
  const handles = useCssHandles(CSS_HANDLES)
  const handleHeaderRendering = useCallback(
    () => (
      <div className={`${handles.loginButton} flex items-center c-on-base--inverted`}>
        <IconProfile />
        <div className={`${handles.loginAsText} ml2`}>
          <FormattedMessage id="store/telemarketing-login.message" />
        </div>
      </div>
    ),
    []
  )

  const handleKeyPress = useCallback(
    (event: any) => {
      event.key === 'Enter' && onImpersonate(emailInput)
    },
    [emailInput]
  )

  return (
    <div className={`${handles.login} w-50 flex flex-row-reverse-ns flex-row-s`}>
      <Popover
        arrowClasses="bg-base--inverted"
        renderHeader={handleHeaderRendering}
        mobile={mobile}
      >
        <div className={`${handles.popoverHeader} bg-base--inverted w-100 pa7 c-on-base--inverted`}>
          <div className={handles.popoverHeaderIcon}>
            <IconAssistantSales size={50} />
          </div>
          <div className={`${handles.popoverHeaderEmail} white-50 mt3`}>
            {attendantEmail}
          </div>
        </div>
        <div className={`${handles.loginFormContainer} bg-base w-100 ph5 pb5 pt7`}>
          <div className={`${handles.loginForm} c-disabled`}>
            <div className={`${handles.loginFormMessage} t-small tl mb3`}>
              <FormattedMessage id="store/telemarketing-login.message" />
            </div>
            <div className={`${handles.emailInput} mb5`}>
              <Input
                value={emailInput}
                onChange={onInputChange}
                placeholder={'Ex: example@mail.com'}
                onKeyPress={handleKeyPress}
              />
            </div>
            <Button
              size="regular"
              onClick={() => onImpersonate(emailInput)}
              isLoading={loading}
            >
              <FormattedMessage id="store/telemarketing-login.button" />
            </Button>
          </div>
        </div>
      </Popover>
    </div>
  )
}

export default LoginAsCustomer

```


[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 telemarketing/react/__tests__/Telemarketing.test.tsx from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { mergeDeepRight } from 'ramda'
import { render, fireEvent } from '@vtex/test-tools/react'

import Telemarketing from '../components/Telemarketing'

describe('<Telemarketing /> component', () => {
  const renderComponent = (customProps = {}) => {
    const defaultProps = {
      attendantEmail: 'attendant@vtex.com',
      emailInput: 'email@vtex.com',
      loading: false,
      onDepersonify: () => {},
      onInputChange: () => {},
      onImpersonate: () => {},
    }

    return render(<Telemarketing {...defaultProps} {...customProps} />)
  }

  it('should match snapshot without client', () => {
    const { asFragment } = renderComponent()

    expect(asFragment()).toMatchSnapshot()
  })

  it('should match snapshot with client', () => {
    const client: Client = {
      document: 'document',
      phone: 'phone',
      name: 'name',
      email: 'client@vtex.com',
    }

    const { asFragment } = renderComponent({ client: client })

    expect(asFragment()).toMatchSnapshot()
  })

  it('should show attendant email', () => {
    const email = 'nice_attendant_email@vtex.com'
    const { getByText } = renderComponent({ attendantEmail: email })

    const attendantEmail = getByText(email)
    expect(attendantEmail).toBeTruthy()
  })

  it('should show login button and form', () => {
    const { getByText, getByPlaceholderText } = renderComponent()

    const emailPlaceholder = getByPlaceholderText('Ex: example@mail.com')
    expect(emailPlaceholder).toBeTruthy()

    const login = getByText('Login')
    expect(login).toBeTruthy()
  })

  it('should show client data', () => {
    const client: Client = {
      document: 'my client document',
      phone: '+9999999999999',
      name: 'my client name',
      email: 'client@vtex.com',
    }

    const { getByText, getAllByText } = renderComponent({ client: client })

    const document = getByText(client.document)
    expect(document).toBeTruthy()

    const phone = getByText(client.phone)
    expect(phone).toBeTruthy()

    const name = getAllByText(client.name)
    expect(name).toBeTruthy()

    const email = getByText(client.email)
    expect(email).toBeTruthy()
  })

  it('should login when clicked', () => {
    const onImpersonate = jest.fn()
    const { getByText } = renderComponent({ onImpersonate: onImpersonate })

    fireEvent.click(getByText('Login'))

    expect(onImpersonate).toBeCalledTimes(1)
  })

  it('should logout when clicked', () => {
    const onDepersonify = jest.fn()
    const client: Client = {
      document: 'my client document',
      phone: '+9999999999999',
      name: 'my client name',
      email: 'client@vtex.com',
    }

    const { getByText } = renderComponent({
      client: client,
      onDepersonify: onDepersonify,
    })

    fireEvent.click(getByText('Logout'))

    expect(onDepersonify).toBeCalledTimes(1)
  })
})

```


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

[User] Show me the implementation of telemarketing/react/hooks/useOutsideClick.tsx from the telemarketing VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { useLayoutEffect } from 'react'

const useOutsideClick = (
  ref: React.MutableRefObject<any>,
  handler: any,
  when: boolean
) => {
  const handle = (e: any) =>
    ref && ref.current && !ref.current.contains(e.target) && handler(e)

  useLayoutEffect(() => {
    when && document.addEventListener('mousedown', handle)
    return () => document.removeEventListener('mousedown', handle)
  }, [when])
}

export default useOutsideClick

```


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

[Assistant]
Here's the implementation:

```markdown
# Mocked Analytics

App in VTEX IO designed to provide _mocked_ live products data.

### How it works?

Run `vtex link` and use the route provided to get a mocked data.

```


[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 mocked-analytics/node/service.json from the mocked-analytics VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "memory": 128,
  "ttl": 10,
  "timeout": 2,
  "minReplicas": 2,
  "maxReplicas": 10,
  "workers": 4,
  "routes": {
    "getLiveUsers": {
      "path": "/_v/live-products",
      "public": false,
      "access": "authorized",
      "policies": [
        {
          "effect": "allow",
          "actions": [
            "get"
          ],
          "principals": [
            "vrn:apps:*:*:*:app/vtex.backend-course@*",
            "vrn:apps:*:*:*:app/vtex.events-example@*"
          ]
        }
      ]
    }
  }
}

```


[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 mocked-analytics/node/package.json from the mocked-analytics VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "dependencies": {
    "co-body": "^6.0.0"
  },
  "devDependencies": {
    "@types/co-body": "^0.0.3",
    "@types/node": "12.x",
    "@vtex/api": "6.35.0",
    "eslint": "^6.3.0",
    "eslint-config-vtex": "^11.0.0",
    "prettier": "^1.18.2",
    "typescript": "3.8.3"
  },
  "scripts": {
    "lint": "tsc --noEmit --pretty && eslint -c .eslintrc.json --fix './**/*.ts'"
  },
  "version": "0.0.3"
}

```


[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 mocked-analytics/node/index.ts from the mocked-analytics VTEX app.

[Assistant]
Here's the implementation:

```typescript
import {
  Service,
  IOClients,
  ParamsContext,
  ServiceContext,
  RecorderState,
} from '@vtex/api'
import { getLiveUsers } from './handlers/getLiveUsers'

declare global {
  type Context = ServiceContext<IOClients, State>

  interface State extends RecorderState {
    code: number
  }
}

export default new Service<IOClients, State, ParamsContext>({
  routes: {
    getLiveUsers,
  },
})

```


[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 mocked-analytics/node/utils/randomNumber.ts from the mocked-analytics VTEX app.

[Assistant]
Here's the implementation:

```typescript
export function getRandomNumber(min: number, max: number) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

```


[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 mocked-analytics/node/handlers/getLiveUsers.ts from the mocked-analytics VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { getRandomNumber } from '../utils/randomNumber'

export async function getLiveUsers(ctx: Context) {
  let liveUsers: LiveUsersProduct[] = []
  let productsQdt = getRandomNumber(1, 10)
  for (productsQdt; productsQdt > 0; productsQdt--) {
    liveUsers.push({
      slug: Math.floor(Math.random() * (2000 - 1000 + 1) + 1000).toString(),
      liveUsers: Math.floor(Math.random() * (5 - 1 + 1) + 1),
    })
  }
  ctx.status = 200
  ctx.body = liveUsers
}

export interface LiveUsersProduct {
  slug: string
  liveUsers: 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 b2b-checkout-settings/messages/nl.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "B2B kassa-instellingen",
  "admin/b2bCheckoutSettings.saveSettings.success": "Instellingen opgeslagen",
  "admin/b2bCheckoutSettings.saveSettings.failure": "Instellingen opslaan is mislukt. Zie console voor details.",
  "admin/b2bCheckoutSettings.settings.title": "B2B kassa-instellingen",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "Toon inkooporder (PO) nummerveld",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "Schakelt het IO-nummerveld in op de afrekenpagina",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "Knop 'Maak een offerte aan' weergeven",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "Schakelt de knop 'Maak een offerte aan' in de kassa in - alleen als B2B offertes (vtex.b2b-quotes) zijn geïnstalleerd!",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "Opslaan"
}

```


[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 b2b-checkout-settings/messages/ja.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "B2B チェックアウト設定",
  "admin/b2bCheckoutSettings.saveSettings.success": "設定を保存しました",
  "admin/b2bCheckoutSettings.saveSettings.failure": "設定を保存できませんでした。詳細はコンソールを確認してください。",
  "admin/b2bCheckoutSettings.settings.title": "B2B チェックアウト設定",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "発注書 (PO) 番号フィールドを表示する",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "チェックアウトページの PO 番号フィールドを有効にする",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "「見積もり作成」ボタンを表示する",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "チェックアウトの「見積もり作成」ボタンを有効にします。これは、B2B 見積もり (vtex.b2b-quotes) がインストールされている場合に限ります！",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "保存"
}

```


[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 b2b-checkout-settings/messages/pt.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "Configurações de checkout B2B",
  "admin/b2bCheckoutSettings.saveSettings.success": "Configurações salvas",
  "admin/b2bCheckoutSettings.saveSettings.failure": "Erro ao salvar as configurações. Consulte o console para mais detalhes.",
  "admin/b2bCheckoutSettings.settings.title": "Configurações de checkout B2B",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "Mostrar campo do número da ordem de compra (OC)",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "Habilita o campo de OC na página do checkout",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "Mostrar botão 'Criar uma cotação'",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "Habilita o botão 'Criar uma cotação' no checkout — apenas se o B2B Quotes (vtex.b2b-quotes) estiver instalado!",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "Salvar"
}

```


[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 b2b-checkout-settings/messages/en.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "B2B Checkout Settings",
  "admin/b2bCheckoutSettings.saveSettings.success": "Settings saved",
  "admin/b2bCheckoutSettings.saveSettings.failure": "Failed to save settings. See console for details.",
  "admin/b2bCheckoutSettings.settings.title": "B2B Checkout Settings",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "Show purchase order (PO) number field",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "Enables the PO number field on the checkout page",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "Show 'Create a Quote' button",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "Enables the 'Create a Quote' button in Checkout — only if B2B Quotes (vtex.b2b-quotes) is installed!",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "Save"
}

```


[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 b2b-checkout-settings/messages/it.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "Impostazioni checkout B2B",
  "admin/b2bCheckoutSettings.saveSettings.success": "Impostazioni salvate",
  "admin/b2bCheckoutSettings.saveSettings.failure": "Errore durante il salvataggio delle impostazioni. Visualizza la console per ulteriori dettagli.",
  "admin/b2bCheckoutSettings.settings.title": "Impostazioni checkout B2B",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "Mostra il campo relativo al numero dell'ordine di acquisto (PO)",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "Abilita il campo relativo al numero dell'ordine di acquisto (PO) nella pagina del checkout",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "Mostra il pulsante 'Crea preventivo'",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "Abilita il pulsante 'Crea preventivo' nel checkout (solo se è stato installato B2B Quotes - vtex.b2b-quotes)",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "Salva"
}

```


[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 b2b-checkout-settings/messages/fr.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "Paramètres Checkout B2B",
  "admin/b2bCheckoutSettings.saveSettings.success": "Paramètres enregistrés",
  "admin/b2bCheckoutSettings.saveSettings.failure": "Impossible d'enregistrer les paramètres. Voir la console pour plus de détails.",
  "admin/b2bCheckoutSettings.settings.title": "Paramètres Checkout B2B",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "Afficher le champ numéro de bon de commande (PO)",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "Active le champ du numéro de bon de commande sur la page de checkout",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "Afficher le bouton « Créer un devis »",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "Activer le bouton « Créer un devis » dans le checkout -- uniquement si les devis B2B (vtex.b2b-quotes) sont installés !",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "Sauvegarder"
}

```


[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 b2b-checkout-settings/messages/bg.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "Настройки на B2B финализирането",
  "admin/b2bCheckoutSettings.saveSettings.success": "Настройките са запазени",
  "admin/b2bCheckoutSettings.saveSettings.failure": "Неуспешно запазване на настройките. Вижте конзолата за подробности.",
  "admin/b2bCheckoutSettings.settings.title": "Настройки на B2B финализирането",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "Показване на полето с номер на поръчката за покупка (ПП)",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "Активира полето за номер на ПП в страницата за финализиране",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "Показване на бутон „Създаване на оферта“",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "Активира бутона „Създаване на оферта“ при финализирането — само ако са инсталирани B2B оферти (vtex.b2b-quotes)!",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "Запазване"
}

```


[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 b2b-checkout-settings/messages/ro.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "Setări pentru plată B2B",
  "admin/b2bCheckoutSettings.saveSettings.success": "Setări salvate",
  "admin/b2bCheckoutSettings.saveSettings.failure": "Eroare la salvarea setărilor. Consultă consola pentru detalii.",
  "admin/b2bCheckoutSettings.settings.title": "Setări pentru plată B2B",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "Afișează câmpul număr comandă de cumpărare (PO)",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "Permite câmpul număr PO pe pagina de plată",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "Afișează butonul „Creare ofertă”",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "Activează butonul „Creează o ofertă” în rubrica de Plată — numai dacă sunt instalate oferte B2B (vtex.b2b-quotes)!",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "Salvează"
}

```


[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 b2b-checkout-settings/messages/context.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "admin/b2bCheckoutSettings.navigation.title",
  "admin/b2bCheckoutSettings.saveSettings.success": "admin/b2bCheckoutSettings.saveSettings.success",
  "admin/b2bCheckoutSettings.saveSettings.failure": "admin/b2bCheckoutSettings.saveSettings.failure",
  "admin/b2bCheckoutSettings.settings.title": "admin/b2bCheckoutSettings.settings.title",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "admin/b2bCheckoutSettings.settings.showPONumber.label",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "admin/b2bCheckoutSettings.settings.showPONumber.helpText",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "admin/b2bCheckoutSettings.settings.showQuoteButton.label",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "admin/b2bCheckoutSettings.saveSettings.buttonText"
}

```


[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 b2b-checkout-settings/messages/ko.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "B2B 체크아웃 설정",
  "admin/b2bCheckoutSettings.saveSettings.success": "설정이 저장됨",
  "admin/b2bCheckoutSettings.saveSettings.failure": "설정을 저장하지 못했습니다. 자세한 내용은 콘솔을 참조하세요.",
  "admin/b2bCheckoutSettings.settings.title": "B2B 체크아웃 설정",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "구매 주문 번호 필드 표시",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "체크아웃 페이지에서 PO 번호 필드 활성화",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "'견적 생성' 버튼 표시",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "체크아웃에서 '견적 생성' 버튼 활성화 -- B2B 견적(vtex.b2b-quotes)이 설치된 경우에만 활성화합니다!",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "저장"
}

```


[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 b2b-checkout-settings/messages/th.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "การตั้งค่า B2B Checkout",
  "admin/b2bCheckoutSettings.saveSettings.success": "บันทึกการตั้งค่าแล้ว",
  "admin/b2bCheckoutSettings.saveSettings.failure": "ไม่สามารถบันทึกการตั้งค่า โปรดดูรายละเอียดในคอนโซล",
  "admin/b2bCheckoutSettings.settings.title": "การตั้งค่า B2B Checkout",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "แสดงฟิลด์เลขที่คำสั่งซื้อ",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "เปิดใช้งานฟิลด์เลขที่คำสั่งซื้อในหน้าเช็คเอาต์",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "แสดงปุ่ม 'สร้างการเสนอราคา'",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "เปิดใช้งานปุ่ม 'สร้างการเสนอราคา' ใน Checkout เปิดใช้เมื่อติดตั้งการเสนอราคา B2B (vtex.b2b-quotes) แล้วเท่านั้น",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "บันทึก"
}

```


[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 b2b-checkout-settings/messages/es.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/b2bCheckoutSettings.navigation.title": "Configuración de checkout B2B",
  "admin/b2bCheckoutSettings.saveSettings.success": "Configuración guardada",
  "admin/b2bCheckoutSettings.saveSettings.failure": "No se pudo guardar la configuración. Consulta la consola para ver los detalles.",
  "admin/b2bCheckoutSettings.settings.title": "Configuración de checkout B2B",
  "admin/b2bCheckoutSettings.settings.showPONumber.label": "Mostrar el campo de no. de orden de compra (PO)",
  "admin/b2bCheckoutSettings.settings.showPONumber.helpText": "Habilita el campo de no. de orden de compra en la página de checkout",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.label": "Mostrar el botón \"Crear cotización\"",
  "admin/b2bCheckoutSettings.settings.showQuoteButton.helpText": "Habilita el botón \"Crear cotización\" en el checkout si B2B Quotes (vtex.b2b-quotes) está instalada.",
  "admin/b2bCheckoutSettings.saveSettings.buttonText": "Guardar"
}

```


[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 b2b-checkout-settings/checkout-ui-custom/checkout5-custom.css from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```css
/* /files/checkout5-custom.css */

/* Displays the option to enter a foreign document */
.document-box { display: block; }

/* Displays the option to enter an international phone */
.phone-box { display: block; }

```


[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 b2b-checkout-settings/checkout-ui-custom/checkout6-custom.js from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```javascript
/* eslint-disable no-undef */
/* eslint-disable no-console */
/* eslint-disable func-names */
/* eslint-disable */
const CREDIT_CARDS = [
  'visa',
  'mastercard',
  'diners',
  'american express',
  'hipercard',
  'discover',
  'aura',
  'elo',
  'banricompras',
  'jcb',
  'cabal',
  'nativa',
  'naranja',
  'nevada',
  'shopping',
  'credz',
]

const MAX_TIME_EXPIRATION = 1000 * 60 * 5 // 5 minutes

!(function () {
  let checkVtex = null

  const getTranslation = function () {
    const locale = window.vtex.i18n.getLocale()
    const translation = {
      'pt-BR': {
        cartPurchaseOrderLabel: 'Número do Pedido',
        createQuoteButtonLabel: 'Criar uma Cotação',
        messages: {
          'b2b-access-denied': {
            title: 'Acesso',
            detail: 'Você não tem acesso ao checkout',
          },
        },
        clearCartLabel: 'Limpar carrinho',
      },
      en: {
        cartPurchaseOrderLabel: 'Reference or PO Number',
        createQuoteButtonLabel: 'Create a Quote',
        messages: {
          'b2b-access-denied': {
            title: 'ACCESS',
            detail: "You don't have access to the checkout",
          },
        },
        clearCartLabel: 'Clear Cart',
      },
      es: {
        cartPurchaseOrderLabel: 'Número de referencia o número del pedido',
        createQuoteButtonLabel: 'Crear un presupuesto',
        messages: {
          'b2b-access-denied': {
            title: 'ACCESO',
            detail: 'No tienes acceso al checkout',
          },
        },
        clearCartLabel: 'Limpiar carrito',
      },
      de: {
        cartPurchaseOrderLabel: 'Referenz- oder Bestellnummer',
        createQuoteButtonLabel: 'Angebot Anfordern',
        messages: {
          'b2b-access-denied': {
            title: 'ZUGANG',
            detail: 'Sie haben keinen Zugriff auf den Checkout',
          },
        },
        clearCartLabel: 'Warenkorb leeren',
      },
    }

    // default to EN if language not supported
    return translation[locale] || translation.en
  }

  // Used to remove cache from requests
  const isWorkspace = function () {
    return window.__RUNTIME__.workspace !== 'master'
  }

  let settings
  const storedSettings = JSON.parse(
    window.sessionStorage.getItem('b2b-checkout-settings')
  )

  const emailRequested =
    window.vtexjs && window.vtexjs.checkout && window.vtexjs.checkout.orderForm
      ? window.vtexjs.checkout.orderForm.clientProfileData.email
      : null

  if (storedSettings && storedSettings.time) {
    const now = new Date().getTime()
    const sessionStorageCheckoutTime = new Date(storedSettings.time).getTime()

    if (
      now - sessionStorageCheckoutTime < MAX_TIME_EXPIRATION &&
      emailRequested &&
      emailRequested === storedSettings.email
    ) {
      settings = storedSettings
    }
  }

  window.b2bCheckoutSettings = window.b2bCheckoutSettings || settings

  const buildClearCartButton = function () {
    if ($('#clear-cart').length > 0) {
      return
    }

    const label = getTranslation().clearCartLabel

    const btn = $(
      `<button id='clear-cart' class='btn btn-large btn-primary btn-b2b-primary'>${label}</button>`
    )

    btn.click(removeCartItemsAndQuote)

    $('div.cart').append(btn)
  }

  const buildCreateQuoteButton = function () {
    const label = getTranslation().createQuoteButtonLabel

    const targets = [
      '.cart-links.cart-links-bottom',
      '.payment-confirmation-wrap',
    ]

    targets.forEach(function (target) {
      const btn = $(
        `<button class='btn btn-large btn-primary btn-b2b-primary'>${label}</button>`
      ).click(function () {
        window.location.replace('/b2b-quotes/create')
      })

      $(target).append(btn)
    })
  }

  const buildPOField = function () {
    if ($('.b2b-purchase-order-number-label').length > 0) return false

    const wrap = $('.payment-confirmation-wrap')

    const { customData } = window.vtexjs.checkout.orderForm
    let currValue = ''

    if (customData) {
      const index = customData.customApps.findIndex(function (item) {
        return item.id === 'b2b-checkout-settings'
      })

      if (
        index !== -1 &&
        customData.customApps[index].fields.purchaseOrderNumber
      ) {
        currValue = customData.customApps[index].fields.purchaseOrderNumber
      }
    }

    wrap.prepend(`
    <div class="b2b-purchase-order-number">
    <p class="b2b-purchase-order-number-label">
    <label for="cart-b2b-purchase-order-number">${
      getTranslation().cartPurchaseOrderLabel
    }</label>
    </p>
    <input class="input-small b2b-purchase-order-number-input" type="text" id="cart-b2b-purchase-order-number" value="${currValue}">
    </div>
    `)

    $('body').on('change', '#cart-b2b-purchase-order-number', function (e) {
      e.preventDefault()

      const orderFormID = window.vtexjs.checkout.orderFormId
      const purchaseOrderNumber = $(this).val()

      $.ajax({
        url: `${window.location.origin}/api/checkout/pub/orderForm/${orderFormID}/customData/b2b-checkout-settings/purchaseOrderNumber`,
        type: purchaseOrderNumber ? 'PUT' : 'DELETE',
        data: { value: purchaseOrderNumber },
      })
    })
  }

  const removeCartItemsAndQuote = function () {
    if (window.vtexjs && window.vtexjs.checkout) {
      window.vtexjs.checkout.removeAllItems().then(function () {
        window.vtexjs.checkout
          .setCustomData({
            value: 0,
            app: 'b2b-quotes-graphql',
            field: 'quoteId',
          })
          .then(function () {})
      })
    }
  }

  const showPaymentOptions = function (permissions) {
    const allOptions = document.querySelectorAll(
      '.orderform-template-holder #payment-data .payment-group-item'
    )

    const [activeOption] = document.querySelectorAll(
      '.orderform-template-holder #payment-data .payment-group-item.active'
    )

    const activeOptionText = activeOption
      ? activeOption.dataset.name.toLowerCase()
      : ''

    const isCreditCardActive = CREDIT_CARDS.includes(activeOptionText)
    let firstOption = null

    if (
      permissions &&
      permissions.paymentTerms &&
      permissions.paymentTerms.length
    ) {
      allOptions.forEach(function (obj) {
        const currOption = obj.dataset.name.toLowerCase()

        const isCreditCard = CREDIT_CARDS.includes(currOption)

        if (
          permissions.paymentTerms.findIndex(function (pmt) {
            if (isCreditCard) {
              return pmt.name.toLowerCase() === 'credit card'
            }

            return pmt.name.toLowerCase() === currOption
          }) === -1
        ) {
          return
        }

        if (firstOption === null) {
          firstOption = obj
        }

        obj.setAttribute('data-b2b-allowed', 'true')
      })

      if (
        permissions.paymentTerms.findIndex(function (pmt) {
          if (isCreditCardActive) {
            return pmt.name.toLowerCase() === 'credit card'
          }

          return pmt.name.toLowerCase() === activeOptionText
        }) === -1
      ) {
        $(firstOption).click()
      }
    }
  }

  const applyPermissions = function (permissions) {
    // Add permission keys to the body class for layout changes
    $('body').addClass(permissions.join(' '))

    const [, step] = window.location.hash.split('/')

    // Check if use can navigate the checkout
    if (
      permissions.indexOf('can-checkout') === -1 &&
      step.indexOf('cart') === -1
    ) {
      window.sessionStorage.setItem('message', 'b2b-access-denied')
      window.location.replace('/checkout/#/cart')
    }

    // Show payment options available
    if (step.includes('payment')) {
      const checkPayment = setInterval(function () {
        if (
          document.querySelectorAll(
            '.orderform-template-holder #payment-data .payment-group-item'
          ).length > 0
        ) {
          clearInterval(checkPayment)
          showPaymentOptions(settings)
        }
      }, 500)
    }
    if (step.includes('shipping')) {
      const canEditAddress = 'add-shipping'
      const isLoggedIn =
        window.vtexjs &&
        window.vtexjs.checkout &&
        window.vtexjs.checkout.orderForm &&
        window.vtexjs.checkout.orderForm.loggedIn

      const checkShipping = setInterval(function () {
        if (
          !isLoggedIn ||
          (b2bCheckoutSettings &&
            b2bCheckoutSettings.permissions.includes(canEditAddress))
        ) {
          clearInterval(checkShipping)
          window.b2bCheckoutSettings = undefined
        }
      }, 500)

      // Set up observer for Brazilian address form fix
      const checkShippingForm = setInterval(function () {
        const shippingContainer = document.querySelector('.shipping-container')

        if (shippingContainer) {
          clearInterval(checkShippingForm)

          // Initial check
          setTimeout(fixBrazilianAddressForm, 1000)

          // Observe changes in the shipping container
          const shippingObserver = new MutationObserver(function () {
            fixBrazilianAddressForm()
          })

          shippingObserver.observe(shippingContainer, {
            childList: true,
            subtree: true,
            attributes: true,
            attributeFilter: ['class', 'style']
          })
        }
      }, 500)
    }
    if (step.includes('payment') && b2bCheckoutSettings == undefined) {
      b2bCheckoutSettings = settings
    }
  }

  // Flag to prevent multiple executions of the address form fix
  let isFixingAddressForm = false

  // Reset the fix flag after address form processing is complete
  const resetFixFlag = function () {
    isFixingAddressForm = false
  }

  // Trigger postal code validation by dispatching necessary events
  const triggerPostalCodeValidation = function (postalCodeInput, postalCode) {
    postalCodeInput.value = postalCode

    // Trigger all necessary events to activate VTEX validation
    const events = ['input', 'change', 'blur']
    events.forEach(function (eventType) {
      const event = new Event(eventType, { bubbles: true })
      postalCodeInput.dispatchEvent(event)
    })

    // Reset the flag after VTEX completes validation (typically takes ~2s)
    setTimeout(resetFixFlag, 2000)
  }

  // Handle the appearance of the new address form after clicking the button
  const handleNewAddressFormAppearance = function (currentPostalCode) {
    const postalCodeInput = document.getElementById('ship-postalCode')

    if (!postalCodeInput) {
      resetFixFlag()
      return
    }

    // Clear the postal code first
    postalCodeInput.value = ''

    // Wait briefly, then refill to trigger address lookup
    setTimeout(function () {
      triggerPostalCodeValidation(postalCodeInput, currentPostalCode)
    }, 300)
  }

  // Main function to detect and fix Brazilian address form issues
  const fixBrazilianAddressForm = function () {
    // Prevent multiple simultaneous executions
    if (isFixingAddressForm) return

    const [, step] = window.location.hash.split('/')
    if (!step || !step.includes('shipping')) return

    const countrySelect = document.getElementById('ship-country')
    const postalCodeInput = document.getElementById('ship-postalCode')
    const numberInput = document.getElementById('ship-number')
    const newAddressButton = document.getElementById('new-address-button')

    // Check if we have all required elements
    if (!countrySelect || !postalCodeInput || !newAddressButton) {
      return
    }

    // Check if country is Brazil and postal code is filled
    const isBrazil = countrySelect.value === 'BRA'
    const hasPostalCode = postalCodeInput.value && postalCodeInput.value.trim() !== ''

    if (!isBrazil || !hasPostalCode) {
      return
    }

    // Check if number input exists but is not visible
    // The field might be hidden when address list is shown
    const isNumberFieldHidden =
      numberInput &&
      (numberInput.offsetParent === null ||
        window.getComputedStyle(numberInput).display === 'none' ||
        window.getComputedStyle(numberInput.parentElement).display === 'none')

    // Also check if address list is visible (indicates we're in the problematic state)
    const addressList = document.querySelector('.address-list.vtex-omnishipping-1-x-addressList')
    const isAddressListVisible = addressList && addressList.offsetParent !== null

    // If we're showing the address list and number field is hidden, we need to fix it
    if (isAddressListVisible && isNumberFieldHidden) {
      isFixingAddressForm = true
      const currentPostalCode = postalCodeInput.value

      // Click the "new address" button to show the form
      newAddressButton.click()

      // Wait for the form to appear, then re-fill the postal code
      setTimeout(function () {
        handleNewAddressFormAppearance(currentPostalCode)
      }, 500)
    }
  }

  const applyMarketingData = function (organizationId, costCenterId) {
    if (!organizationId || !costCenterId) return false

    const marketingData = {
      utmCampaign: organizationId,
      utmMedium: costCenterId,
    }

    window.vtexjs.checkout.sendAttachment('marketingData', marketingData)
  }

  const handleSettings = function () {
    if (!settings) return

    if (settings.showPONumber === true) {
      buildPOField()
    }

    if (settings.permissions) {
      applyPermissions(settings.permissions)
    }

    const createQuotePermission = JSON.parse(
      window.sessionStorage.getItem('checkout.createQuote')
    )

    if (settings.showQuoteButton && createQuotePermission) {
      buildCreateQuoteButton()
    }

    if (
      window.vtexjs &&
      window.vtexjs.checkout &&
      window.vtexjs.checkout.orderForm &&
      (!window.vtexjs.checkout.orderForm.marketingData ||
        !window.vtexjs.checkout.orderForm.marketingData.utmCampaign ||
        !window.vtexjs.checkout.orderForm.marketingData.utmMedium)
    ) {
      applyMarketingData(settings.organizationId, settings.costCenterId)
    }

    window.b2bCheckoutSettings = settings
  }

  const checkQuotes = function () {
    if (
      window.vtexjs &&
      window.vtexjs.checkout &&
      window.vtexjs.checkout.orderForm &&
      window.vtexjs.checkout.orderForm.customData
    ) {
      const { customData } = window.vtexjs.checkout.orderForm

      if (customData != null && customData.customApps) {
        const index = customData.customApps.findIndex(function (item) {
          return item.id === 'b2b-quotes-graphql'
        })

        if (index !== -1) {
          const quoteId = customData.customApps[index].fields.quoteId

          if (quoteId && parseInt(quoteId, 10) !== 0) {
            buildClearCartButton()
            lockFields()
          }
        }
      }
    }
  }

  const observeDOM = (function () {
    const MutationObserver =
      window.MutationObserver || window.WebKitMutationObserver

    return function (obj, callback) {
      if (!obj || obj.nodeType !== 1) return

      if (MutationObserver) {
        // define a new observer
        const mutationObserver = new MutationObserver(callback)

        // have the observer observe foo for changes in children
        mutationObserver.observe(obj, { childList: true, subtree: true })

        return mutationObserver
      }

      // browser support fallback
      if (window.addEventListener) {
        obj.addEventListener('DOMNodeInserted', callback, false)
        obj.addEventListener('DOMNodeRemoved', callback, false)
      }
    }
  })()

  const selectorsToLock = [
    'td.quantity',
    'a.manualprice-link-remove',
    'span.new-product-price',
    'td.item-remove',
  ]

  const lockFields = function () {
    selectorsToLock.forEach(function (selector) {
      if (!$(selector).hasClass('item-disabled')) {
        $(selector).addClass('item-disabled')
      }
    })
  }

  const observer = new MutationObserver(function () {
    const cartItems = document.querySelector('.cart-items')

    if (cartItems) {
      observer.disconnect()
      observeDOM(cartItems, function () {
        cartItems.classList.add('pointer-events-none')
        checkQuotes()
        setTimeout(function () {
          cartItems.classList.remove('pointer-events-none')
        }, 500)
      })
    }
  })

  observer.observe(document.body, {
    childList: true,
    subtree: true,
  })

  const fetchSettings = function () {
    const rootPath =
      window.vtex.renderRuntime.rootPath !== undefined
        ? window.vtex.renderRuntime.rootPath
        : ''

    const ts = new Date().getTime()

    $.ajax({
      url: `${rootPath}/_v/private/b2b-checkout-settings/${
        isWorkspace() ? `?v=${ts}` : ''
      }`,
    }).then(function (response) {
      if (Object.keys(response).length === 0) {
        window.sessionStorage.removeItem('b2b-checkout-settings')

        return
      }

      response.time = new Date().toISOString()

      if (
        window.vtexjs &&
        window.vtexjs.checkout &&
        window.vtexjs.checkout.orderForm
      ) {
        response.email =
          window.vtexjs.checkout.orderForm.clientProfileData.email
      }

      window.sessionStorage.setItem(
        'b2b-checkout-settings',
        JSON.stringify(response)
      )
      settings = response
      handleSettings()
    })
  }

  // Wait until it have the vtex runtime to call the functions
  checkVtex = setInterval(function () {
    if (window.vtex !== undefined && window.vtex.renderRuntime !== undefined) {
      clearInterval(checkVtex)
      if (isWorkspace() || !settings) {
        fetchSettings()
      } else {
        handleSettings()
      }
    }
  }, 500)

  const initialize = function () {
    const message = window.sessionStorage.getItem('message')

    if (settings && settings.permissions) {
      applyPermissions(settings.permissions)
    }

    if (message) {
      $(window).trigger('addMessage.vtex', {
        type: 'info',
        id: message,
        content: {
          title: getTranslation().messages[message].title,
          detail: getTranslation().messages[message].detail,
        },
      })
      window.sessionStorage.removeItem('message')
    }
  }

  $(window).on('hashchange', () => initialize())
})()

```


[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 b2b-checkout-settings/checkout-ui-custom/checkout-confirmation-custom.js from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```javascript
// WARNING: THE USAGE OF CUSTOM SCRIPTS IS NOT SUPPORTED. VTEX IS NOT LIABLE FOR ANY DAMAGES THIS MAY CAUSE.
// THIS MAY BREAK YOUR STORE AND STOP SALES. IN CASE OF ERRORS, PLEASE DELETE THE CONTENT OF THIS SCRIPT.

```


[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 b2b-checkout-settings/checkout-ui-custom/checkout5-custom.js from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```javascript
// WARNING: THE USAGE OF CUSTOM SCRIPTS IS NOT SUPPORTED. VTEX IS NOT LIABLE FOR ANY DAMAGES THIS MAY CAUSE. THIS MAY BREAK YOUR STORE AND STOP SALES. IN CASE OF ERRORS, PLEASE DELETE THE CONTENT OF THIS SCRIPT.

```


[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 b2b-checkout-settings/checkout-ui-custom/checkout6-custom.css from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```css
.pointer-events-none {
  pointer-events: none;
}
.b2b-purchase-order-number {
  margin-bottom: 15px;
}
.b2b-purchase-order-number input[type='text'] {
  height: 30px;
  line-height: 30px;
  max-height: initial;
  display: inline-block;
  padding: 0px 10px;
  border-radius: 4px;
  border: 1px solid #cbcbcb;
  outline: initial;
  font-family: 'Roboto', sans-serif;
  box-sizing: border-box;
  width: 100%;
}
.b2b-purchase-order-number input[type='text']:focus {
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(0, 0, 0, 0.4);
}

body.can-checkout .client-profile-data a.link-box-edit,
body.can-checkout button.vtex-omnishipping-1-x-buttonEditAddress,
body.can-checkout button.vtex-omnishipping-1-x-buttonCreateAddress,
body.can-checkout .orderform-template-holder #payment-data .payment-group-item {
  display: none !important;
}

body.change-profile .client-profile-data a.link-box-edit,
body.edit-shipping button.vtex-omnishipping-1-x-buttonEditAddress,
body.add-shipping button.vtex-omnishipping-1-x-buttonCreateAddress,
body.can-checkout
  .orderform-template-holder
  #payment-data
  .payment-group-item[data-b2b-allowed='true'] {
  display: block !important;
}

.btn-b2b-primary {
  margin: 10px 0;
  width: 100%;
}

.item-disabled {
  pointer-events: none;
  opacity: 0.5;
}

.v-custom-payment-item-wrap {
  border: none !important;
}
.v-custom-payment-item-wrap.active {
  border: 1px solid !important;
}

```


[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 b2b-checkout-settings/admin/navigation.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
[
  {
    "section": "storeSetup",
    "titleId": "admin/b2bCheckoutSettings.navigation.title",
    "path": "/admin/b2b-checkout-settings/"
  },
  {
    "section": "storeSettings",
    "subSection": "storeFront",
    "adminVersion": 4,
    "subSectionItems": [
      {
        "labelId": "admin/b2bCheckoutSettings.navigation.title",
        "path": "/admin/b2b-checkout-settings/"
      }
    ]
  }
]

```


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

[User] Show me the implementation of b2b-checkout-settings/admin/routes.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin.app.b2b-checkout-settings": {
    "component": "B2BCheckoutAdmin",
    "path": "/admin/app/b2b-checkout-settings"
  }
}

```


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

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

[Assistant]
Here's the implementation:

```markdown
# B2B Checkout Settings

> ℹ The **B2B Checkout Settings** app is part of VTEX’s [B2B Suite](https://developers.vtex.com/vtex-developer-docs/docs/vtex-b2b-suite) solution, a collection of apps that allow stores to manage organizations, storefront roles and permissions, and checkout settings for B2B commerce relationships. We recommend that you use it alongside the other apps in this suite for all functionalities to work as expected.

In B2B commerce, it is often necessary to provide customized options during checkout, such as:

* Making specific payment methods available for each organization or cost center.
* Providing pre-filled addresses.
* Including a purchase order number in the order.
* Offering the option to create an order quote before making an actual purchase.

The **B2B Checkout Settings** app works alongside other **B2B Suite** apps to extend the checkout experience for users who are members of organizations, adding all the above possibilities to the checkout page.

## Before you start

First, make sure you have the [VTEX IO CLI (Command Line Interface)](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-vtex-io-cli-install) installed in your machine.

To use **B2B Checkout Settings**, you must have the [B2B Organizations](https://developers.vtex.com/vtex-developer-docs/docs/vtex-b2b-organizations) app installed in your store, which will enable you to group B2B users into organizations, with their own assigned payment methods, price tables, product collections, and cost centers.

You must also have the [Storefront Permissions](https://developers.vtex.com/vtex-developer-docs/docs/vtex-storefront-permissions) app installed – it allows you to grant specific storefront roles for B2B users in an organization. See the **Storefront Permissions** app documentation for information on the available roles and how to customize their permissions.

## Installation

You can install this app by running `vtex install vtex.b2b-checkout-settings` in your terminal, using the [VTEX IO CLI](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-vtex-io-cli-installation-and-command-reference).

After this command, the app will be installed in your VTEX Admin, and B2B store administrators can access it on **Store Setup** > **B2B Checkout Settings**.

## How it works

Considering B2B stores often need similar customizations, **B2B Checkout Settings** provides a ready-to-use customized checkout page for B2B scenarios.

Once **B2B Checkout Settings** is installed in your account, every script contained in its [`checkout-ui-custom` folder](https://github.com/vtex-apps/b2b-checkout-settings/tree/master/checkout-ui-custom) will be automatically linked to your store. The app will customize your checkout page with the functionalities described below. You will also be able to [configure](#configuration) the app on **Store Setup** > **B2B Checkout Settings**.

> ℹ The behavior of the checkout page in VTEX stores is customizable through JavaScript code. In case you need additional customization, we recommend that you use [Checkout UI Custom](https://apps.vtex.com/vtex-checkout-ui-custom/p) if you prefer using the VTEX Admin interface or [Checkout UI Settings](https://developers.vtex.com/vtex-developer-docs/docs/vtex-checkout-ui-settings) if you prefer a code-only option.

### Restricted access to checkout

This app automatically checks users’ roles within the organization by communicating with the **B2B Organizations** app, and validates if the user has the required permissions to access checkout, by communicating with the Storefront Permissions app.

By default, users with any storefront role can access checkout, except for users with the **Organization Buyer** role. Any attempt to proceed to checkout without the required permission will result in a notification with the following message: _You don’t have access to the checkout_.

Note that if you have [Storefront Permissions UI](https://developers.vtex.com/vtex-developer-docs/docs/vtex-storefront-permissions-ui) installed, you can customize these permissions on the VTEX Admin by accessing **Account Settings > Storefront Permissions**.

### Cost Center addresses

The **B2B Checkout Settings** app communicates with the **B2B Organizations** app and automatically lists the [Cost Center addresses](https://developers.vtex.com/vtex-developer-docs/docs/vtex-b2b-organizations#cost-center-details) associated with the user during checkout:

| ![cost-center-details-addresses](https://raw.githubusercontent.com/vtex-apps/b2b-checkout-settings/master/docs/images/cost-center-details-addresses.png) | ![shipping](https://raw.githubusercontent.com/vtex-apps/b2b-checkout-settings/master/docs/images/shipping.png) |
|-|-|
| **Cost Center Details** page, displaying two options of addresses associated with the cost center in question | Checkout page for an user associated with this organization and cost center |

### Purchase order number field

A purchase order (PO) is a commercial agreement between a buyer company and a B2B store, authorizing the payment for products or services to be delivered in the future within a specific time frame.

Having a purchase order number allows B2B customers to pay for authorized purchases by referencing this number. The purchase order is authorized and issued in advance by the company that is making the purchase.

Using **B2B Checkout Settings**, it is possible to enable an optional **Reference or PO Number** field for customers to insert this information during the checkout.

![purchase-order](https://raw.githubusercontent.com/vtex-apps/b2b-checkout-settings/master/docs/images/purchase-order.png)

See the [Configuration](#configuration) section to understand how to enable or disable this button.

## Configuration

To change app settings, in the VTEX Admin go to **Store Setup** > **B2B Checkout Settings**.

![b2b-checkout-settings](https://raw.githubusercontent.com/vtex-apps/b2b-checkout-settings/master/docs/images/b2b-checkout-settings.png)

You can use the toggle button to activate or deactivate the available settings:

* **Show Purchase Order Number Field:** enabling this will add the **Reference or PO Number** input field to the checkout page. This will allow users to insert a purchase order number during checkout.
* **Show 'Create a Quote' Button:** enabling this will add the `Create a Quote` button to checkout, which allows users to create a quote using the current contents of their cart.

> ⚠ You should only enable the `Create a Quote` button if your store has the [B2B Quotes](https://github.com/vtex-apps/b2b-quotes) app installed. Check the **B2B Quotes** app documentation for more information on how order quotes work.

```


[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 b2b-checkout-settings/graphql/schema.graphql from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```graphql
type Query {
  appSettings: Settings @cacheControl(scope: PUBLIC, maxAge: SHORT)
}

type Mutation {
  saveAppSettings(settings: SettingsInput!): Settings
    @withAdminAccess
    @cacheControl(scope: PRIVATE)
}

type Settings {
  showPONumber: Boolean
  hasPONumber: Boolean
  showQuoteButton: Boolean
}

input SettingsInput {
  showPONumber: Boolean!
  hasPONumber: Boolean!
  showQuoteButton: Boolean!
}

```


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

[User] Show me the implementation of b2b-checkout-settings/graphql/directives.graphql from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```graphql
directive @withAdminAccess on FIELD | FIELD_DEFINITION

```


[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 b2b-checkout-settings/vtex.storefront-permissions/configuration.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "B2B Checkout Settings",
  "features": [
    {
      "label": "Can change profile",
      "value": "change-profile",
      "roles": ["store-admin", "sales-admin", "sales-manager"]
    },
    {
      "label": "Can add shipping",
      "value": "add-shipping",
      "roles": [
        "store-admin",
        "sales-admin",
        "sales-manager",
        "sales-representative",
        "customer-admin",
        "customer-approver"
      ]
    },
    {
      "label": "Can checkout",
      "value": "can-checkout",
      "roles": [
        "store-admin",
        "sales-admin",
        "sales-manager",
        "sales-representative",
        "customer-admin",
        "customer-approver"
      ]
    }
  ]
}

```


[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 b2b-checkout-settings/node/service.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "stack": "nodejs",
  "memory": 1024,
  "ttl": 300,
  "timeout": 60,
  "cpu": {
    "type": "shared",
    "value": 5,
    "scalingPercentage": 20
  },
  "minReplicas": 8,
  "maxReplicas": 80,
  "workers": 1,
  "routes": {
    "settings": {
      "path": "/_v/private/b2b-checkout-settings/",
      "public": true
    }
  }
}

```


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

[User] Show me the implementation of b2b-checkout-settings/node/typings.d.ts from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface ReqContext {
  account: string
  workspace: string
  authToken: string
  region: string
  production: boolean
  userAgent: string
}

interface Logger {
  log(content: string, level: LogLevel, details?: any): PromiseLike<void>
}

interface OrderFormConfiguration {
  paymentConfiguration?: PaymentConfiguration
  taxConfiguration?: TaxConfiguration
  minimumQuantityAccumulatedForItems?: number
  decimalDigitsPrecision?: number
  minimumValueAccumulated?: number
  apps?: [App]
  allowMultipleDeliveries?: boolean
  allowManualPrice?: boolean
  maxIntOfWhiteLabelSellers?: number
  maskFirstPurchaseData?: boolean
  recaptchaValidation?: boolean
}

interface OperationState {
  orderFormId: string
  ctx: ReqContext
  data?: OperationData
  logger: Logger
}

interface OperationData {
  orderForm?: any
  userProfileId: string
  cookie: string
}

type ProcessPaymentStep = (
  state: OperationState,
  next: () => Promise<void>
) => Promise<void>

type LogLevel = 'info' | 'error' | 'warning'

type Timings = { [middleware: string]: [number, number] }

declare module '*.json' {
  const value: any
  export default value
}

interface OrganizationInput {
  name: string
  b2bCustomerAdmin: B2BCustomerInput
  defaultCostCenter: DefaultCostCenterInput
}

interface B2BCustomerInput {
  firstName: string
  lastName: string
  email: string
}

interface DefaultCostCenterInput {
  name: string
  address: AddressInput
}

interface CostCenterInput {
  name: string
  addresses: AddressInput[]
}

interface AddressInput {
  addressId: string
  addressType: string
  postalCode: string
  country: string
  receiverName: string
  city: string
  state: string
  street: string
  number: string
  complement: string
  neighborhood: string
  geoCoordinates: [number]
}

interface OrganizationRequest {
  name: string
  defaultCostCenter: DefaultCostCenterInput
  b2bCustomerAdmin: string
  status: string
  created: string
}

interface Organization {
  id: string
  name: string
  costCenters: string[]
  status: string
  created: string
}

interface CostCenter {
  id: string
  name: string
  organization: string
  addresses: any[]
}

interface UserArgs {
  id?: string
  roleId: string
  userId?: string
  orgId?: string
  costId?: string
  clId?: string
  canImpersonate?: boolean
  name: string
  email: string
}

```


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

[User] Show me the implementation of b2b-checkout-settings/node/package.json from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "vtex.b2b-organizations",
  "version": "3.1.0",
  "dependencies": {
    "@vtex/api": "6.50.1",
    "atob": "^2.1.2",
    "co-body": "^6.0.0",
    "graphql": "^14.5.0",
    "graphql-tools": "^4.0.6",
    "jsonwebtoken": "^8.5.0",
    "qs": "^6.9.4",
    "ramda": "^0.25.0"
  },
  "devDependencies": {
    "@ngneat/falso": "^6.4.0",
    "@types/atob": "^2.1.2",
    "@types/bluebird": "^3.5.25",
    "@types/co-body": "0.0.3",
    "@types/graphql": "^14.5.0",
    "@types/jest": "27.4.1",
    "@types/jsonwebtoken": "^8.5.0",
    "@types/node": "^12.12.21",
    "@types/ramda": "types/npm-ramda#dist",
    "@vtex/prettier-config": "^0.3.1",
    "@vtex/tsconfig": "^0.6.0",
    "jest": "27.5.1",
    "ts-jest": "^27.1.4",
    "ts-node": "^10.9.1",
    "tslint": "^5.12.0",
    "tslint-config-prettier": "^1.18.0",
    "tslint-config-vtex": "^2.1.0",
    "typescript": "3.9.7",
    "vtex.b2b-organizations-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.b2b-organizations-graphql@0.9.2/public/@types/vtex.b2b-organizations-graphql",
    "vtex.graphql-server": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.graphql-server@1.67.0/public/_types/react",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.0/public/@types/vtex.styleguide"
  },
  "scripts": {
    "lint": "tsc --noEmit && tslint -c tslint.json './**/*.ts'",
    "test": "jest"
  }
}

```