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

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

[Assistant]
Here's the implementation:

```json
{
  "name": "@vtex/profile-form",
  "version": "2.9.6",
  "description": "React component for managing user profiles",
  "main": "lib/index.js",
  "files": [
    "lib"
  ],
  "scripts": {
    "build": "npm run symlinks && nwb build-react-component --no-demo && npm run removeMocks && npm run addLocales",
    "build:link": "npm link && watch 'npm run build' src",
    "removeMocks": "rm -rf lib/**/__mocks__ && rm -rf lib/__mocks__",
    "addLocales": "cp -R -f messages/ lib/locales/",
    "clean": "nwb clean-module && nwb clean-demo",
    "start": "npm run symlinks && nwb serve-react-demo",
    "symlinks": "rm -rf src && ln -sf react src",
    "test": "cd .. && jest --env=jsdom",
    "test:coverage": "jest --env=jsdom --coverage",
    "test:watch": "jest --env=jsdom --watch",
    "vtex:link": "npm run symlinks && vtex link",
    "prepublishOnly": "npm run build",
    "lint:messages": "intl-equalizer"
  },
  "repository": "https://github.com/vtex/profile-form",
  "author": "Gustavo Silva (@akafts)",
  "license": "AGPL-3.0-only",
  "homepage": "https://github.com/vtex/profile-form",
  "keywords": [
    "react-component",
    "vtex",
    "profile"
  ],
  "intl-equalizer": {
    "localeDirectory": "../messages/"
  },
  "husky": {
    "hooks": {
      "pre-push": "yarn lint:messages && yarn test"
    }
  },
  "jest": {
    "setupTestFrameworkScriptFile": "./__tests__/setupTests.js",
    "testURL": "http://localhost",
    "testPathIgnorePatterns": [
      "/node_modules/",
      "<rootDir>/es/",
      "<rootDir>/lib/",
      "<rootDir>/umd/",
      "<rootDir>/src/",
      "setupTests"
    ],
    "modulePathIgnorePatterns": [
      "<rootDir>/es/",
      "<rootDir>/lib/",
      "<rootDir>/umd/",
      "<rootDir>/src/"
    ],
    "transformIgnorePatterns": [
      "[/\\\\]lib[/\\\\].+\\.(js|jsx)$",
      "[/\\\\]umd[/\\\\].+\\.(js|jsx)$",
      "[/\\\\]es[/\\\\].+\\.(js|jsx)$",
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
    ],
    "moduleNameMapper": {
      "\\.(css|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)(\\?.*)?$": "identity-obj-proxy"
    },
    "transform": {
      "^.+\\.js$": "../jest.transform.js"
    }
  },
  "devDependencies": {
    "react": "^16.4.1",
    "@vtex/intl-equalizer": "^2.3.0",
    "babel-jest": "^23.6.0",
    "babel-plugin-add-react-displayname": "0.0.5",
    "babel-preset-react-app": "^3.1.2",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "enzyme-react-intl": "^2.0.0",
    "husky": "^2.3.0",
    "jest": "^22.4.4",
    "jest-enzyme": "^6.0.2",
    "nwb": "^0.21.5",
    "react-dom": "^16.4.1",
    "react-hot-loader": "^4.3.4",
    "react-test-renderer": "^16.4.1",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@7.42.0/public/@types/vtex.render-runtime"
  },
  "dependencies": {
    "@vtex/phone": "^4.8.0",
    "@vtex/styleguide": "^5.4.4",
    "downshift": "^2.0.20",
    "match-sorter": "^2.2.3",
    "moment": "^2.22.2",
    "msk": "^1.0.3",
    "react-intl": "^2.4.0"
  },
  "peerDependencies": {
    "react": "^16.4.1",
    "vtex-tachyons": "^2.5.0"
  }
}

```


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

[User] Show me the implementation of instore-profile/react/modules.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import addValidation from './modules/addValidation'
import removeValidation from './modules/removeValidation'

export default { addValidation, removeValidation }

```


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

[User] Show me the implementation of instore-profile/react/ProfileField.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { applyMask, applyValidation } from './modules/validateProfile'
import RuleFieldShape from './RuleFieldShape'
import ProfileFieldShape from './ProfileFieldShape'

class ProfileField extends Component {
  componentDidUpdate() {
    const { field, data, onFieldUpdate } = this.props
    if (data.focus && this.el) {
      this.el.focus()
      onFieldUpdate({ [field.name]: { ...data, focus: false } })
    }
  }

  handleChange = e => {
    const { field, data, onFieldUpdate } = this.props
    const { value } = e.target

    const error = data.touched ? applyValidation(field, value) : null
    const maskedValue = applyMask(field, value)

    onFieldUpdate({ [field.name]: { ...data, value: maskedValue, error } })
  }

  handleBlur = () => {
    const { field, data, onFieldUpdate } = this.props
    const error = applyValidation(field, data.value)

    onFieldUpdate({ [field.name]: { ...data, touched: true, error } })
  }

  inputRef = el => {
    this.el = el
  }

  render() {
    const { field, data, options, Input } = this.props
    return (
      <Input
        field={field}
        data={data}
        options={options}
        inputRef={this.inputRef}
        onChange={this.handleChange}
        onBlur={this.handleBlur}
      />
    )
  }
}

ProfileField.propTypes = {
  /** Rules for the field this component represents */
  field: RuleFieldShape.isRequired,
  /** Data to be displayed by this component */
  data: ProfileFieldShape.isRequired,
  /** Additional options to modify this input */
  options: PropTypes.object,
  /** Function to be called when data changes */
  onFieldUpdate: PropTypes.func.isRequired,
  /** Component to be used as input for the field */
  Input: PropTypes.func.isRequired,
}

export default ProfileField

```


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

[User] Show me the implementation of instore-profile/react/ProfileSummary.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { intlShape, injectIntl } from 'react-intl'
import ProfileShape from './ProfileShape'
import RuleShape from './RuleShape'

class ProfileSummary extends Component {
  mapFields(fields) {
    const { profile, intl } = this.props

    return fields
      .map(field => {
        const data = profile[field.name]
        return {
          [field.name]: {
            label: intl.formatMessage({
              id: 'profile-form.field.' + field.label,
            }),
            value: field.display && data ? field.display(data) : data,
            hidden: field.hidden,
          },
        }
      })
      .reduce((acc, cur) => ({ ...acc, ...cur }), {})
  }

  translateGender(mappedData) {
    const gender = mappedData.gender.value
    return {
      ...mappedData,
      gender: {
        ...mappedData.gender,
        value:
          gender &&
          this.props.intl.formatMessage({
            id: `profile-form.gender.${gender}`,
            // fallback to whatever came from the master data
            defaultMessage: gender,
          }),
      },
    }
  }

  render() {
    const { rules, children } = this.props
    const { isCorporate } = this.props.profile
    const personalData = this.translateGender(
      this.mapFields(rules.personalFields),
    )
    const businessData = this.mapFields(rules.businessFields)

    return (
      <div className="vtex-profile-form__profile-summary">
        {children({ personalData, businessData, isCorporate })}
      </div>
    )
  }
}

ProfileSummary.propTypes = {
  /** Profile to be displayed */
  profile: ProfileShape.isRequired,
  /** Rules to be applied over the profile */
  rules: RuleShape.isRequired,
  /** Render prop that receives all display data */
  children: PropTypes.func.isRequired,
  /** React-intl injected utility */
  intl: intlShape.isRequired,
}

export default injectIntl(ProfileSummary)

```


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

[User] Show me the implementation of instore-profile/react/RuleShape.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import PropTypes from 'prop-types'
import RuleFieldShape from './RuleFieldShape'

export default PropTypes.shape({
  /** The country this rule refers to */
  country: PropTypes.string,
  /** Configuration for the personal fields */
  personalFields: PropTypes.arrayOf(RuleFieldShape).isRequired,
  /** Configuration for the business fields */
  businessFields: PropTypes.arrayOf(RuleFieldShape).isRequired,
})

```


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

[User] Show me the implementation of instore-profile/demo/src/DisplaySlice.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React from 'react'
import PropTypes from 'prop-types'

const DisplaySlice = ({ slice }) => {
  return (
    <div className={`mb6 ${slice.hidden ? 'dn' : ''}`}>
      <label className="db fw5 black-90 mb2">{slice.label}</label>
      <span className="light black-40">{slice.value}</span>
    </div>
  )
}

DisplaySlice.propTypes = {
  /** Piece of display data to show */
  slice: PropTypes.object.isRequired,
}

export default DisplaySlice

```


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

[User] Show me the implementation of instore-profile/demo/src/index.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import App from './App'

const root = document.getElementById('demo')
const renderApp = Root => {
  ReactDOM.render(
    <AppContainer>
      <Root />
    </AppContainer>,
    root,
  )
}

renderApp(App)

if (module.hot) {
  module.hot.accept('./App', () => {
    const NewApp = require('./App').default
    renderApp(NewApp)
  })
}

```


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

[User] Show me the implementation of instore-profile/demo/src/App.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React, { Component } from 'react'
import { IntlProvider, addLocaleData } from 'react-intl'
import ptLocaleData from 'react-intl/locale-data/pt'
import Button from '@vtex/styleguide/lib/Button'
import ptTranslations from '../../messages/pt'
import ProfileContainer from '../../react/ProfileContainer'
import ProfileRules from '../../react/ProfileRules'
import ProfileSummary from '../../react/ProfileSummary'
import DisplaySlice from './DisplaySlice'
import emptyProfile from '../../react/modules/emptyProfile'
import 'vtex-tachyons'

class App extends Component {
  constructor(props) {
    super(props)
    addLocaleData(ptLocaleData)

    this.state = {
      profile: emptyProfile,
      profileCountry: 'BRA',
      submitted: false,
    }
  }

  toggleLocale = () => {
    this.setState(prevState => ({
      profileCountry: prevState.profileCountry === 'BRA' ? 'USA' : 'BRA',
    }))
  }

  handleSubmit = ({ valid, profile }) => {
    if (!valid) return
    this.setState({ profile, submitted: true })
  }

  render() {
    const { profile, profileCountry, submitted } = this.state

    return (
      <div className="pa4">
        <h2 className="dark-gray">ProfileForm demo:</h2>
        {!submitted && (
          <div className="mb6">
            <Button
              size="small"
              variation="secondary"
              onClick={this.toggleLocale}
            >
              Set rules to {profileCountry === 'BRA' ? 'USA' : 'BRA'}
            </Button>
          </div>
        )}
        <IntlProvider locale={'pt-BR'} messages={ptTranslations}>
          <div>
            <ProfileRules
              key={profileCountry}
              country={profileCountry}
              fetch={country => import('../../src/rules/' + country)}
            >
              {submitted ? (
                <ProfileSummary profile={profile}>
                  {({ personalData, businessData, isCorporate }) => (
                    <div>
                      <h3 className="heavy-rebel-pink">Personal Data:</h3>
                      {Object.keys(personalData).map(fieldName => (
                        <DisplaySlice
                          key={fieldName}
                          slice={personalData[fieldName]}
                        />
                      ))}
                      <h3 className="heavy-rebel-pink">Business Data:</h3>
                      {Object.keys(businessData).map(fieldName => (
                        <DisplaySlice
                          key={fieldName}
                          slice={businessData[fieldName]}
                        />
                      ))}
                      <h3 className="heavy-rebel-pink">
                        Is corporate?
                        <span className="near-black ml3">
                          {isCorporate ? 'yes' : 'no'}
                        </span>
                      </h3>
                    </div>
                  )}
                </ProfileSummary>
              ) : (
                <ProfileContainer
                  defaultProfile={profile}
                  onSubmit={this.handleSubmit}
                  shouldShowExtendedGenders={true}
                />
              )}
            </ProfileRules>
          </div>
        </IntlProvider>
      </div>
    )
  }
}

export default App

```


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

[User] Show me the implementation of instore-profile/react/utils/dateRules.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import moment from 'moment'
import msk from 'msk'

export function filterDateType(fields) {
  return fields.filter(rule => rule.type === 'date')
}

// merge the arr2 into arr1 based on a rule name
// considering the arr2 value over the arr1
function mergeArrays(arr1, arr2) {
  const aux = {}
  arr2.forEach(rule => (aux[rule.name] = rule))

  return arr1.map(rule => {
    return aux[rule.name] ? aux[rule.name] : rule
  })
}

export function prepareDateRules(rules, intl) {
  return {
    ...rules,
    personalFields: mergeArrays(
      rules.personalFields,
      setDateRuleValidations(filterDateType(rules.personalFields), intl),
    ),
  }
}

function setDateRuleValidations(rules, intl) {
  if (rules) {
    return rules.map(rule => {
      const ruleCopy = { ...rule }
      ruleCopy.mask = value => msk.fit(value, '99/99/9999')
      ruleCopy.validate = value => {
        const mom = moment.utc(value, 'L', intl.locale.toLowerCase())

        return mom.isValid() && rule.validate(mom.unix())
      }
      ruleCopy.display = value =>
        moment
          .utc(value, [moment.ISO_8601, 'L'], intl.locale.toLowerCase())
          .format('L')
      ruleCopy.submit = value => {
        if (!value) return null

        const date = moment.utc(value, 'L', intl.locale.toLowerCase(), true)
        if (!date.isValid()) return null

        return date.format()
      }
      return ruleCopy
    })
  }
  return rules
}

export function isPastDate(unixTimestamp) {
  const nowMS = Date.now() / 1000

  return unixTimestamp - nowMS < 0
}

```


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

[User] Show me the implementation of instore-profile/react/__tests__/ProfileRules.test.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import { IntlProvider } from 'react-intl'

import { prepareDateRules, filterDateType } from '../utils/dateRules'
import defaultRules from '../rules/default'

const intlProvider = new IntlProvider({ locale: 'pt-br' }, {})
const { intl } = intlProvider.getChildContext()

function getBirthDate(rules) {
  const preparedRules = prepareDateRules(rules, intl)
  const birthDateInitialized = preparedRules.personalFields.find(
    rule => rule.name === 'birthDate',
  )
  return birthDateInitialized
}

describe('ProfileRules aux functions', () => {
  it('should filter the correct rules', () => {
    const rules = defaultRules
    const filteredFields = filterDateType(rules.personalFields)

    expect(filteredFields.length).toBe(1)
    expect(filteredFields[0].name).toBe('birthDate')
  })

  it('should set the functions to the rules of type date', () => {
    const rules = defaultRules
    const birthDate = filterDateType(rules.personalFields)[0]

    expect(birthDate.mask).toBeUndefined()
    expect(birthDate.validate).toBeDefined()
    expect(birthDate.display).toBeUndefined()
    expect(birthDate.submit).toBeUndefined()

    const birthDateInitialized = getBirthDate(rules)

    expect(birthDateInitialized.mask).toBeDefined()
    expect(birthDateInitialized.validate).toBeDefined()
    expect(birthDateInitialized.display).toBeDefined()
    expect(birthDateInitialized.submit).toBeDefined()
  })

  it('should mask correctly', () => {
    const rules = defaultRules
    const birthDateInitialized = getBirthDate(rules)

    expect(birthDateInitialized.mask('100')).toBe('10/0')
    expect(birthDateInitialized.mask('10/09')).toBe('10/09')
    expect(birthDateInitialized.mask('10/091994')).toBe('10/09/1994')
  })

  it('should validate correctly', () => {
    const rules = defaultRules
    const birthDateInitialized = getBirthDate(rules)

    expect(birthDateInitialized.validate('100')).toBeFalsy()
    expect(birthDateInitialized.validate('10/09/1994')).toBeTruthy()
    expect(birthDateInitialized.validate('29/02/1000')).toBeFalsy()
  })

  it('should display correctly', () => {
    const rules = defaultRules
    const birthDateInitialized = getBirthDate(rules)

    expect(birthDateInitialized.display('10/09/1994')).toBe('10/09/1994')
    expect(birthDateInitialized.display('2018-11-25T00:00:00')).toBe(
      '25/11/2018',
    )
  })

  it('should submit correctly', () => {
    const rules = defaultRules
    const birthDateInitialized = getBirthDate(rules)

    expect(birthDateInitialized.submit('25/11/2018')).toMatch(
      new RegExp('2018-11-25T([0-9])([0-9]):00:00Z'),
    )
  })

  describe('date', () => {
    it('empty date should be submitted as null', () => {
      const rules = defaultRules
      const birthDateInitialized = getBirthDate(rules)

      expect(birthDateInitialized.submit()).toBe(null)
    })

    it('invalid date should be submitted as null', () => {
      const rules = defaultRules
      const birthDateInitialized = getBirthDate(rules)

      expect(birthDateInitialized.submit('30/28/19501')).toBe(null)
      expect(birthDateInitialized.submit('not-a-date')).toBe(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 instore-profile/react/__tests__/StyleguideInput.test.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React from 'react'
import { shallowWithIntl, loadTranslation } from 'enzyme-react-intl'
import StyleguideInput from '../inputs/StyleguideInput'
import mockField from '../__mocks__/ruleField'
import mockData from '../__mocks__/profileField'

loadTranslation('../messages/pt.json')

describe('StyleguideInput', () => {
  let wrapper
  let mockChange
  let mockBlur
  beforeEach(() => {
    // Arrange
    mockChange = jest.fn()
    mockBlur = jest.fn()
    wrapper = shallowWithIntl(
      <StyleguideInput
        field={mockField}
        data={mockData}
        onChange={mockChange}
        onBlur={mockBlur}
      />,
    ).dive()
  })

  it('should render input based on rules', () => {
    // Act
    const result = wrapper.children().props().name

    // Assert
    expect(result).toBe(mockField.name)
  })

  it('should fill input with received data', () => {
    // Act
    const result = wrapper.children().props().value

    // Assert
    expect(result).toBe(mockData.value)
  })

  it('should display error if said so', () => {
    // Arrange
    const errorWrapper = shallowWithIntl(
      <StyleguideInput
        field={mockField}
        data={{ value: 'John', error: 'EMPTY_FIELD' }}
        onChange={mockChange}
        onBlur={mockBlur}
      />,
    ).dive()

    // Act
    const result = errorWrapper.children().props().errorMessage

    // Assert
    expect(result).toBeTruthy()
  })

  it('should not display hidden fields', () => {
    // Arrange
    const emptyWrapper = shallowWithIntl(
      <StyleguideInput
        field={{ name: 'firstName', label: 'firstName', hidden: true }}
        data={mockData}
        onChange={mockChange}
        onBlur={mockBlur}
      />,
    ).dive()

    // Assert
    expect(emptyWrapper).toHaveClassName('dn')
  })
})

```


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

[User] Show me the implementation of instore-profile/react/__tests__/ProfileContainer.test.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React from 'react'
import { shallowWithIntl, loadTranslation } from 'enzyme-react-intl'
import ProfileContainer from '../ProfileContainer'
import ProfileField from '../ProfileField'
import mockRules from '../__mocks__/rules'
import mockProfile from '../__mocks__/profile'

loadTranslation('../messages/pt.json')

describe('ProfileContainer', () => {
  let wrapper
  let mockSubmit
  beforeEach(() => {
    // Arrange
    mockSubmit = jest.fn()
    wrapper = shallowWithIntl(
      <ProfileContainer
        rules={mockRules}
        defaultProfile={mockProfile}
        onSubmit={mockSubmit}
      />,
    ).dive()
  })

  it('should render fields based on rules', () => {
    // Act
    const result = wrapper.find(ProfileField)

    // Assert
    expect(result).toHaveLength(4)
  })

  it('should pass down profile data to fields', () => {
    // Act
    const firstName = wrapper
      .find(ProfileField)
      .first()
      .props().data.value
    const lastName = wrapper
      .find(ProfileField)
      .last()
      .props().data.value

    // Assert
    expect(firstName).toBe('John')
    expect(lastName).toBe('Appleseed')
  })

  it('should update its state when receives changes', () => {
    // Act
    wrapper.instance().handleFieldUpdate({
      firstName: {
        value: 'Jack',
      },
    })
    wrapper.update()
    const result = wrapper.state().profile.firstName.value

    // Assert
    expect(result).toBe('Jack')
  })

  it('should call onSubmit with a validated profile when necessary', () => {
    // Arrange
    const subRules = {
      ...mockRules,
      personalFields: [
        ...mockRules.personalFields,
        {
          name: 'document',
          maxLength: 30,
          label: 'document',
          required: true,
        },
      ],
    }
    const instance = shallowWithIntl(
      <ProfileContainer
        rules={subRules}
        defaultProfile={mockProfile}
        onSubmit={mockSubmit}
      />,
    )
      .dive()
      .instance()

    // Act
    instance.handleSubmit({
      preventDefault() {},
    })

    // Assert
    expect(mockSubmit).toHaveBeenCalledWith({
      profile: {
        birthDate: '23/05/92',
        firstName: 'John',
        gender: null,
        lastName: 'Appleseed',
        tradeName: null,
        document: null,
        isCorporate: false,
      },
      valid: false,
    })
  })

  it('should include isCorporate in profile object when submitting', () => {
    // Arrange
    const corpProfile = {
      isCorporate: true,
    }
    const instance = shallowWithIntl(
      <ProfileContainer
        rules={mockRules}
        defaultProfile={corpProfile}
        onSubmit={mockSubmit}
      />,
    )
      .dive()
      .instance()

    // Act
    instance.handleSubmit({
      preventDefault() {},
    })

    // Assert
    expect(mockSubmit).toHaveBeenCalledWith({
      profile: { isCorporate: true },
      valid: 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 instore-profile/react/__tests__/setupTests.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import 'jest-enzyme'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

Enzyme.configure({ adapter: new Adapter() })

global.console.warn = warn => {
  throw new Error(warn)
}

```


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

[User] Show me the implementation of instore-profile/react/__tests__/ProfileSummary.test.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React from 'react'
import { shallowWithIntl, loadTranslation } from 'enzyme-react-intl'
import ProfileSummary from '../ProfileSummary'
import mockRules from '../__mocks__/rules'
import mockProfile from '../__mocks__/profile'

loadTranslation('../messages/pt.json')

describe('ProfileSummary', () => {
  let wrapper
  beforeEach(() => {
    // Arrange
    wrapper = shallowWithIntl(
      <ProfileSummary profile={mockProfile} rules={mockRules}>
        {displayData => <span displayData={displayData}>It works!</span>}
      </ProfileSummary>,
    ).dive()
  })

  it('should render its children', () => {
    // Act
    const result = wrapper.find('span')

    // Assert
    expect(result).toHaveLength(1)
  })

  it('should pass down the data in the correct structure', () => {
    // Act
    const result = wrapper.find('span').props().displayData

    // Assert
    expect(result.personalData).toBeTruthy()
    expect(result.personalData.firstName).toBeTruthy()
    expect(result.businessData).toBeTruthy()
  })

  it('should correctly signal hidden fields in the data', () => {
    // Arrange
    const hiddenRules = {
      ...mockRules,
      businessFields: [
        {
          name: 'tradeName',
          label: 'tradeName',
          hidden: true,
        },
      ],
    }
    const hiddenWrapper = shallowWithIntl(
      <ProfileSummary profile={mockProfile} rules={hiddenRules}>
        {displayData => <span displayData={displayData}>It works!</span>}
      </ProfileSummary>,
    ).dive()

    // Act
    const result = hiddenWrapper.find('span').props().displayData.businessData
      .tradeName

    // Assert
    expect(result.hidden).toBe(true)
  })

  it('should translate the gender before serving', () => {
    // Arrange
    const panProfile = { ...mockProfile, gender: 'pangender' }
    const panWrapper = shallowWithIntl(
      <ProfileSummary profile={panProfile} rules={mockRules}>
        {displayData => <span displayData={displayData}>It works!</span>}
      </ProfileSummary>,
    ).dive()

    // Act
    const result = panWrapper.find('span').props().displayData.personalData
      .gender

    // Assert
    expect(result.value).toBe('Pangênero')
  })

  it('should apply pre-display transformation to data if necessary', () => {
    // Arrange
    const preProfile = { ...mockProfile, tradeName: 'Apple Inc.' }
    const preRules = {
      ...mockRules,
      businessFields: [
        {
          name: 'tradeName',
          label: 'tradeName',
          display: value => value.toUpperCase(),
        },
      ],
    }
    const preWrapper = shallowWithIntl(
      <ProfileSummary profile={preProfile} rules={preRules}>
        {displayData => <span displayData={displayData}>It works!</span>}
      </ProfileSummary>,
    ).dive()

    // Act
    const result = preWrapper.find('span').props().displayData.businessData
      .tradeName

    // Assert
    expect(result.value).toBe('APPLE INC.')
  })

  it('should pass down the isCorporate profile attribute', () => {
    // Arrange
    const corpProfile = { ...mockProfile, isCorporate: true }
    const preWrapper = shallowWithIntl(
      <ProfileSummary profile={corpProfile} rules={mockRules}>
        {displayData => <span displayData={displayData}>It works!</span>}
      </ProfileSummary>,
    ).dive()

    // Act
    const result = preWrapper.find('span').props().displayData.isCorporate

    // Assert
    expect(result).toBe(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 instore-profile/react/__tests__/validateProfile.test.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import {
  applyMask,
  applyValidation,
  addFocusToFirstInvalidInput,
  isProfileValid,
  applyFullValidation,
} from '../modules/validateProfile'
import addValidation from '../modules/addValidation'
import removeValidation from '../modules/removeValidation'
import cleanProfile from '../__mocks__/profile'
import validatedProfile from '../__mocks__/validatedProfile'
import invalidProfile from '../__mocks__/invalidProfile'
import mockRules from '../__mocks__/rules'

describe('validateProfile', () => {
  it('should add validation data to a clean profile', () => {
    // Act
    const result = addValidation(cleanProfile, mockRules)

    // Assert
    expect(result).toEqual({
      birthDate: { value: '23/05/92' },
      firstName: { value: 'John' },
      gender: { value: null },
      lastName: { value: 'Appleseed' },
      tradeName: { value: null },
    })
  })

  it('should apply pre-display transformation to data if necessary', () => {
    // Arrange
    const displayRules = {
      ...mockRules,
      businessFields: [
        {
          name: 'tradeName',
          display: value => value.toUpperCase(),
        },
      ],
    }
    const displayProfile = { ...cleanProfile, tradeName: 'Apple Inc.' }

    // Act
    const result = addValidation(displayProfile, displayRules)

    // Assert
    expect(result).toEqual({
      birthDate: { value: '23/05/92' },
      firstName: { value: 'John' },
      gender: { value: null },
      lastName: { value: 'Appleseed' },
      tradeName: { value: 'APPLE INC.' },
    })
  })

  it('should remove validation data from a validated profile', () => {
    // Act
    const result = removeValidation(validatedProfile, mockRules)

    // Assert
    expect(result).toEqual({
      birthDate: '23/05/92',
      firstName: 'John',
      gender: null,
      lastName: 'Appleseed',
      tradeName: null,
    })
  })

  it('should apply pre-submit transformation to data if necessary', () => {
    // Arrange
    const submitRules = {
      ...mockRules,
      businessFields: [
        {
          name: 'tradeName',
          submit: value => value.toUpperCase(),
        },
      ],
    }
    const submitProfile = {
      ...validatedProfile,
      tradeName: { value: 'Apple Inc.' },
    }

    // Act
    const result = removeValidation(submitProfile, submitRules)

    // Assert
    expect(result).toEqual({
      birthDate: '23/05/92',
      firstName: 'John',
      gender: null,
      lastName: 'Appleseed',
      tradeName: 'APPLE INC.',
    })
  })

  it('should apply a given mask to a value', () => {
    // Arrange
    const mockField = { mask: value => '**' + value + '**' }

    // Act
    const result = applyMask(mockField, 'hello')

    // Assert
    expect(result).toBe('**hello**')
  })

  it('should validate a required field', () => {
    // Arrange
    const mockField = { required: true }

    // Act
    const result = applyValidation(mockField, '')

    // Assert
    expect(result).toBe('EMPTY_FIELD')
  })

  it('should validate a field according to rules', () => {
    // Arrange
    const mockField = { validate: value => value.length === 3 }

    // Act
    const validResult = applyValidation(mockField, 'AAA')
    const invalidResult = applyValidation(mockField, 'AAAA')

    // Assert
    expect(validResult).toBeNull()
    expect(invalidResult).toBe('INVALID_FIELD')
  })

  it('should check if a profile is valid', () => {
    // Act
    const result = isProfileValid(invalidProfile)

    // Assert
    expect(result).toBe(false)
  })

  it('should apply focus to the first invalid input', () => {
    // Arrange
    const focusRules = {
      personalFields: [
        ...mockRules.personalFields,
        { name: 'gender', required: true },
      ],
    }

    // Act
    const focusedProfile = addFocusToFirstInvalidInput(
      focusRules,
      invalidProfile,
    )

    // Assert
    expect(focusedProfile.gender.focus).toBe(true)
  })

  it('should not validate business fields if the profile is not corporate', () => {
    // Arrange
    const corpRules = {
      personalFields: [...mockRules.personalFields],
      businessFields: [
        ...mockRules.businessFields,
        {
          name: 'stateRegistration',
          required: true,
        },
      ],
    }

    // Act
    const checkedProfile = applyFullValidation(
      corpRules,
      validatedProfile,
      false,
    )

    // Assert
    expect(checkedProfile.stateRegistration.error).not.toBeTruthy()
  })

  it('should validate business fields if the profile is corporate', () => {
    // Arrange
    const corpRules = {
      personalFields: [...mockRules.personalFields],
      businessFields: [
        ...mockRules.businessFields,
        {
          name: 'stateRegistration',
          required: true,
        },
      ],
    }

    // Act
    const checkedProfile = applyFullValidation(
      corpRules,
      validatedProfile,
      true,
    )

    // Assert
    expect(checkedProfile.stateRegistration.error).toBeTruthy()
  })
  it('should check for emojis', () => {
    const rules = {
      personalFields: [...mockRules.personalFields],
      businessFields: [],
    }

    const profile = { ...validatedProfile }

    const validProfile = applyFullValidation(rules, profile, false)

    expect(validProfile.firstName.error).toBeFalsy()

    profile.firstName.value = '🥰'

    const inValidProfile = applyFullValidation(rules, profile, false)

    expect(inValidProfile.firstName.error).toBeTruthy()
  })
})

```


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

[User] Show me the implementation of instore-profile/react/__tests__/ProfileField.test.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React from 'react'
import { shallow } from 'enzyme'
import ProfileField from '../ProfileField'
import mockField from '../__mocks__/ruleField'
import mockData from '../__mocks__/profileField'
import StyleguideInput from '../inputs/StyleguideInput'

describe('ProfileField', () => {
  let wrapper
  let mockChange
  beforeEach(() => {
    // Arrange
    mockChange = jest.fn()
    wrapper = shallow(
      <ProfileField
        field={mockField}
        data={mockData}
        onFieldUpdate={mockChange}
        Input={StyleguideInput}
      />,
    )
  })

  it('should pass down received rules and data', () => {
    // Act
    const fieldResult = wrapper.find(StyleguideInput).props().field
    const dataResult = wrapper.find(StyleguideInput).props().data

    // Assert
    expect(fieldResult).toBe(mockField)
    expect(dataResult).toBe(mockData)
  })

  it('should call onFieldUpdate when receives new data', () => {
    // Act
    wrapper.instance().handleChange({ target: { value: 'Joe' } })

    // Assert
    expect(mockChange).toHaveBeenCalled()
  })

  it('should mask data if necessary before passing up', () => {
    // Arrange
    const maskField = {
      ...mockField,
      mask: value => '-' + value + '-',
    }
    const maskWrapper = shallow(
      <ProfileField
        field={maskField}
        data={mockData}
        onFieldUpdate={mockChange}
        Input={StyleguideInput}
      />,
    )

    // Act
    maskWrapper.instance().handleChange({ target: { value: '123456789' } })

    // Assert
    expect(mockChange).toHaveBeenCalledWith({
      [maskField.name]: {
        ...mockData,
        value: '-123456789-',
        error: null,
      },
    })
  })

  it('should validate touched fields before passing up', () => {
    // Arrange
    const valField = { ...mockField, required: true }
    const valData = { ...mockData, touched: true }
    const valWrapper = shallow(
      <ProfileField
        field={valField}
        data={valData}
        onFieldUpdate={mockChange}
        Input={StyleguideInput}
      />,
    )

    // Act
    valWrapper.instance().handleChange({ target: { value: '' } })

    // Assert
    expect(mockChange).toHaveBeenCalledWith({
      [valField.name]: {
        ...valData,
        value: '',
        error: 'EMPTY_FIELD',
      },
    })
  })

  it('should not validate pristine fields before passing up', () => {
    // Arrange
    const valField = { ...mockField, required: true }
    const valData = { ...mockData, touched: false }
    const valWrapper = shallow(
      <ProfileField
        field={valField}
        data={valData}
        onFieldUpdate={mockChange}
        Input={StyleguideInput}
      />,
    )

    // Act
    valWrapper.instance().handleChange({ target: { value: '' } })

    // Assert
    expect(mockChange).toHaveBeenCalledWith({
      [valField.name]: {
        ...valData,
        value: '',
        error: 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 instore-profile/react/rules/CRI.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import costarica from '@vtex/phone/countries/CRI'

import { getPhoneFields } from '../modules/phone'
import regexValidation from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(costarica)

export default {
  country: 'CRI',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'CRI_cedula',
      hidden: true,
      validate: regexValidation(/^\d{10}$/),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
      hidden: true,
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'CRI_cedula',
      hidden: true,
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/FRA.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import france from '@vtex/phone/countries/FRA'

import { getPhoneFields } from '../modules/phone'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(france)

export default {
  country: 'FRA',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/GBR.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import gbr from '@vtex/phone/countries/GBR' // Used for initialization purposes, do not remove it!

import { getPhoneFields } from '../modules/phone'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(gbr)

export default {
  country: 'GBR',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/ROU.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import { isPastDate } from '../utils/dateRules'

export default {
  country: 'ROU',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'corporateDocument',
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/ESP.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import spain from '@vtex/phone/countries/ESP'

import { getPhoneFields } from '../modules/phone'
import regexValidation from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(spain)

export default {
  country: 'ESP',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'ESP_dni',
      required: false,
      validate: regexValidation(/^(?:\d{8}|[A-z]\d{7})-?[A-z]{1}$/),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      required: false,
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'ESP_cif',
      validate: regexValidation(/^[A-z]{1}\d{8}$/),
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/USA.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import usa from '@vtex/phone/countries/USA' // Used for initialization purposes, do not remove it!

import { getPhoneFields } from '../modules/phone'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'
import regexValidation, { regexEmail } from '../modules/regexValidation'

const phoneCountryCode = initialize(usa)

export default {
  country: 'USA',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'document',
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      required: true,
      validate: regexValidation(regexEmail),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      required: true,
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
      required: true,
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
      required: true,
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'corporateDocument',
      required: true,
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: 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 instore-profile/react/rules/URY.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import uruguay from '@vtex/phone/countries/URY' // Used for initialization purposes, do not remove it!

import { getPhoneFields } from '../modules/phone'
import regexValidation from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(uruguay)

function validateCedulaURY(value) {
  var baseArray, c, i, intArray, j, k, len, len1, verifiyDigit
  value = value.replace(/\-|\./g, '')
  intArray = []
  for (j = 0, len = value.length; j < len; j++) {
    c = value[j]
    intArray.push(parseInt(c))
  }
  //array base para validação no Uruguai
  baseArray = [8, 1, 2, 3, 4, 7, 6]
  verifiyDigit = 0
  //executa o cálculo para criação do dígito verificador
  for (i = k = 0, len1 = baseArray.length; k < len1; i = ++k) {
    value = baseArray[i]
    verifiyDigit += baseArray[i] * intArray[i]
  }
  verifiyDigit %= 10
  //valida o dígito verificador
  return verifiyDigit === intArray[intArray.length - 1]
}

export default {
  country: 'URY',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'URY_cedula',
      required: true,
      validate: validateCedulaURY,
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'URY_rut',
      validate: regexValidation(/^\d{12}$/),
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/ECU.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import ecuador from '@vtex/phone/countries/ECU'

import { getPhoneFields } from '../modules/phone'
import regexValidation from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(ecuador)

function validateCedulaECU(value) {
  var c,
    calculatedVerifyDigit,
    documentWithOnlyNumbers,
    evenDigitsSum,
    i,
    intArray,
    j,
    len,
    nextDozen,
    oddDigitMultiplied,
    oddDigitsSum,
    provinceCode,
    sum,
    temp
  // o número é formado por 10 dígitos, podendo ter um '-' entre o nono e o décimo
  if (RegExp(/^[0-9]{9}-[0-9]{1}$|^[0-9]{10}$/).test(value)) {
    // remove traços contidos no documento
    documentWithOnlyNumbers = value.replace('-', '')
    // converte o array de caracteres em um array de inteiros
    intArray = []
    for (j = 0, len = documentWithOnlyNumbers.length; j < len; j++) {
      c = documentWithOnlyNumbers[j]
      intArray.push(parseInt(c))
    }
    // os dois primeiros dígitos correspondem à província e devem ser um número de 01 a 24
    provinceCode = intArray[0] * 10 + intArray[1]
    if (provinceCode < 1 || provinceCode > 24) {
      return false
    }
    evenDigitsSum = 0
    oddDigitsSum = 0
    // percorre o array de dígitos desconsiderando o dígito verificador
    i = 0
    while (i < intArray.length - 1) {
      // soma-se todos os dígitos de posição par do array
      // verifica se a posição atual é par (+1 é devido ao fato do array começar na posição zero)
      if ((i + 1) % 2 === 0) {
        evenDigitsSum += intArray[i]
      } else {
        // os dígitos da posição ímpar devem ser multiplicador por 2. Se o resultado da multiplicação der um número maior que 9, subtrair 9 a esse número.
        // Ao final, somar o resultado de todas essas contas
        oddDigitMultiplied = intArray[i] * 2
        if (oddDigitMultiplied > 9) {
          oddDigitMultiplied -= 9
        }
        oddDigitsSum += oddDigitMultiplied
      }
      i++
    }
    // o dígito verificador é calculado pela subtração da próxima dezena da soma dos cálculos acima pelo resultado da soma

    // cálcula a soma dos resultados acima
    sum = oddDigitsSum + evenDigitsSum
    // calcula a próxima dezena
    temp = sum / 10.0
    temp = Math.ceil(temp)
    nextDozen = temp * 10
    // calcula o dígito verificador
    calculatedVerifyDigit = nextDozen - sum
    // verifica se o calculado é igual ao passado
    return calculatedVerifyDigit === intArray[intArray.length - 1]
  }

  return false
}

export default {
  country: 'ECU',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'ECU_cedula',
      required: true,
      validate: validateCedulaECU,
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'ECU_ruc',
      validate: regexValidation(/^\d{13}$/),
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: true,
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/PRT.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import regexValidation from '../modules/regexValidation'
import { isPastDate } from '../utils/dateRules'

export default {
  country: 'PRT',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'PRT_nif',
      validate: regexValidation(/^\d+$/),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'PRT_nipc',
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/MEX.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import mexico from '@vtex/phone/countries/MEX'

import { getPhoneFields } from '../modules/phone'
import regexValidation, { regexEmail } from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(mexico)

export default {
  country: 'MEX',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      required: true,
      validate: regexValidation(regexEmail),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      required: true,
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'MEX_rfc',
      validate: regexValidation(/^[a-zA-Z]{4}[0-9]{6}(?:[a-zA-Z0-9]{3}|)$/),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
      required: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'MEX_rfc',
      required: true,
      validate: regexValidation(/^[a-zA-Z]{4}[0-9]{6}(?:[a-zA-Z0-9]{3}|)$/),
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'MEX_rfc_corporate',
      required: true,
      validate: regexValidation(/^[a-zA-Z]{3}[0-9]{6}[a-zA-Z0-9]{3}$/),
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
      required: true,
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: 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 instore-profile/react/rules/PAN.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import panama from '@vtex/phone/countries/PAN'

import { getPhoneFields } from '../modules/phone'
import regexValidation from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(panama)

export default {
  country: 'PAN',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'PAN_cip',
      required: true,
      validate: regexValidation(/^[a-zA-Z0-9]{5,30}$/),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'PAN_ruc',
      validate: regexValidation(/^(\w{6,12})$/),
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: true,
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/ARG.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import argentina from '@vtex/phone/countries/ARG'

import { getPhoneFields } from '../modules/phone'
import regexValidation, { regexEmail } from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(argentina)

export default {
  country: 'ARG',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      required: true,
      validate: regexValidation(regexEmail),
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'ARG_dni',
      required: true,
      validate: regexValidation(/^[A-z]?\d{6,8}$/),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      required: true,
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
      required: true,
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
      required: true,
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'ARG_cuit',
      required: true,
      validate: regexValidation(/^([\d]{2})?([\d]{8})?([\d]{1})$/),
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: true,
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/BRA.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import msk from 'msk'
import brazil from '@vtex/phone/countries/BRA'

import { getPhoneFields } from '../modules/phone'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'
import regexValidation, { regexEmail } from '../modules/regexValidation'

const phoneCountryCode = initialize(brazil)

export default {
  country: 'BRA',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      required: true,
      validate: regexValidation(regexEmail),
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'BRA_cpf',
      required: true,
      mask: value => msk.fit(value, '999.999.999-99'),
      validate: cpf => {
        if (!cpf) {
          return false
        }

        let remainder

        cpf = !cpf || typeof cpf !== 'string' ? '' : cpf.replace(/[^\d]+/g, '')

        if (
          cpf === '00000000000' ||
          cpf === '11111111111' ||
          cpf === '22222222222' ||
          cpf === '33333333333' ||
          cpf === '44444444444' ||
          cpf === '55555555555' ||
          cpf === '66666666666' ||
          cpf === '77777777777' ||
          cpf === '88888888888' ||
          cpf === '99999999999'
        ) {
          return false
        }

        const cpfDigits = cpf.split('').map(Number)
        const firstElement = 0
        const cpfDigitsArray = [firstElement].concat(cpfDigits)

        const sum1 = cpfDigitsArray.reduce(function(acc, value, index) {
          if (index < 10) {
            return acc + value * (11 - index)
          }

          return acc
        })

        remainder = (sum1 * 10) % 11

        if (remainder === 10 || remainder === 11) remainder = 0
        if (remainder !== parseInt(cpf.substring(9, 10), 10)) return false

        const sum2 = cpfDigitsArray.reduce(function(acc, value, index) {
          if (index < 11) {
            return acc + value * (12 - index)
          }

          return acc
        })

        remainder = (sum2 * 10) % 11

        if (remainder === 10 || remainder === 11) remainder = 0
        if (remainder !== parseInt(cpf.substring(10, 11), 10)) return false

        return true
      },
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      required: true,
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
      required: true,
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'BRA_cnpj',
      required: true,
      mask: value => msk.fit(value, '99.999.999/9999-99'),
      validate: cnpj => {
        if (!cnpj) {
          return false
        }

        cnpj = cnpj.replace(/[^\d]+/g, '')

        if (cnpj.length !== 14) {
          return false
        }

        if (
          cnpj === '00000000000000' ||
          cnpj === '11111111111111' ||
          cnpj === '22222222222222' ||
          cnpj === '33333333333333' ||
          cnpj === '44444444444444' ||
          cnpj === '55555555555555' ||
          cnpj === '66666666666666' ||
          cnpj === '77777777777777' ||
          cnpj === '88888888888888' ||
          cnpj === '99999999999999'
        ) {
          return false
        }

        // Validate DVs
        let size = cnpj.length - 2
        let numbers = cnpj.substring(0, size)
        const digits = cnpj.substring(size)
        let sum = 0
        let pos = size - 7

        for (let i = size; i >= 1; i--) {
          sum += parseInt(numbers.charAt(size - i), 10) * pos--
          if (pos < 2) {
            pos = 9
          }
        }

        let result = sum % 11 < 2 ? 0 : 11 - (sum % 11)

        if (result !== parseInt(digits.charAt(0), 10)) {
          return false
        }

        size += 1
        numbers = cnpj.substring(0, size)
        sum = 0
        pos = size - 7
        for (let i = size; i >= 1; i--) {
          sum += parseInt(numbers.charAt(size - i), 10) * pos--
          if (pos < 2) {
            pos = 9
          }
        }

        result = sum % 11 < 2 ? 0 : 11 - (sum % 11)
        if (result !== parseInt(digits.charAt(1), 10)) {
          return false
        }

        return true
      },
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: true,
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
      required: 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 instore-profile/react/rules/GTM.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import guatemala from '@vtex/phone/countries/GTM'

import { getPhoneFields } from '../modules/phone'
import regexValidation from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(guatemala)

export default {
  country: 'GTM',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'GTM_dpi',
      required: true,
      validate: regexValidation(
        /^[\d]{8}(?:\-|)[\d]{1}(?:\-|)[\d]{2}(?:\-|)[\d]{2}$/,
      ),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'GTM_nit',
      validate: regexValidation(/^[\d]{7}(?:\-|)[\dkK]{1}$/),
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/KOR.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import korea from '@vtex/phone/countries/KOR'

import { getPhoneFields } from '../modules/phone'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(korea)

export default {
  country: 'KOR',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'document',
      required: true,
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'corporateDocument',
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/PER.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import peru from '@vtex/phone/countries/PER'

import { getPhoneFields } from '../modules/phone'
import regexValidation from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(peru)

export default {
  country: 'PER',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'PER_document',
      required: true,
      validate: regexValidation(/^[a-zA-Z0-9]{8,12}$/),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'PER_ruc',
      validate: regexValidation(/^[0-9]{11}$|^[0-9]{8}$/),
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/PRY.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import paraguay from '@vtex/phone/countries/PRY'

import { getPhoneFields } from '../modules/phone'
import regexValidation from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(paraguay)

export default {
  country: 'PRY',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'PRY_cedula',
      required: true,
      validate: regexValidation(/^(\w{4,8}(?:\-|)\w{1})$/),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'PRY_ruc',
      validate: regexValidation(/^(\w{4,8}(?:\-|)\w{1})$/),
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: true,
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/CAN.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import canada from '@vtex/phone/countries/CAN'

import { getPhoneFields } from '../modules/phone'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(canada)

export default {
  country: 'CAN',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/initializeCountryPhone.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import Phone from '@vtex/phone'

export default function initialize(country) {
  const phoneCountryCode = country.countryCode
  Phone.countries[phoneCountryCode] = country

  return phoneCountryCode
}

```


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

[User] Show me the implementation of instore-profile/react/rules/default.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import { isPastDate } from '../utils/dateRules'
import regexValidation, { regexEmail } from '../modules/regexValidation'

export default {
  country: 'UNI',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      required: true,
      validate: regexValidation(regexEmail),
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'document',
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
      required: true,
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
      required: true,
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'corporateDocument',
      required: true,
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: true,
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/CHL.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import chile from '@vtex/phone/countries/CHL'

import { getPhoneFields } from '../modules/phone'
import regexValidation from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(chile)

function validateRUT(rut) {
  var caracteres, dig, dv, i, j, k, resto, serie, sumatoria
  // Codigo inspirado de http://metaltux.cl/2014/06/12/script-de-validacion-de-rut-chileno-en-javascript/
  if (/^\d{1,2}\.?\d{3}\.?\d{3}\-?[\dkK]$/.test(rut)) {
    rut = rut.replace(/[.-]/g, '')
    if (rut.length === 8) {
      rut = '0' + rut
    }
    rut = rut.substr(0, 8) + '-' + rut.substr(8, 1)
    caracteres = []
    serie = [2, 3, 4, 5, 6, 7]
    dig = rut.toString().substr(rut.toString().length - 1, 1)
    rut = rut.toString().substr(0, rut.toString().length - 2)
    i = 0
    while (i < rut.length) {
      caracteres[i] = parseInt(rut.charAt(rut.length - (i + 1)))
      i++
    }
    sumatoria = 0
    k = 0
    resto = 0
    j = 0
    while (j < caracteres.length) {
      if (parseInt(k, 10) === 6) {
        k = 0
      }
      sumatoria += parseInt(caracteres[j]) * parseInt(serie[k])
      k++
      j++
    }
    resto = sumatoria % 11
    dv = 11 - resto
    if (parseInt(dv, 10) === 10) {
      dv = 'K'
    } else if (parseInt(dv, 10) === 11) {
      dv = 0
    }

    if (
      dv
        .toString()
        .trim()
        .toUpperCase() ===
      dig
        .toString()
        .trim()
        .toUpperCase()
    ) {
      return true
    }

    return false
  }

  return false
}

export default {
  country: 'CHL',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'CHL_rut',
      required: false,
      validate: validateRUT,
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'CHL_rut',
      validate: regexValidation(/^0*(\d{1,3}(\.?\d{3})*)\-?([\dkK])$/),
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: true,
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/COL.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import colombia from '@vtex/phone/countries/COL'

import { getPhoneFields } from '../modules/phone'
import regexValidation, { regexEmail } from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(colombia)

export default {
  country: 'COL',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      required: true,
      validate: regexValidation(regexEmail),
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'COL_cedula',
      required: true,
      validate: regexValidation(/^[\d]{6,12}$/),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      required: true,
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
      required: true,
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
      required: true,
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'COL_rut',
      required: true,
      validate: regexValidation(/^[\d]{5,}$/),
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: true,
    },
    {
      name: 'stateRegistration',
      maxLength: 50,
      label: 'stateRegistration',
      required: true,
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/rules/VEN.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import venezuela from '@vtex/phone/countries/VEN'

import { getPhoneFields } from '../modules/phone'
import regexValidation from '../modules/regexValidation'
import initialize from './initializeCountryPhone'
import { isPastDate } from '../utils/dateRules'

const phoneCountryCode = initialize(venezuela)

export default {
  country: 'VEN',
  personalFields: [
    {
      name: 'firstName',
      maxLength: 100,
      label: 'firstName',
      required: true,
    },
    {
      name: 'lastName',
      maxLength: 100,
      label: 'lastName',
      required: true,
    },
    {
      name: 'email',
      maxLength: 100,
      label: 'email',
      hidden: true,
    },
    {
      name: 'document',
      maxLength: 50,
      label: 'VEN_cedula',
      required: true,
      validate: regexValidation(/^[VvJjEe]-?\d{6,8}$/),
    },
    {
      name: 'homePhone',
      maxLength: 30,
      label: 'homePhone',
      ...getPhoneFields(phoneCountryCode),
    },
    {
      name: 'gender',
      maxLength: 30,
      label: 'gender',
    },
    {
      name: 'birthDate',
      maxLength: 30,
      label: 'birthDate',
      type: 'date',
      validate: isPastDate,
    },
  ],
  businessFields: [
    {
      name: 'corporateName',
      maxLength: 100,
      label: 'corporateName',
    },
    {
      name: 'tradeName',
      maxLength: 100,
      label: 'tradeName',
    },
    {
      name: 'corporateDocument',
      maxLength: 30,
      label: 'VEN_rif',
      validate: regexValidation(/^[VvJjEe]-?\d{6,8}-?\d$/),
    },
    {
      name: 'businessPhone',
      maxLength: 30,
      label: 'businessPhone',
      ...getPhoneFields(phoneCountryCode),
    },
  ],
}

```


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

[User] Show me the implementation of instore-profile/react/modules/validateProfile.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
export function applyMask(field, value) {
  return field.mask ? field.mask(value) : value
}

export function applyValidation(field, value) {
  if (!value || !value.trim()) {
    return field.required ? 'EMPTY_FIELD' : null
  }

  return (field.validate && !field.validate(value)) || containsEmoji(value)
    ? 'INVALID_FIELD'
    : null
}

export function applyFullValidation(rules, profile, isCorporate) {
  const validatedProfile = Object.keys(profile)
    .map(field => {
      const rule =
        rules.personalFields.find(rule => rule.name === field) ||
        rules.businessFields.find(rule => rule.name === field && isCorporate)

      if (rule) {
        const error = applyValidation(rule, profile[field].value)

        return { [field]: { ...profile[field], error } }
      }

      return { [field]: { value: null } }
    })
    .reduce((acc, cur) => ({ ...acc, ...cur }), {})

  return addFocusToFirstInvalidInput(rules, validatedProfile)
}

export function isProfileValid(profile) {
  return !Object.keys(profile).some(field => profile[field].error != null)
}

export function addFocusToFirstInvalidInput(rules, profile) {
  const firstInvalidInput =
    rules.personalFields.find(field => profile[field.name].error != null) ||
    rules.businessFields.find(field => profile[field.name].error != null)

  if (firstInvalidInput == null) return profile

  const focusedInput = { ...profile[firstInvalidInput.name], focus: true }

  return { ...profile, [firstInvalidInput.name]: focusedInput }
}

function containsEmoji(input) {
  // Emojis until version 11.0
  const EMOJIS_REGEX = /(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/

  return EMOJIS_REGEX.test(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 instore-profile/react/modules/emptyProfile.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
export default {
  birthDate: null,
  businessPhone: null,
  corporateDocument: null,
  corporateName: null,
  document: null,
  email: null,
  firstName: null,
  gender: null,
  homePhone: null,
  lastName: null,
  stateRegistration: null,
  tradeName: null,
  isCorporate: 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 instore-profile/react/modules/phone.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
import Phone from '@vtex/phone'

export function validatePhone(countryCode) {
  return value => Phone.validate(value, countryCode)
}

export function formatPhone(countryCode) {
  return value => {
    const phoneDigits = value.replace(/[^\d]+/g, '')
    const phone =
      value.indexOf('+') === 0
        ? Phone.getPhoneInternational(phoneDigits, countryCode)
        : Phone.getPhoneNational(phoneDigits, countryCode)

    if (!phone) return value.replace(/[^\d]+/g, '')

    return Phone.format(phone, Phone.NATIONAL)
  }
}

export function cleanPhone(countryCode) {
  return value => {
    const numbers = value.replace(/[^\d]/g, '')

    try {
      const phone = Phone.getPhoneNational(numbers, countryCode)

      if (!phone) return value

      return Phone.format(phone, Phone.INTERNATIONAL)
    } catch (err) {
      return numbers
    }
  }
}

export function getPhoneFields(phoneCountryCode) {
  return {
    mask: formatPhone(phoneCountryCode),
    validate: validatePhone(phoneCountryCode),
    display: formatPhone(phoneCountryCode),
    submit: cleanPhone(phoneCountryCode),
  }
}

```


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

[User] Show me the implementation of instore-profile/react/modules/addValidation.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
export default function addValidation(profile, rules) {
  const allRules = [...rules.personalFields, ...rules.businessFields]

  return allRules
    .map(field => ({
      [field.name]: {
        value:
          field.display && profile[field.name]
            ? field.display(profile[field.name])
            : profile[field.name],
      },
    }))
    .reduce((acc, cur) => ({ ...acc, ...cur }), {})
}

```


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

[User] Show me the implementation of instore-profile/react/modules/removeValidation.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
export default function removeValidation(profile, rules) {
  const allRules = [...rules.personalFields, ...rules.businessFields]

  return allRules.reduce((acc, field) => {
    const fieldValue = profile[field.name].value

    if (field.submit && fieldValue != null) {
      acc[field.name] = field.submit(fieldValue)
    } else {
      acc[field.name] = fieldValue
    }

    return acc
  }, {})
}

```


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

[User] Show me the implementation of instore-profile/react/modules/regexValidation.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
export default function regexValidation(customRegex) {
  const regex = new RegExp(customRegex)

  return value => regex.test(value)
}

export const regexEmail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

```


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

[User] Show me the implementation of instore-profile/react/modules/genders.js from the instore-profile VTEX app.

[Assistant]
Here's the implementation:

```javascript
export default [
  'agender',
  'androgyne',
  'bigender',
  'genderfluid',
  'nonconforming',
  'questioning',
  'variant',
  'genderqueer',
  'neutrois',
  'pangender',
  'transgender',
  'transsexual',
  'other',
]

```