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

[User] Show me the implementation of starter.store-react-components/pages/package.json from the starter.store-react-components VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "pages",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build index.html"
  },
  "dependencies": {
    "react-app-polyfill": "^2.0.0"
  },
  "alias": {
    "react": "../node_modules/react",
    "react-dom": "../node_modules/react-dom/profiling",
    "scheduler/tracing": "../node_modules/scheduler/tracing-profiling"
  },
  "devDependencies": {
    "@types/react": "^16.9.11",
    "@types/react-dom": "^16.8.4",
    "parcel": "^1.12.3",
    "typescript": "^3.4.5"
  },
  "resolutions": {
    "@babel/preset-env": "7.13.8"
  }
}

```


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

[User] Show me the implementation of starter.store-react-components/src/index.tsx from the starter.store-react-components VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';

import { Hello as HelloComponent, HelloProps } from './components/Hello';
import { Configuration } from './utils/configuration';

const client = new ApolloClient({
  uri: Configuration.serverUrl,
  cache: new InMemoryCache(),
});

export { Thing } from './components/Things';

export function Hello(helloProps: HelloProps) {
  return (
    <ApolloProvider client={client}>
      <HelloComponent
        name={helloProps.name}
        backgroundColor={helloProps.backgroundColor}
      />
    </ApolloProvider>
  );
}

```


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

[User] Show me the implementation of starter.store-react-components/src/config.json from the starter.store-react-components VTEX app.

[Assistant]
Here's the implementation:

```json
{
    "appBackendBaseUrl": {
        "localServer": "http://localhost:8080",
        "development": "https://vtex-app-poc-backend.vtex.io",
        "production": "https://vtex-app-poc-backend.vtex.io"
    }
}

```


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

[User] Show me the implementation of starter.store-react-components/src/utils/configuration.ts from the starter.store-react-components VTEX app.

[Assistant]
Here's the implementation:

```typescript
import * as configFile from '../config.json';
interface Configuration {
  serverUrl: string;
}

function getServerBaseUrl(): string {
  if (process.env.USE_LOCAL_SERVER === 'true') {
    return configFile.appBackendBaseUrl.localServer;
  } else {
    return configFile.appBackendBaseUrl[process.env.NODE_ENV];
  }
}

let config: Configuration = {
  serverUrl: `${getServerBaseUrl()}/graphql`,
};

export const Configuration = config;

```


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

[User] Show me the implementation of starter.store-react-components/src/components/Hello.tsx from the starter.store-react-components VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react';
import { useQuery, gql } from '@apollo/client';

const HELLO_QUERY = gql`
  query Hello {
    hello
  }
`;
export interface HelloProps {
  name: string;
  backgroundColor?: string;
}

export function Hello({ name, backgroundColor = '#db1457' }: HelloProps) {
  const { loading, error, data } = useQuery(HELLO_QUERY);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return (
    <div
      style={{
        backgroundColor,
        padding: '10px',
        color: 'white',
        fontSize: '2em',
      }}
    >
      {data.hello},{' '}
      <span>
        <u>{name}</u>
      </span>
      !
    </div>
  );
}

```


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

[User] Show me the implementation of starter.store-react-components/src/components/Things.tsx from the starter.store-react-components VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, HTMLAttributes, ReactChild } from 'react';

export interface Props extends HTMLAttributes<HTMLDivElement> {
  /** custom content, defaults to 'the snozzberries taste like snozzberries' */
  children?: ReactChild;
}

// Please do not use types off of a default export module or else Storybook Docs will suffer.
// see: https://github.com/storybookjs/storybook/issues/9556
/**
 * A custom Thing component. Neat!
 */
export const Thing: FC<Props> = ({ children }) => {
  return <div>{children}</div>;
};

```


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

[User] Show me the implementation of multisite-segment-results/messages/pt.json from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.multisite.title"                     : "Multisitio",
  "editor.multisite.description"               : "Componente de Multisitio",
  "editor.multisite.navigation.name1"          : "Primeiro nome de navegação",
  "editor.multisite.navigation.default"        : "Nome",
  "editor.multisite.navigation.value1"         : "Primeiro parâmetro ID",
  "editor.multisite.navigation.name2"          : "Segundo nome de navegação",
  "editor.multisite.navigation.value2"         : "Segundo parâmetro ID",
  "editor.multisite.navigation.name3"          : "Terceiro nome de navegação",
  "editor.multisite.navigation.value3"         : "Terceiro parâmetro ID",
  "editor.image.src.title"                     : "Src",
  "editor.image.alt.title"                     : "Alt",
  "editor.image.title.title"                   : "Título"
}

```


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

[User] Show me the implementation of multisite-segment-results/messages/en.json from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.multisite.title"                     : "Multisite",
  "editor.multisite.description"               : "Multisite component",
  "editor.multisite.navigation.name1"          : "First navigation name",
  "editor.multisite.navigation.default"        : "Name",
  "editor.multisite.navigation.value1"         : "First parameter ID",
  "editor.multisite.navigation.name2"          : "Second navigation name",
  "editor.multisite.navigation.value2"         : "Second parameter ID",
  "editor.multisite.navigation.name3"          : "Third navigation name",
  "editor.multisite.navigation.value3"         : "Third parameter ID",
  "editor.image.src.title"                     : "Src",
  "editor.image.alt.title"                     : "Alt",
  "editor.image.title.title"                   : "Title"
}
```


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

[User] Show me the implementation of multisite-segment-results/messages/context.json from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.multisite.title"                     : "Multisite",
  "editor.multisite.description"               : "Multisite component",
  "editor.multisite.navigation.name1"          : "First navigation name",
  "editor.multisite.navigation.default"        : "Name",
  "editor.multisite.navigation.value1"         : "First parameter ID",
  "editor.multisite.navigation.name2"          : "Second navigation name",
  "editor.multisite.navigation.value2"         : "Second parameter ID",
  "editor.multisite.navigation.name3"          : "Third navigation name",
  "editor.multisite.navigation.value3"         : "Third parameter ID",
  "editor.image.src.title"                     : "Src",
  "editor.image.alt.title"                     : "Alt",
  "editor.image.title.title"                   : "Title"
}
```


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

[User] Show me the implementation of multisite-segment-results/messages/es.json from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.multisite.title"                     : "Multisitio",
  "editor.multisite.description"               : "Componente Multisitio",
  "editor.multisite.navigation.name1"          : "Primer nombre de la navegación",
  "editor.multisite.navigation.default"        : "Nombre",
  "editor.multisite.navigation.value1"         : "Primer ID de parametro",
  "editor.multisite.navigation.name2"          : "Segundo nombre de la navegación",
  "editor.multisite.navigation.value2"         : "Segundo ID de parametro",
  "editor.multisite.navigation.name3"          : "Tercer nombre de la navegación",
  "editor.multisite.navigation.value3"         : "Tercer ID de parametro",
  "editor.image.src.title"                     : "Src",
  "editor.image.alt.title"                     : "Alt",
  "editor.image.title.title"                   : "Título"
}
```


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

[User] Show me the implementation of multisite-segment-results/docs/README.md from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```markdown
# VTEX Recommendation Resolver

This app is an implementation of the VTEX recommendation protocol for recommendation shelves that is defined by the schema GraphQL [recommendation-graphql](https://github.com/vtex-apps/recommendation-graphql).

```


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

[User] Show me the implementation of multisite-segment-results/node/service.json from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "stack": "nodejs",
  "memory": 256,
  "minReplicas": 3,
  "workers": 1,
  "ttl": 60
}

```


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

[User] Show me the implementation of multisite-segment-results/node/package.json from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "dependencies": {
    "graphql": "^14.5.8",
    "graphql-tools": "^4.0.6",
    "vtex.search-segment-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-segment-graphql@0.1.0/public"
  },
  "devDependencies": {
    "@types/atob": "^2.1.2",
    "@types/node": "^12.0.0",
    "@vtex/api": "6.45.12",
    "@vtex/prettier-config": "^0.1.3",
    "eslint": "^6.8.0",
    "eslint-config-vtex": "^12.2.1",
    "husky": "^4.2.0",
    "lint-staged": "^10.0.2",
    "prettier": "^1.19.1",
    "typescript": "3.9.7",
    "vtex.css-handles": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles",
    "vtex.messages": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.messages@1.65.0/public/@types/vtex.messages",
    "vtex.native-types": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.native-types@0.8.0/public/@types/vtex.native-types",
    "vtex.search-segment-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-segment-graphql@0.1.1/public/@types/vtex.search-segment-graphql",
    "vtex.search-session": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-session@0.2.10/public/_types/react",
    "vtex.store-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.152.0/public/@types/vtex.store-graphql",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.1/public/@types/vtex.styleguide"
  },
  "version": "0.1.4"
}

```


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

[User] Show me the implementation of multisite-segment-results/node/global.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```typescript
import {
  IOContext,
  ParamsContext,
  RecorderState,
  ServiceContext,
  SegmentData,
} from '@vtex/api'

import { Clients } from './clients/index'

declare global {
  type Context = ServiceContext<Clients, RecorderState, CustomContext>

  interface CustomContext extends ParamsContext {
    vtex: CustomIOContext
  }
  interface CustomIOContext extends IOContext {
    segment?: SegmentData
  }

  interface SearchSegmentInput {
    userEmail?: string
    isAuthenticated?: boolean
    selectedFacets?: SelectedFacet[]
  }

  interface SelectedFacet {
    key: string
    value: 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 multisite-segment-results/node/index.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { Service, RecorderState, ParamsContext } from '@vtex/api'
import schema from 'vtex.search-segment-graphql/graphql'

import { Clients, clients } from './clients'
import { queries as segmentSearchQueries } from './resolvers/segmentSearch'

export default new Service<Clients, RecorderState, ParamsContext>({
  clients,
  graphql: {
    resolvers: {
      Query: {
        ...segmentSearchQueries,
      },
    },
    schema,
  },
})

```


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

[User] Show me the implementation of multisite-segment-results/react/Multisite.tsx from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useEffect } from 'react';
import NavigationLink from './components/NavegationLink';
import { useCssHandles } from 'vtex.css-handles';

interface MultisiteProps {
  src1: string,
  alt1: string,
  title1: string,
  idValue1: number,
  src2: string,
  alt2: string,
  title2: string,
  idValue2: number,
  src3: string,
  alt3: string,
  title3: string,
  idValue3: number
}

const SetCssClass = (el: any, cssClass: string) => {
  el?.classList.add(cssClass);
}

const SetActiveClassOnReload = () =>{
  const activeBtn = localStorage.getItem("btnActiveElement") || "";
  const el = document.getElementById(activeBtn);
  const activeClass = localStorage.getItem("btnActiveClass") || "";
  SetCssClass(el, activeClass);
  localStorage.removeItem("btnActiveElement");
  localStorage.removeItem("btnActiveClass");
}

const Multisite: StorefrontFunctionComponent<MultisiteProps> = ({
    src1,
    alt1,
    title1,
    idValue1,

    src2,
    alt2,
    title2,
    idValue2,

    src3,
    alt3,
    title3,
    idValue3,

  }) => {

  useEffect(() => {
    SetActiveClassOnReload();
  }, []);

  const CSS_HANDLES = [
    'multisiteSegmentatitionResultsContainer',
  ]

  const handles = useCssHandles(CSS_HANDLES)

  return (
    <div className={`${handles.multisiteSegmentatitionResultsContainer} flex ph7 pv2 items-center`}>

      <NavigationLink
        src={src1}
        alt={alt1}
        title={title1}
        idValue={idValue1}
        >
      </NavigationLink>

      <NavigationLink
        src={src2}
        alt={alt2}
        title={title2}
        idValue={idValue2}
        >
      </NavigationLink>

      <NavigationLink
        src={src3}
        alt={alt3}
        title={title3}
        idValue={idValue3}
        >
      </NavigationLink>

    </div>
  )
}

Multisite.schema = {
  title: 'editor.multisite.title',
  description: 'editor.multisite.description'
}

export default Multisite

```


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

[User] Show me the implementation of multisite-segment-results/react/ConditionalSegmentBlock.tsx from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FC } from "react";
import React from "react";
// import { useRuntime } from "vtex.render-runtime";
import type { Runtime } from './typings/global';
import atob from 'atob';

type Props = {
  segmentValue: number;
  isDefault: boolean
};

declare let window: {
  __RUNTIME__: Runtime
};

const ConditionalSegmentBlock: FC<Props> = ({
  segmentValue,
  isDefault,
  children,
}) => {
  //obtener de la cookie vtex_segment
  const segmentParameter = 'productClustersId';
  const segmentToken = window?.__RUNTIME__?.segmentToken;
  const defaultBanner = isDefault;
  let selectedSegment = <>{defaultBanner && children}</>;

  if (segmentToken) {
    const segmentTokenInfo = JSON.parse(atob(segmentToken));

    if (segmentTokenInfo && segmentTokenInfo.facets) {
      let segmentFacet = (segmentTokenInfo.facets).split("=");
      let facetParameter = segmentFacet[0];
      let facetParameterId = segmentFacet[1].split(";")[0];
      const condition = segmentValue == facetParameterId;

      if (segmentParameter === facetParameter) {
        selectedSegment = <>{condition && children}</>;
      }
    }

  }

  return selectedSegment;
};

export default ConditionalSegmentBlock;

```


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

[User] Show me the implementation of multisite-segment-results/react/package.json from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "dependencies": {
    "@vtex/css-handles": "^1.0.0",
    "atob": "^2.1.2",
    "classnames": "^2.2.6",
    "ramda": "^0.26.1",
    "react": "^16.12.0",
    "react-apollo": "^3.1.3",
    "react-dom": "^16.12.0",
    "react-intl": "^3.12.0"
  },
  "devDependencies": {
    "@apollo/react-testing": "^3.1.3",
    "@types/atob": "^2.1.2",
    "@types/classnames": "^2.2.7",
    "@types/jest": "^24.0.18",
    "@types/node": "^12.7.5",
    "@types/prop-types": "^15.7.0",
    "@types/ramda": "^0.26.5",
    "@types/react": "^16.9.31",
    "@vtex/test-tools": "^3.3.2",
    "@vtex/tsconfig": "^0.4.4",
    "apollo-cache-inmemory": "^1.6.5",
    "apollo-client": "^2.5.1",
    "graphql": "^14.6.0",
    "typescript": "3.9.7",
    "vtex.css-handles": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles",
    "vtex.messages": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.messages@1.65.0/public/@types/vtex.messages",
    "vtex.native-types": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.native-types@0.8.0/public/@types/vtex.native-types",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.4/public/@types/vtex.render-runtime",
    "vtex.search-segment-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-segment-graphql@0.1.1/public/@types/vtex.search-segment-graphql",
    "vtex.search-session": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-session@0.2.10/public/_types/react",
    "vtex.store-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.152.0/public/@types/vtex.store-graphql",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.1/public/@types/vtex.styleguide"
  }
}

```


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

[User] Show me the implementation of multisite-segment-results/store/contentSchemas.json from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```json
{
    "definitions": {
        "Multisite": {
            "type": "object",
            "properties": {
                "src1": {
                    "title": "admin/editor.image.src.title",
                    "$ref": "app:vtex.native-types#/definitions/url",
                    "default": "",
                    "widget": {
                      "ui:widget": "image-uploader"
                    }
                },
                "alt1": {
                    "title": "admin/editor.image.alt.title",
                    "$ref": "app:vtex.native-types#/definitions/text",
                    "default": ""
                },
                "title1": {
                    "title": "admin/editor.image.title.title",
                    "description": "admin/editor.image.title.description",
                    "$ref": "app:vtex.native-types#/definitions/text",
                    "default": ""
                },
                "idValue1": {
                    "title": "editor.multisite.navigation.value1",
                    "type": "number",
                    "default": null
                },
                "src2": {
                    "title": "admin/editor.image.src.title",
                    "$ref": "app:vtex.native-types#/definitions/url",
                    "default": "",
                    "widget": {
                      "ui:widget": "image-uploader"
                    }
                },
                "alt2": {
                    "title": "admin/editor.image.alt.title",
                    "$ref": "app:vtex.native-types#/definitions/text",
                    "default": ""
                },
                "title2": {
                    "title": "admin/editor.image.title.title",
                    "description": "admin/editor.image.title.description",
                    "$ref": "app:vtex.native-types#/definitions/text",
                    "default": ""
                },
                "idValue2": {
                    "title": "editor.multisite.navigation.value2",
                    "type": "number",
                    "default": null
                },
                "src3": {
                    "title": "admin/editor.image.src.title",
                    "$ref": "app:vtex.native-types#/definitions/url",
                    "default": "",
                    "widget": {
                      "ui:widget": "image-uploader"
                    }
                },
                "alt3": {
                    "title": "admin/editor.image.alt.title",
                    "$ref": "app:vtex.native-types#/definitions/text",
                    "default": ""
                },
                "title3": {
                    "title": "admin/editor.image.title.title",
                    "description": "admin/editor.image.title.description",
                    "$ref": "app:vtex.native-types#/definitions/text",
                    "default": ""
                },
                "idValue3": {
                    "title": "editor.multisite.navigation.value3",
                    "type": "number",
                    "default": null
                }
            }
        },
        "ConditionalSegmentBlock": {
            "type": "object",
            "properties": {
                "segmentValue": {
                    "title": "segmentValue",
                    "type": "number",
                    "default": null
                },
                "isDefault": {
                    "title": "isDefault",
                    "type": "boolean",
                    "default": false
                }
            }
        }
    }
}
```


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

[User] Show me the implementation of multisite-segment-results/store/interfaces.json from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "multisite": {
    "component": "Multisite",
    "content": {
      "$ref": "#/definitions/Multisite"
    }
  },
  "conditionalSegmentBlock": {
    "component": "ConditionalSegmentBlock",
    "composition": "children",
    "content": {
      "$ref": "#/definitions/ConditionalSegmentBlock"
    }
  }
}
```


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

[User] Show me the implementation of multisite-segment-results/node/clients/index.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

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

const MEDIUM_TIMEOUT_MS = 2 * 1000

export class Clients extends IOClients {
  // Add client example
  // public get myClient(): ClientType {
  //   return this.getOrSet('myClient', ClientType)
  // }
}

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

```


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

[User] Show me the implementation of multisite-segment-results/node/typings/global.d.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare const metrics

type GenericObject = Record<string, any>

```


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

[User] Show me the implementation of multisite-segment-results/node/resolvers/segmentSearch.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const queries = {

  searchSegment: async (
    __: unknown,
    args: SearchSegmentInput,
    context: Context
  ) => {

    const { parameterValue } = await context.clients.apps.getAppSettings(
      `${process.env.VTEX_APP_ID}`
    )
    const parameter = 'productClustersId';

    if(args.isAuthenticated === true){
      const selectedFacets = args.selectedFacets || [];
      if (selectedFacets.length > 0){
        return [{ key: selectedFacets[0].key, value: selectedFacets[0].value }];
      }
    }

    return [{ key: parameter, value: parameterValue }];

  }
}
```


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

[User] Show me the implementation of multisite-segment-results/react/typings/storefront.d.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

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

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

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

```


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

[User] Show me the implementation of multisite-segment-results/react/typings/vtex.render-runtime.d.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

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

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

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

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

  export const ExtensionPoint: ComponentType<ExtensionPointProps>

  interface ChildBlockProps {
    id: string
  }

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

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

```


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

[User] Show me the implementation of multisite-segment-results/react/typings/global.d.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```typescript
export interface Runtime {
  segmentToken: string
}

export interface TimeSplit {
  hours: string
  minutes: string
  seconds: string
}

type GenericObject = Record<string, any>

```


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

[User] Show me the implementation of multisite-segment-results/react/typings/css.d.ts from the multisite-segment-results 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 multisite-segment-results/react/typings/graphql.d.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

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

  const value: DocumentNode
  export default value
}

```


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

[User] Show me the implementation of multisite-segment-results/react/typings/vtex.styleguide.d.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

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

  export const Input: ComponentType<InputProps>

  interface InputProps {
    [key: string]: any
  }
}

```


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

[User] Show me the implementation of multisite-segment-results/react/utils/time.ts from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

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

const SECONDS_IN_MINUTE = 60
const SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE

const fillWithZero = (digits: number, number: number): string => {
  const filled = `${'0'.repeat(digits - 1)}${number}`

  return filled.slice(filled.length - digits)
}

export const parseTimeRemaining = (totalSeconds: number): TimeSplit => {
  const hours = Math.floor(totalSeconds / SECONDS_IN_HOUR)
  const minutes = Math.floor(
    (totalSeconds % SECONDS_IN_HOUR) / SECONDS_IN_MINUTE
  )

  const seconds = Math.floor(
    (totalSeconds % SECONDS_IN_HOUR) % SECONDS_IN_MINUTE
  )

  return {
    hours: fillWithZero(2, hours),
    minutes: fillWithZero(2, minutes),
    seconds: fillWithZero(2, seconds),
  }
}

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

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

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

export const getTwoDaysFromNow = () => {
  const today = new Date()

  today.setDate(today.getDate() + 2)

  return today.toISOString()
}

```


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

[User] Show me the implementation of multisite-segment-results/react/styles/styles.css from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```css
.navigationLink {
    border: 1px solid transparent;
    background-color: transparent;
    color: rgba(150, 150, 150, 0.322);
    text-decoration: none;
    margin-right: .5rem;
    padding: .5rem 1.5rem;
    width: 150px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.navigationLink:hover {
    border: 1px solid rgba(150, 150, 150, 0.322);
    cursor: pointer;
    transition: .3s all ease-in;
}

.active {
    border: 1px solid rgba(150, 150, 150, 0.322);
    color: rgba(44, 44, 44, 0.322);
    transition: .3s all ease-in;
}

.navigationLink img {
    width: 100%;
    height: auto;
}
```


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

[User] Show me the implementation of multisite-segment-results/react/components/NavegationLink.tsx from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react';
import { useState } from 'react';
import styles from '../styles/styles.css';
import LoadingSpinner from './LoadingSpinner';
// import LoadingSpinner from './component/LoadingSpinner';

interface NavigationLinkProps {
    src: string,
    alt: string,
    title: string,
    idValue: number,
}

const parameter = 'productClustersId';

const SetFacets = async(parameter: string, parameterValue: number, btn: string, activeClass: any) => {
  const data = {
    public: {
      facets: {
        value: `${parameter}=${parameterValue};`
      }
    }
  };

  fetch('/api/sessions', {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
      },
      body: JSON.stringify(data)
  })
  .then((response: any) => {
    response.json();
    SetLocalStorageBtnActiveClass(btn, activeClass);
    location.reload();
  });
}

const SetCssClassById = (id: string, cssClass: string) => {
  const el = document.getElementById(id);
  el?.classList.add(cssClass);
}

const SetLocalStorageBtnActiveClass = (btn: string, activeClass: string) =>{
  localStorage.setItem("btnActiveElement", btn);
  localStorage.setItem("btnActiveClass", activeClass);
}

const NavigationLink: StorefrontFunctionComponent<NavigationLinkProps> = ({src, alt, title, idValue}) => {

  const [loadingState, SetLoadingState] = useState(false);

  let content = loadingState ? <LoadingSpinner/> : <img src={src} alt={alt} /> ;

  return (
    <>
      <button
        id={`btn-${title}`}
        className={styles.navigationLink}
        onClick={() => {
          SetCssClassById(`btn-${title}`, styles.active);
          SetFacets(parameter, idValue, `btn-${title}`, styles.active);
          SetLoadingState(true);
        }}>
        {content}
      </button>
    </>
  )
}

export default NavigationLink
```


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

[User] Show me the implementation of multisite-segment-results/react/components/LoadingSpinner.tsx from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { Spinner } from 'vtex.styleguide'
import React from 'react'

export default function LoadingSpinner() {
  return (
    <div className="loading-container">
        <span className="dib c-muted-1">
            <Spinner color="currentColor" size={20} />
        </span>
    </div>
  )
}
```


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

[User] Show me the implementation of multisite-segment-results/react/graphql/productReleaseDate.graphql from the multisite-segment-results VTEX app.

[Assistant]
Here's the implementation:

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

```


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

[User] Show me the implementation of vtex-anaf/docs/anaf.css from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

```css
.corporate-info-box p.client-company-document {
    position: relative;
}

.corporate-info-box p.client-company-document .getCompanyInfo {
    position: absolute;
    height: 44px;
    right: 0;
    top: 20px;
    background: #b3f498;
    border: none;
    cursor: pointer;
    display: none;
    z-index: 9;
}

.cuiError {
    font-weight: 600;
    color: #cc0000;
}

.corporate-info-box {
    flex-direction: column;
}

.corporate-info-box .client-company-document {
    order: -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 vtex-anaf/docs/README.md from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

```markdown
# VTEX ANAF

### Installation Guide
- Open the VTEX App Store and install this app on your store, or run the following command on VTEX toolbelt:

> vtex install vtex.taxid-validation@0.x

### Check CUI

Make a new POST request to https://{{vendor}}.myvtex.com/anaf/validate-cui with the following body:

```
{
    "cui": "YOUR CUI HERE"
}
```

*If the CUI is invalid, the response code will be 500*

Response body example:
```
{
    "cod": 200,
    "message": "SUCCESS",
    "found": [
        {
            "cui": YOUR_CUI_HERE,
            "data": "2021-03-30",
            "denumire": "COMPANY NAME",
            "adresa": "COMPANY ADDRESS",
            "nrRegCom": "",
            "telefon": "",
            "fax": "",
            "codPostal": "",
            "act": "",
            "stare_inregistrare": "",
            "scpTVA": false,
            "data_inceput_ScpTVA": "",
            "data_sfarsit_ScpTVA": "",
            "data_anul_imp_ScpTVA": "",
            "mesaj_ScpTVA": "nu figureaza in registre ",
            "dataInceputTvaInc": "",
            "dataSfarsitTvaInc": "",
            "dataActualizareTvaInc": "",
            "dataPublicareTvaInc": "",
            "tipActTvaInc": "",
            "statusTvaIncasare": false,
            "dataInactivare": " ",
            "dataReactivare": " ",
            "dataPublicare": " ",
            "dataRadiere": " ",
            "statusInactivi": false,
            "dataInceputSplitTVA": "",
            "dataAnulareSplitTVA": "",
            "statusSplitTVA": false,
            "iban": ""
        }
    ],
    "notfound": []
}
```

If there is no company with the CUI you provide, the "denumire" and "adresa" fields will be blank.

# App Settings
1. Go to **Admin > Apps > My Apps > VTEX Anaf**
2. Fill up the form and press save.

Key listafirme.ro is optional. If you have licence on listafirme, put your api key thene.
If the request to ANAF fails, the application will make a new request to the list of companies

# Add Validation on checkout

1. Go to **Admin > Checkout > Code**
2. Create a new file `anaf.js`
3. Create a new file `anaf.css`
4. Copy the content from docs/anaf.js and paste it into your `anaf.js`
5. Copy the content from docs/anaf.css and paste it into your `anaf.css`
6. Go to checkout6-custom.js in admin and paste the following code

```
(function (document, tag) {
      var lockersTag = document.createElement(tag);
      var firstLockersTag = document.getElementsByTagName(tag)[0];
      lockersTag.src = "/files/anaf.js?" + Date.now();
      firstLockersTag.parentNode.insertBefore(lockersTag, firstLockersTag);

  $('head').append('<link rel="stylesheet" href="/files/anaf.css?'+ Date.now()+'" />');
  })(document, "script");
```

Now you can customize your `anaf.js` and `anaf.css` file as you want.

```


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

[User] Show me the implementation of vtex-anaf/docs/anaf.js from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

```javascript
const body = $('body');
vtexjs.checkout.getOrderForm().done((orderForm) => {
    getAnafSettings();
});
body.on('click', 'a#is-corporate-client, #client-profile-data .link-box-edit', function(){
    getAnafSettings();
}).on('keyup', '.corporate-info-box input#client-company-document', function(){
    if($(this).val()) {
        $('.getCompanyInfo').show();
    } else {
        $('.getCompanyInfo').hide();
    }
}).on('click', '.getCompanyInfo', function(e){
    e.preventDefault();
    const cui = $('.corporate-info-box input#client-company-document').val();
    validateCui(cui.replace(/[^0-9]/g, ''));

    return false;
});

async function validateCui(cui) {
    const requestBody = {
        cui
    }
    const response = await fetch(`/anaf/validate-cui`, {
        method: "POST",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody)
    });

    const company = await response.json();

    vtexjs.checkout.getOrderForm().done((orderForm) => {
        let clientProfileData = orderForm.clientProfileData
        clientProfileData.corporateName = company.name
        clientProfileData.tradeName = company.name
        clientProfileData.corporateDocument = cui
        clientProfileData.corporatePhone = company.phone
        clientProfileData.isCorporate = true
        vtexjs.checkout.sendAttachment(
            "clientProfileData",
            clientProfileData
        ).then(() => {
            if(company.hasOwnProperty('allowEdit') && company.allowEdit === false){
                disableInputs();
            }

            if(company.error){
                if(!$('.corporate-info-box p.client-company-document .cuiError').length) {
                    $('.corporate-info-box p.client-company-document').append('<p class="cuiError">CUI invalid</p>');
                }

            } else {
                if($('.corporate-info-box p.client-company-document .cuiError').length) {
                    $('.corporate-info-box p.client-company-document .cuiError').remove();
                }
            }

            if(!company.allowContinue && (company.error || !company.isActive)) {
                $("#go-to-shipping").hide();
            } else {
                $("#go-to-shipping").show();
            }
        })
    });
}

async function getAnafSettings() {
    $('label[for="client-company-document"]').html('CUI:');
    if(!$('.box-client-info-pj h5.corporate-title').hasClass('visible')) {
        $('.corporate-info-box').css('display', 'none');
    } else {
        $('.corporate-info-box').css('display', 'flex');
    }

    if(!$('.corporate-info-box .client-company-document .getCompanyInfo').length) {
        $('.corporate-info-box .client-company-document').append('<button class="getCompanyInfo">Preia</button>');
    }

    const settingsResponse = await fetch(`/anaf/get-settings`);
    const settings = await settingsResponse.json();

    if(!settings.allowEdit) {
        disableInputs();
    }

    if(!$('#client-company-name').val()) {
        const getUserResponse = await fetch(`/anaf/get-user`);
        const userResponse = await getUserResponse.json();
        console.log(userResponse);
    }
}

function disableInputs() {
    $('#client-company-name').prop('disabled', 'disabled');
    $('#client-company-nickname').prop('disabled', 'disabled');
}

```


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

[User] Show me the implementation of vtex-anaf/node/service.json from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "memory": 256,
  "ttl": 10,
  "timeout": 5000,
  "minReplicas": 2,
  "maxReplicas": 4,
  "routes": {
    "validateCUI": {
      "path": "/anaf/validate-cui",
      "public": true,
      "settingsType": "workspace"
    },
    "getSettings": {
      "path": "/anaf/get-settings",
      "public": true,
      "settingsType": "workspace"
    }
  }
}

```


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

[User] Show me the implementation of vtex-anaf/node/package.json from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "dependencies": {
    "axios": "^0.20.0",
    "co-body": "^6.0.0",
    "ramda": "^0.25.0",
    "@vtex/api": "6.44.0"
  },
  "devDependencies": {
    "@types/co-body": "^0.0.3",
    "@types/jest": "^24.0.18",
    "@types/node": "^12.0.0",
    "@types/ramda": "types/npm-ramda#dist",
    "@vtex/api": "6.44.0",
    "@vtex/test-tools": "^1.0.0",
    "tslint": "^5.14.0",
    "tslint-config-vtex": "^2.1.0",
    "typescript": "3.9.7"
  },
  "scripts": {
    "lint": "tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'"
  },
  "version": "0.0.7"
}

```


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

[User] Show me the implementation of vtex-anaf/node/index.ts from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

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

import { Clients } from './clients'
import { settings } from './middlewares/settings'
import { validateCUI } from './middlewares/validateCUI'

const TIMEOUT_MS = 5000
const memoryCache = new LRUCache<string, any>({ max: 5000 })

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

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

  interface State extends RecorderState {}
}

export default new Service({
  clients,
  routes: {
    getSettings: method({
      GET: settings,
    }),
    validateCUI: method({
      POST: validateCUI,
    }),
  },
})

```


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

[User] Show me the implementation of vtex-anaf/node/clients/anaf.ts from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

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

import { getCurrentDate } from '../utils/functions'

export default class Anaf extends ExternalClient {

    constructor(context: IOContext, options?: InstanceOptions) {
        super('', context, options)
    }

    public async validateCuiAnaf(body: any): Promise<any> {
        const postBody = [
            {
                cui: body.cui,
                data: getCurrentDate(),
            },
        ]

        return this.http.post(
            `http://webservicesp.anaf.ro/PlatitorTvaRest/api/v5/ws/tva`,
            postBody, {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'X-Vtex-Use-Https': true,
                },
            })
    }

    public async validateCuiListaFirme(key: any, body: any): Promise<any> {
        return this.http.post(
            `https://www.listafirme.ro/api/info-v1.asp?key=${key}&data=${JSON.stringify(body)}`,
            {}, {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'X-Vtex-Use-Https': 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 vtex-anaf/node/clients/index.ts from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

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

import Anaf from './anaf'

// Extend the default IOClients implementation with our own custom clients.
export class Clients extends IOClients {
  public get anaf() {
    return this.getOrSet('anaf', Anaf)
  }
}

```


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

[User] Show me the implementation of vtex-anaf/node/middlewares/settings.ts from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

```typescript

import {getSettings} from '../utils/helpers'

export async function settings(ctx: Context, next: () => Promise<any>) {

    const appSettings = await getSettings(ctx)

    const allowEdit = appSettings.allowEdit ? appSettings.allowEdit : false
    const allowContinue = appSettings.allowContinue ? appSettings.allowContinue : false

    const output = {
        allowContinue,
        allowEdit,
    }

    ctx.status = 200
    ctx.body = output

    await next()
}

```


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

[User] Show me the implementation of vtex-anaf/node/middlewares/validateCUI.ts from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

```typescript
import {json} from 'co-body'
import {getSettings} from '../utils/helpers'

export async function validateCUI(ctx: Context, next: () => Promise<any>) {

    const body = await json(ctx.req)
    const settings = await getSettings(ctx)

    const allowEdit = settings.allowEdit ? settings.allowEdit : false
    const allowContinue = settings.allowContinue ? settings.allowContinue : false
    const apiKeyListaFirme = settings.listaFirme ? settings.listaFirme : ''

    const {
        clients: {anaf: client},
    } = ctx

    let output = {
        address: '',
        allowContinue,
        allowEdit,
        cui: body.cui,
        error: false,
        errorMessage: '',
        isActive: false,
        name: '',
        nrRegCom: '',
        phone: '',
    }

    const response = await client.validateCuiAnaf(body)
    if (response.cod === 200 && response.found.length) {
        const company = response.found[0]
        output = {
            ...output,
            address: company.adresa,
            error: company.statusInactivi || !company.denumire,
            isActive: !company.statusInactivi,
            name: company.denumire,
            nrRegCom: company.nrRegCom,

            phone: company.telefon,
        }
    } else {
        if (apiKeyListaFirme) {
            const listaFirmeData = {
                Address: '',
                Mobile: '',
                Name: '',
                RegNo: '',
                Status: '',
                TaxCode: body.cui,
            }

            const responseListaFirme = await client.validateCuiListaFirme(apiKeyListaFirme, listaFirmeData)
            if (responseListaFirme.hasOwnProperty('error')) {
                output = {
                    ...output,
                    error: true,
                    errorMessage: responseListaFirme.error,
                }
            } else {
                output = {
                    ...output,
                    address: responseListaFirme.Address,
                    error: responseListaFirme.Status !== 'functiune',
                    errorMessage: responseListaFirme.Status !== 'functiune' ? 'Compania este inactiva' : '',
                    isActive: responseListaFirme.Status === 'functiune',
                    name: responseListaFirme.Name,
                    nrRegCom: responseListaFirme.RegNo,
                    phone: responseListaFirme.Mobile[0] ?? '',
                }
            }

        } else {
            output = {
                ...output,
                error: true,
                errorMessage: 'Couldn\'t get company info',
            }
        }
    }

    ctx.status = 200
    ctx.body = output

    await next()
}

```


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

[User] Show me the implementation of vtex-anaf/node/utils/helpers.ts from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

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

export const getSettings = (ctx: any) => {
    const apps = new Apps(ctx.vtex)

    return apps.getAppSettings(ctx.vtex.userAgent)
}

```


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

[User] Show me the implementation of vtex-anaf/node/utils/functions.ts from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

```typescript
export function getCurrentDate() {
    var d = new Date(),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2)
        month = '0' + month;
    if (day.length < 2)
        day = '0' + day;

    return [year, month, day].join('-');
}

```


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

[User] Show me the implementation of vtex-anaf/node/__tests__/simple.test.ts from the vtex-anaf VTEX app.

[Assistant]
Here's the implementation:

```typescript
// You can import your files here for testing them
//
// More info: https://github.com/sapegin/jest-cheat-sheet

describe('simpleTest', () => {
  it('one test case', async () => {
    expect(0.2 + 0.1).not.toBe(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 phone-field/docs/README.md from the phone-field VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Phone Field

Phone Field is a VTEX IO app that handles formatting and validation of phone numbers. It
includes an UI component that renders a text field with a listbox that contains the flag of
the country and the respective [country calling code](https://en.wikipedia.org/wiki/List_of_country_calling_codes).

<img width="405" alt="component screenshot USA" src="https://user-images.githubusercontent.com/10223856/76995145-306bba80-692e-11ea-9f3b-847627dfc49f.png">
<img width="405" alt="component screenshot Brazil" src="https://user-images.githubusercontent.com/10223856/76907932-3efe9700-6886-11ea-8b01-1c81ce31a339.png">

## Usage

To use this app, you first need to add it in your `manifest.json` file, like so

```json
{
  "dependencies": {
    "vtex.phone-field": "0.x"
  }
}
```

> If you are developing in TypeScript, you may also want to run `vtex setup` after the step above

Then, you can import the phone context and field components and use it inside your forms:

```jsx
import React from 'react'
import { PhoneField, PhoneContext, rules } from 'vtex.phone-field'

const Form = () => {
  const [phone, setPhone] = React.useState('+15554567038')

  const handlePhoneChange = React.useCallback(({ value, isValid }) => {
    setPhone(value)
    // you can use the `isValid` variable to show some error message
  }, [])

  return (
    <form>
      <PhoneContext.PhoneContextProvider rules={rules}>
        <PhoneField
          label="Phone number"
          value={phone}
          onChange={handlePhoneChange}
        />
      </PhoneContext.PhoneContextProvider>
    </form>
  )
}
```

You might be wondering, _what is that `rules` variable?_ And there is a few reasons that it and the
phone context exists.

The rules variable includes all default rules that exist inside the `vtex.phone-field` app, but the
`PhoneField` component isn't limited to them. A rule is a definition of the format (mask) of the phone
number, alongside it's [country ISO alpha-3 code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) and
country calling code. This is used by the component to mask the number correctly and also do the validations.

The phone context exists so we can decouple the rules definition of the component itself. If you ever
want to include a rule that our app doesn't natively support yet, you can pass it to the `rules` prop
of the `PhoneContextProvider` component. If you have any problems with that, please
[open an issue](https://github.com/vtex-apps/phone-field/issues/new/choose)!

The country flags are all inside the app for now, and the `PhoneField` component is rendering them based on
the country ISO of the rule. For example, given the following rule:

```javascript
const rule = {
  countryISO: 'BRA',
  countryCode: '55',
  mask: '(99) 9 9999-9999',
}
```

The component will look for a flag named `BRA.svg` inside the `react/icons` folder of the app and
render it. If the component doesn't find the flag of the country, it will use a default gray flag as
a placeholder.

## Components

### PhoneField

Responsible for rendering the listbox with the text field and formatting and validating the phone number.

#### Props

The `PhoneField` component also accepts all props of [Styleguide's `Input`](https://styleguide.vtex.com/#/Components/Forms/Input),
except for the `value` and `onChange`, which are redefined by this component.

| Prop name | type | Required |
| --- | --- | --- |
| [`value`](#phonefield-value) | `string` | `true` |
| [`onChange`](#phonefield-onchange) | `func` | `true` |
| [`defaultCountry`](#phonefield-defaultcountry) | `string` | `false` |

##### PhoneField value

`value: string`

The phone field value. Can include the country calling code. E.g.: `+15554567038`, `+55999998888`

##### PhoneField onChange

`onChange: (data: { value: string; isValid: boolean }) => void`

Callback to trigger the change of phone value. Can be triggered by either typing on the text field
or by changing the country from the listbox.

##### PhoneField defaultCountry

`defaultCountry?: string`

The default country to show in the listbox. Used only when the phone number passed in `value`
doesn't have a country calling code or if we don't have a `value` at all.

### PhoneContext.PhoneContextProvider

The wrapper component for the phone number that provides the rules definitions.

#### Props

| Prop name | type | Required |
| --- | --- | --- |
| [`rules`](#phonecontext-rules) | `array` | `true` |

##### PhoneContext rules

`rules: Array<{ countryISO: string; countryCode: string; mask?: string }>`

The rules definitions used by the `<PhoneField />` component.

```


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

[User] Show me the implementation of phone-field/react/rules.tsx from the phone-field VTEX app.

[Assistant]
Here's the implementation:

```tsx
export interface PhoneRuleDescriptor {
  /**
   * ISO3 Country code representation
   */
  countryISO: string
  /**
   * Country's international code number. E.g.: "55" for Brazil
   */
  countryCode: string
  /**
   * Mask to the phone. E.g.: "(99) 9 9999-9999"
   */
  mask?: string
  /**
   * Regex used for the phone validation
   */
  pattern: string
}

/**
 * Default rules for the phone field. Don't use this as this won't be updated
 * to include any more countries. Instead you should rely on a service that provides
 * this information dynamically (such as `vtex.country-data-settings`).
 *
 * @deprecated
 */
const defaultRules: PhoneRuleDescriptor[] = [
  {
    countryCode: '55',
    countryISO: 'BRA',
    mask: '(99) 9 9999-9999',
    pattern:
      '^(?:(?:(?:\\+|)(?:55|)|))(?:0|)(?:(?:(?:1[1-9]|2[12478]|3[1-8]|6[1-9]|7[134579]|8[1-9]|9[1-9]|4[1-9]|5[1-5])(?:9\\d{8}|\\d{8})))$',
  },
  {
    countryCode: '54',
    countryISO: 'ARG',
    mask: '9 999 999-9999',
    pattern:
      '^(?:(?:\\+|)54|)(?:0|)(?:(?:9(?:0|)(?:(?:11\\d{8})|(?:2(?:20|21|23|30|36|37|49|60|61|63|64|66|80|91|94|97|98|99)|3(?:36|41|42|43|45|45|48|51|53|58|62|64|70|76|79|80|81|83|85|87|88))\\d{7})|(?:2(?:2(?:02|21|23|24|25|26|27|29|41|42|43|44|45|46|52|54|55|57|61|62|64|65|66|67|68|71|72|73|74|81|83|84|85|86|91|92|96|97)|3(?:02|14|16|17|20|23|24|25|26|31|33|34|35|37|38|42|43|44|45|46|52|53|54|55|56|57|58|92|93|94|95|96)|4(?:73|74|75|77|78)|6(?:22|24|25|26|46|47|48|51|55|56|57|58)|9(?:01|02|03|20|21|22|23|24|25|26|27|28|29|31|32|33|34|35|36|40|42|45|46|48|52|53|54|62|63|64|66|72|82|83))|3(?:3(?:27|29|82|85|87|88)|4(?:00|01|02|04|05|06|07|08|09|35|36|37|38|42|44|45|46|47|54|55|56|58|60|62|63|64|65|66|67|68|69|71|72|76|82|83|87|89|91|92|93|96|97|98)|5(?:21|22|24|25|32|33|37|41|42|43|44|46|47|48|49|62|63|64|71|72|73|74|75|76|82|83|84|85)|7(?:11|15|16|18|21|25|31|34|35|41|43|51|54|55|56|57|58|72|73|74|75|77|81|82|86)|8(?:21|25|26|27|32|35|37|38|41|43|44|45|46|54|55|56|57|58|61|62|63|65|67|68|69|73|76|77|78|85|86|87|88|91|92|94))\\d{6}))|(?:(?:11(?:15\\d{8}|(?!15)\\d{8}))|(?:(?:2(?:20|21|23|30|36|37|49|60|61|63|64|66|80|91|94|97|98|99)|3(?:36|41|42|43|45|45|48|51|53|58|62|64|70|76|79|80|81|83|85|87|88))(?:15\\d{7}|(?!15)\\d{7}))|(?:2(?:2(?:02|21|23|24|25|26|27|29|41|42|43|44|45|46|52|54|55|57|61|62|64|65|66|67|68|71|72|73|74|81|83|84|85|86|91|92|96|97)|3(?:02|14|16|17|20|23|24|25|26|31|33|34|35|37|38|42|43|44|45|46|52|53|54|55|56|57|58|92|93|94|95|96)|4(?:73|74|75|77|78)|6(?:22|24|25|26|46|47|48|51|55|56|57|58)|9(?:01|02|03|20|21|22|23|24|25|26|27|28|29|31|32|33|34|35|36|40|42|45|46|48|52|53|54|62|63|64|66|72|82|83))|3(?:3(?:27|29|82|85|87|88)|4(?:00|01|02|04|05|06|07|08|09|35|36|37|38|42|44|45|46|47|54|55|56|58|60|62|63|64|65|66|67|68|69|71|72|76|82|83|87|89|91|92|93|96|97|98)|5(?:21|22|24|25|32|33|37|41|42|43|44|46|47|48|49|62|63|64|71|72|73|74|75|76|82|83|84|85)|7(?:11|15|16|18|21|25|31|34|35|41|43|51|54|55|56|57|58|72|73|74|75|77|81|82|86)|8(?:21|25|26|27|32|35|37|38|41|43|44|45|46|54|55|56|57|58|61|62|63|65|67|68|69|73|76|77|78|85|86|87|88|91|92|94)))(?:15\\d{6}|(?!15)\\d{6})))$',
  },
  {
    countryCode: '1',
    countryISO: 'USA',
    mask: '999-999-9999',
    pattern:
      '^(?:(?:(?:\\+|)(?:1|))|)(?:1|)(?:2(?:0[1-9]|1[02-9]|2[4-9]|3[1469]|4[089]|5[01-46]|6[0279]|7[0468]|8[139])|3(?:0[1-9]|1[02-9]|2[01235]|3[014679]|4[01367]|5[12]|6[01459]|8[056])|4(?:0[1-9]|1[02-9]|2[345]|3[0-24578]|4[023578]|5[08]|6[49]|7[0589]|8[04]|50[1-57-9])|5(?:0[1-9]|1[02-9]|20|3[014]|4[01]|5[179]|6[1-47]|7[013-59]|8[01567])|6(?:0[1-9]|1[0234-9]|2[036-8]|3[0169]|4[167]|5[0179]|6[01279]|7[0189]|8[1249])|7(?:0[1-9]|1[2-9]|2[047]|3[01247]|4[07]|5[247]|6[02-59]|7[02-589]|8[01567])|8(?:0[1-8]|1[0-9]|28|3[0-25]|4[3578]|5[06-9]|6[02-57]|7[0238])|9(?:0[1-9]|1[02-9]|2[0578]|3[15-9]|4[0179]|5[124679]|7[0-3589]|8[045]|89))\\d{7}$',
  },
]

export default defaultRules

```


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

[User] Show me the implementation of phone-field/react/PhoneField.css from the phone-field VTEX app.

[Assistant]
Here's the implementation:

```css
.phoneField :global(.vtex-input__prefix) {
  padding-left: 0;
}

.phoneField :global(.vtex-input__prefix) {
  flex-shrink: 0;
  padding-right: 0;
}

.phoneField :global(.vtex-input) input {
  padding-right: .5rem;
  padding-left: .5rem;
  flex: 1;
  width: auto;
  min-width: 0;
}

.listboxButton {
  border-radius: 0;
  padding-top: 0;
  padding-bottom: 0;
  padding-right: .5rem;
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "name": "phone-field",
  "version": "0.1.5",
  "private": true,
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "devDependencies": {
    "@apollo/react-testing": "^3.1.3",
    "@reach/listbox": "^0.10.2",
    "@types/classnames": "^2.2.10",
    "@types/jest": "^25.1.4",
    "@types/node": "^13.9.1",
    "@types/react": "^16.9.23",
    "@vtex/styleguide": "^9.112.20",
    "@vtex/test-tools": "^3.0.3",
    "vtex.checkout-components": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-components@0.4.0/public/@types/vtex.checkout-components",
    "vtex.country-flags": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.country-flags@0.1.1/public/@types/vtex.country-flags",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.104.3/public/@types/vtex.render-runtime",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.120.1/public/@types/vtex.styleguide"
  },
  "dependencies": {
    "classnames": "^2.2.6",
    "msk": "^1.0.5",
    "react": "^16.13.0",
    "react-intl": "^3.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 phone-field/react/PhoneContext.tsx from the phone-field VTEX app.

[Assistant]
Here's the implementation:

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

import { PhoneRuleDescriptor } from './rules'

interface Context {
  rules: PhoneRuleDescriptor[]
}

const PhoneContext = createContext<Context | undefined>(undefined)

export const usePhoneContext = () => {
  const contextValue = useContext(PhoneContext)

  if (contextValue === undefined) {
    throw new Error(
      'usePhoneContext must be used inside a PhoneContextProvider'
    )
  }

  return contextValue
}

export const PhoneContextProvider: React.FC<Context> = ({
  rules,
  children,
}) => {
  const contextValue = useMemo(
    () => ({
      rules: rules.sort((ruleA, ruleB) =>
        ruleA.countryISO > ruleB.countryISO
          ? 1
          : ruleA.countryISO < ruleB.countryISO
          ? -1
          : 0
      ),
    }),
    [rules]
  )

  return (
    <PhoneContext.Provider value={contextValue}>
      {children}
    </PhoneContext.Provider>
  )
}

export default { PhoneContextProvider, usePhoneContext }

```


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

[User] Show me the implementation of phone-field/react/PhoneField.tsx from the phone-field VTEX app.

[Assistant]
Here's the implementation:

```tsx
import classnames from 'classnames'
import msk from 'msk'
import React, { useMemo, useRef, useState, useEffect, useCallback } from 'react'
import { Input } from 'vtex.styleguide'
import { Listbox } from 'vtex.checkout-components'
import { CountryFlag } from 'vtex.country-flags'

import { usePhoneContext } from './PhoneContext'
import styles from './PhoneField.css'
import { PhoneRuleDescriptor } from './rules'

const {
  ListboxInput,
  ListboxButton,
  ListboxPopover,
  ListboxList,
  ListboxOption,
} = Listbox

interface PhoneData {
  value: string
  isValid: boolean
}

interface Props
  extends Omit<
    React.InputHTMLAttributes<HTMLInputElement>,
    'onChange' | 'value' | 'size'
  > {
  onChange?: (data: PhoneData) => void
  value?: string
  defaultCountry?: string
  // Input's props
  label?: string | React.ReactElement
  error?: boolean
  errorMessage?: string
  helpText?: React.ReactNode
  suffix?: React.ReactNode
  size?: 'small' | 'regular' | 'large'
  isLoadingButton?: boolean
}

const renderCountryFlagWithCode = ({
  country,
  code,
}: {
  country: string
  code?: string
}) => (
  <>
    <CountryFlag iso3={country} />
    {code && <span className="dib ml3">+{code}</span>}
  </>
)

const ArrowDownIcon: React.FC<{ size?: number; color?: string }> = ({
  size = 16,
  color = 'currentColor',
}) => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width={size}
    height={size}
    viewBox="0 0 24 24"
  >
    <g fill={color}>
      <path d="M7.41 7.84L12 12.42l4.59-4.58L18 9.25l-6 6-6-6z" />
    </g>
  </svg>
)

const unmaskPhone = (phone: string) => phone.replace(/\D/g, '')

const PhoneField = React.forwardRef<HTMLInputElement, Props>(
  function PhoneField(
    { onChange = () => {}, value = '', defaultCountry = 'BRA', ...props },
    ref
  ) {
    const { rules } = usePhoneContext()
    const inputRef = useRef<HTMLInputElement>(null)

    const [inputHovered, setInputHovered] = useState(false)
    const [inputFocused, setInputFocused] = useState(false)
    const [hovered, setHovered] = useState(false)

    const phoneData = useMemo(() => {
      let phoneValue = value
      let selectedCountry = !value ? defaultCountry : ''

      if (value.startsWith('+')) {
        phoneValue = value.substr(1)
        const unmaskedPhone = unmaskPhone(phoneValue)

        const phoneRule = rules.find(({ countryCode }) => {
          return unmaskedPhone.startsWith(countryCode)
        })

        if (phoneRule) {
          selectedCountry = phoneRule.countryISO
          phoneValue = phoneValue.substr(phoneRule.countryCode.length)
        }
      } else {
        phoneValue = unmaskPhone(value)
      }

      return { phoneValue, selectedCountry }
    }, [defaultCountry, rules, value])

    const countryRule = useMemo(
      () =>
        rules.find(
          ({ countryISO }) => countryISO === phoneData.selectedCountry
        ),
      [rules, phoneData.selectedCountry]
    )

    const onChangeRef = useRef(onChange)

    useEffect(() => {
      onChangeRef.current = onChange
    }, [onChange])

    const updatePhone = useCallback(
      (phone: string, rule: PhoneRuleDescriptor) => {
        const unmaskedValue = `+${rule.countryCode}${unmaskPhone(phone)}`

        onChangeRef.current({
          value: `+${rule.countryCode}${phone}`,
          isValid: !!unmaskedValue.match(rule.pattern),
        })
      },
      []
    )

    useEffect(() => {
      if (inputFocused || !countryRule || !countryRule.mask) {
        return
      }

      const phone = msk(unmaskPhone(phoneData.phoneValue), countryRule.mask)

      updatePhone(phone, countryRule)
    }, [phoneData.phoneValue, countryRule, inputFocused, updatePhone])

    const handleChange: React.ChangeEventHandler<HTMLInputElement> = ({
      target: { value: eventValue },
    }) => {
      if (!countryRule) {
        return
      }

      updatePhone(eventValue, countryRule)
    }

    const handleCountryUpdate = (country: string) => {
      const newRule = rules.find(({ countryISO }) => countryISO === country)!

      updatePhone(phoneData.phoneValue, newRule)

      // schedule focus for the next tick since the listbox
      // is already focused by default after this event handler,
      // and we need to override that
      setTimeout(() => void inputRef.current?.focus(), 0)
    }

    const handleInputMouseEnter: React.MouseEventHandler<HTMLInputElement> = evt => {
      setInputHovered(true)
      props.onMouseEnter?.(evt)
    }

    const handleInputMouseLeave: React.MouseEventHandler<HTMLInputElement> = evt => {
      setInputHovered(false)
      props.onMouseLeave?.(evt)
    }

    const handleInputFocus: React.FocusEventHandler<HTMLInputElement> = evt => {
      setInputFocused(true)
      props.onFocus?.(evt)
    }

    const handleInputBlur: React.FocusEventHandler<HTMLInputElement> = evt => {
      setInputFocused(false)
      props.onBlur?.(evt)
    }

    const handleMouseEnter = () => {
      setHovered(true)
    }

    const handleMouseLeave = () => {
      setHovered(false)
    }

    // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
    const hasError = !!(props.error || props.errorMessage)

    // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
    const inputDisabled = props.disabled || !countryRule

    return (
      <div className={styles.phoneField}>
        <Input
          {...props}
          onFocus={handleInputFocus}
          onBlur={handleInputBlur}
          onMouseEnter={handleInputMouseEnter}
          onMouseLeave={handleInputMouseLeave}
          disabled={inputDisabled}
          inputMode="numeric"
          value={phoneData.phoneValue}
          onChange={handleChange}
          ref={(node: HTMLInputElement) => {
            if (ref) {
              if (typeof ref === 'function') {
                ref(node)
              } else {
                // @ts-ignore: React TS types says this is read-only, but
                // it its possible to mutate this value
                ref.current = node
              }
            }
            // @ts-ignore: same as above
            inputRef.current = node
          }}
          prefix={
            <ListboxInput
              className="h-100 flex-auto"
              value={phoneData.selectedCountry}
              onChange={handleCountryUpdate}
              disabled={inputDisabled}
            >
              <ListboxButton
                className={classnames(styles.listboxButton, 'br bw1 br-2', {
                  'b--danger': hasError,
                  'b--muted-4':
                    !(hovered || inputHovered || inputFocused) && !hasError,
                  'b--muted-3':
                    (hovered || inputHovered) && !inputFocused && !hasError,
                  'b--muted-2': inputFocused && !hasError,
                })}
                variation="plain"
                arrow={
                  <div className="c-action-primary flex items-center ml2">
                    <ArrowDownIcon />
                  </div>
                }
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}
              >
                {({ label }) =>
                  renderCountryFlagWithCode({
                    country: phoneData.selectedCountry,
                    code: label,
                  })
                }
              </ListboxButton>
              <ListboxPopover
                className="nl1"
                style={{ minWidth: 192, maxHeight: 200 }}
              >
                <ListboxList>
                  {rules.map(({ countryCode, countryISO }) => {
                    return (
                      <ListboxOption
                        value={countryISO}
                        label={countryCode}
                        key={countryISO}
                      >
                        {renderCountryFlagWithCode({
                          country: countryISO,
                          code: countryCode,
                        })}
                      </ListboxOption>
                    )
                  })}
                </ListboxList>
              </ListboxPopover>
            </ListboxInput>
          }
        />
      </div>
    )
  }
)

export default PhoneField

```


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

[User] Show me the implementation of phone-field/react/typings/assets.d.ts from the phone-field VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.svg' {
  const url: string

  export default url
}

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

```


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

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

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable import/order */

import * as Styleguide from 'vtex.styleguide'

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

  export const Input: React.FC

  export const IconCaretDown: React.FC
}

```


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

[User] Show me the implementation of phone-field/react/__tests__/PhoneField.test.tsx from the phone-field VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { render, fireEvent, act } from '@vtex/test-tools/react'
import React, { useState, useEffect, useRef } from 'react'

import PhoneField from '../PhoneField'
import defaultRules, { PhoneRuleDescriptor } from '../rules'
import { PhoneContextProvider } from '../PhoneContext'

/**
 * Listbox opens on mousedown, not click event
 */
function fireMouseClick(element: HTMLElement) {
  fireEvent.mouseDown(element)
  fireEvent.mouseUp(element)
}

describe('<PhoneField />', () => {
  beforeEach(() => {
    jest.useFakeTimers()
  })

  afterEach(() => {
    jest.clearAllTimers()
  })

  it('should correctly mask a phone number given a rule', () => {
    const rules: PhoneRuleDescriptor[] = [
      {
        countryISO: 'ABC',
        countryCode: '123',
        mask: '999 999 9-9',
        pattern: '\\d{8}',
      },
    ]

    const Component: React.FC = () => {
      const [phone, setPhone] = useState('')

      const handlePhoneChange = ({ value }: { value: string }) => {
        setPhone(value)
      }

      return (
        <PhoneContextProvider rules={rules}>
          <PhoneField
            label="Phone number"
            value={phone}
            defaultCountry="ABC"
            onChange={handlePhoneChange}
          />
        </PhoneContextProvider>
      )
    }

    const { getByRole } = render(<Component />)

    const phoneInput = getByRole('textbox')
    const listboxButton = getByRole('button')

    fireEvent.focus(phoneInput)

    fireEvent.change(phoneInput, { target: { value: '4567' } })

    expect(listboxButton).toHaveTextContent('+123')

    expect(phoneInput).toHaveValue('4567')

    fireEvent.change(phoneInput, { target: { value: '45678901' } })

    expect(phoneInput).toHaveValue('45678901')

    fireEvent.change(phoneInput, { target: { value: '456789012' } })

    fireEvent.blur(phoneInput)

    expect(phoneInput).toHaveValue('456 789 0-12')
  })

  it('should show error message for invalid phones', () => {
    const Component: React.FC = () => {
      const [phone, setPhone] = useState('')
      const [valid, setValid] = useState(false)

      const handlePhoneChange = ({
        value,
        isValid,
      }: {
        value: string
        isValid: boolean
      }) => {
        setPhone(value)
        setValid(isValid)
      }

      return (
        <PhoneContextProvider rules={defaultRules}>
          <PhoneField
            label="Phone number"
            value={phone}
            defaultCountry="BRA"
            onChange={handlePhoneChange}
          />
          {!valid && <span>Phone is invalid</span>}
        </PhoneContextProvider>
      )
    }

    const { getByRole, queryByText } = render(<Component />)

    const phoneInput = getByRole('textbox')

    expect(queryByText(/phone is invalid/i)).toBeInTheDocument()

    fireEvent.change(phoneInput, { target: { value: '21988884444' } })

    expect(queryByText(/phone is invalid/i)).not.toBeInTheDocument()

    fireEvent.change(phoneInput, { target: { value: '219888844443' } })

    expect(queryByText(/phone is invalid/i)).toBeInTheDocument()
  })

  it('should focus the input button on flag change', () => {
    const Component: React.FC = () => {
      const [phone, setPhone] = useState('+5511999998888')

      return (
        <PhoneContextProvider rules={defaultRules}>
          <PhoneField
            label="Phone number"
            value={phone}
            onChange={({ value }) => setPhone(value)}
          />
        </PhoneContextProvider>
      )
    }

    const { getByRole, getByLabelText } = render(<Component />)

    const phoneInput = getByLabelText(/phone number/i)

    expect(document.activeElement).not.toBe(phoneInput)

    const listboxButton = getByRole('button')

    act(() => void fireMouseClick(listboxButton))

    const usaOption = getByRole('option', { name: '+ 1' })

    act(() => {
      fireMouseClick(usaOption)
      jest.runAllTimers()
    })

    expect(document.activeElement).toBe(phoneInput)
  })

  it('should use pattern for phone validation', () => {
    const rules: PhoneRuleDescriptor[] = [
      { countryISO: 'ABC', countryCode: '1', pattern: '\\d{9}' },
    ]

    const Component: React.FC = () => {
      const [phone, setPhone] = useState('+1')
      const [valid, setValid] = useState(false)

      const handlePhoneChange = ({
        value,
        isValid,
      }: {
        value: string
        isValid: boolean
      }) => {
        setPhone(value)
        setValid(isValid)
      }

      return (
        <PhoneContextProvider rules={rules}>
          <PhoneField
            label="Phone number"
            value={phone}
            onChange={handlePhoneChange}
          />
          {!valid && <span>Phone is invalid</span>}
        </PhoneContextProvider>
      )
    }

    const { getByRole, queryByText } = render(<Component />)

    const phoneField = getByRole('textbox')

    fireEvent.focus(phoneField)

    fireEvent.change(phoneField, { target: { value: '123 456' } })

    expect(queryByText(/phone is invalid/i)).toBeInTheDocument()

    fireEvent.change(phoneField, { target: { value: '123 456 789' } })

    expect(queryByText(/phone is invalid/i)).not.toBeInTheDocument()

    fireEvent.blur(phoneField)

    expect(phoneField).toHaveValue('123 456 789')
  })

  it('should be able to accept refs in phone field', () => {
    let ref = null

    const Component: React.FC = () => {
      const inputRef = useRef<HTMLInputElement>(null)

      useEffect(() => {
        ref = inputRef.current
      })

      return (
        <PhoneContextProvider rules={defaultRules}>
          <PhoneField
            label="Phone number"
            value="+5511999998888"
            ref={inputRef}
          />
        </PhoneContextProvider>
      )
    }

    const { getByLabelText } = render(<Component />)

    expect(ref).toBe(getByLabelText(/phone number/i))
  })

  it("should show phone number when rule don't have a mask", () => {
    const rules = [
      {
        countryISO: 'ABC',
        countryCode: '1',
        pattern: '.*',
      },
    ]

    const Component: React.FC = () => {
      return (
        <PhoneContextProvider rules={rules}>
          <PhoneField label="Phone number" value="+1123456" />
        </PhoneContextProvider>
      )
    }

    const { getByLabelText } = render(<Component />)

    const phoneInput = getByLabelText(/phone number/i)

    expect(phoneInput).toHaveValue('123456')
  })

  describe('default rules', () => {
    it('should correctly apply the USA mask with country change', () => {
      const Component: React.FC = () => {
        const [phone, setPhone] = useState('+5511999998888')
        const [valid, setValid] = useState(true)

        return (
          <PhoneContextProvider rules={defaultRules}>
            <PhoneField
              label="Phone number"
              value={phone}
              onChange={({ value, isValid }) => {
                setPhone(value)
                setValid(isValid)
              }}
            />
            {!valid && <span>Phone is invalid</span>}
          </PhoneContextProvider>
        )
      }

      const { getByRole, getByLabelText, getByText } = render(<Component />)

      const listboxButton = getByRole('button')

      act(() => void fireMouseClick(listboxButton))

      const usaOption = getByRole('option', { name: '+ 1' })

      act(() => void fireMouseClick(usaOption))

      const phoneInput = getByLabelText(/phone number/i)

      expect(phoneInput).toHaveValue('119-999-98888')

      const errorMessage = getByText(/phone is invalid/i)

      expect(errorMessage).toBeInTheDocument()
    })
  })
})

```


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

[User] Show me the implementation of easy-setup/messages/pt.json from the easy-setup VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/easy-setup.navigation.label-group": "Easy Setup",
  "admin/easy-setup.navigation.label-home": "Easy Setup",
  "admin/easy-setup.navigation.kws": "easy, setup, catalog, products",
  "admin/easy-setup.title": "Easy Setup"
}

```


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

[User] Show me the implementation of easy-setup/messages/en.json from the easy-setup VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/easy-setup.navigation.label-group": "Easy Setup",
  "admin/easy-setup.navigation.label-home": "Easy Setup",
  "admin/easy-setup.navigation.kws": "easy, setup, catalog, products",
  "admin/easy-setup.title": "Easy Setup"
}

```


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

[User] Show me the implementation of easy-setup/messages/context.json from the easy-setup VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/easy-setup.navigation.label-group": "admin/easy-setup.navigation.label-group",
  "admin/easy-setup.navigation.label-home": "admin/easy-setup.navigation.label-home",
  "admin/easy-setup.navigation.kws": "admin/easy-setup.navigation.kws",
  "admin/easy-setup.title": "admin/easy-setup.title"
}

```


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

[User] Show me the implementation of easy-setup/messages/es.json from the easy-setup VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/easy-setup.navigation.label-group": "Easy Setup",
  "admin/easy-setup.navigation.label-home": "Easy Setup",
  "admin/easy-setup.navigation.kws": "easy, setup, catalog, products",
  "admin/easy-setup.title": "Easy Setup"
}

```


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

[User] Show me the implementation of easy-setup/admin/navigation.json from the easy-setup VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "section": "storeSetup",
  "titleId": "admin/easy-setup.navigation.label-group",
  "searchKeyWordsHelpers": "admin/easy-setup.navigation.kws",
  "path": "/admin/easy-setup"
}

```


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

[User] Show me the implementation of easy-setup/admin/routes.json from the easy-setup VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin.app.easy-setup": {
    "component": "AdminHome",
    "path": "/admin/app/easy-setup"
  }
}

```