[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 trustpilot/react/modules/invitation.ts from the trustpilot VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { OrderPlacedTrackedData } from '../typings/events'

export function createProductInvitation(eventData: OrderPlacedTrackedData) {
  const { visitorContactInfo, orderGroup, transactionProducts } = eventData

  const [email, name, lastname] = visitorContactInfo
  const products = transactionProducts.map(product => {
    return {
      sku: product.sku,
      productUrl: `${window.location.origin}/${product.slug}/p`,
      name: product.name,
    }
  })
  const skus = products.map(p => p.sku)

  const tpData = {
    recipientEmail: email,
    recipientName: `${name} ${lastname}`,
    referenceId: orderGroup,
    source: 'InvitationScript',
    productSkus: skus,
    products,
  }

  window.tp('createInvitation', tpData)
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "memory": 256,
  "ttl": 10,
  "timeout": 2,
  "minReplicas": 1,
  "maxReplicas": 1,
  "workers": 1,
  "routes": {
    "status": {
      "path": "/_v/status/:code",
      "public": true
    }
  }
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "dependencies": {
    "co-body": "^6.0.0",
    "ramda": "^0.25.0"
  },
  "devDependencies": {
    "@types/co-body": "^0.0.3",
    "@types/jest": "^24.0.18",
    "@types/node": "^12.0.0",
    "@types/ramda": "types/npm-ramda#dist",
    "@vtex/api": "6.45.15",
    "@vtex/test-tools": "^1.0.0",
    "@vtex/tsconfig": "^0.5.6",
    "typescript": "3.9.7",
    "vtex.b2b-core": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.b2b-core@0.0.1/public/@types/vtex.b2b-core"
  },
  "resolutions": {
    "@types/testing-library__dom": "6.12.1",
    "@types/express": "4.16.0",
    "@types/express-serve-static-core": "4.16.0"
  },
  "scripts": {
    "lint": "tsc --noEmit --pretty"
  },
  "version": "1.0.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 vtex-b2b-core/node/index.ts from the vtex-b2b-core VTEX app.

[Assistant]
Here's the implementation:

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

import { Clients } from './clients'
import { status } from './middlewares/status'
import { validate } from './middlewares/validate'

const TIMEOUT_MS = 800

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

metrics.trackCache('status', memoryCache)

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

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

  interface State extends RecorderState {
    code: number
  }
}

export default new Service({
  clients,
  routes: {
    status: method({
      GET: [validate, status],
    }),
  },
})

```


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

[User] Show me the implementation of vtex-b2b-core/public/metadata/messages/es-AR.json from the vtex-b2b-core VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "B2B Core",
  "headline": "B2B Core",
  "overview": "B2B Core",
  "features": ["B2B Core"],
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


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

[User] Show me the implementation of vtex-b2b-core/public/metadata/messages/pt-BR.json from the vtex-b2b-core VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "B2B Core",
  "headline": "B2B Core",
  "overview": "B2B Core",
  "features": ["B2B Core"],
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


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

[User] Show me the implementation of vtex-b2b-core/public/metadata/messages/en-US.json from the vtex-b2b-core VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "B2B Core",
  "headline": "B2B Core",
  "overview": "B2B Core",
  "features": ["B2B Core"],
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


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

[User] Show me the implementation of vtex-b2b-core/masterdata/buyerOrgMember/schema.json from the vtex-b2b-core VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "title": "buyerOrgMember",
  "properties": {
    "customerId": {
      "type": "string",
      "title": "CustomerId"
    },
    "name": {
      "type": "string",
      "title": "Name"
    },
    "email": {
      "type": "string",
      "title": "Email"
    },
    "role": {
      "type": "string",
      "title": "Role"
    }
  },
  "v-indexed": ["id", "customerId"],
  "v-cache": 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 vtex-b2b-core/masterdata/buyerOrgConfiguration/schema.json from the vtex-b2b-core VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "title": "buyerOrgConfiguration",
  "properties": {
    "sellers": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "title": "Sellers"
    },
    "accessControlList": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "title": "AccessControlList"
    },
    "tradePolicy": {
      "type": "string",
      "title": "TradePolicy"
    },
    "canEditAddress": {
      "type": "boolean",
      "title": "CanEditAddress"
    }
  },
  "v-indexed": ["id"],
  "v-cache": 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 vtex-b2b-core/node/clients/status.ts from the vtex-b2b-core VTEX app.

[Assistant]
Here's the implementation:

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

export default class Status extends ExternalClient {
  constructor(context: IOContext, options?: InstanceOptions) {
    super('http://httpstat.us', context, options)
  }

  public async getStatus(status: number): Promise<string> {
    return this.http.get(status.toString(), {
      metric: 'status-get',
    })
  }

  public async getStatusWithHeaders(
    status: number
  ): Promise<IOResponse<string>> {
    return this.http.getRaw(status.toString(), {
      metric: 'status-get-raw',
    })
  }

  public async getStatusAndForceMaxAge(
    status: number
  ): Promise<IOResponse<string>> {
    return this.http.get(status.toString(), {
      forceMaxAge: 5000,
      metric: 'status-get-forceMaxAge',
    })
  }
}

```


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

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

[Assistant]
Here's the implementation:

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

import Status from './status'

export class Clients extends IOClients {
  public get status() {
    return this.getOrSet('status', Status)
  }
}

```


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

[User] Show me the implementation of vtex-b2b-core/node/middlewares/status.ts from the vtex-b2b-core VTEX app.

[Assistant]
Here's the implementation:

```typescript
export async function status(ctx: Context, next: () => Promise<any>) {
  const {
    state: { code },
    clients: { status: statusClient },
  } = ctx

  console.info('Received code:', code)

  const statusResponse = await statusClient.getStatus(code)

  console.info('Status response:', statusResponse)

  const {
    headers,
    data,
    status: responseStatus,
  } = await statusClient.getStatusWithHeaders(code)

  console.info('Status headers', headers)
  console.info('Status data:', data)

  ctx.status = responseStatus
  ctx.body = data
  ctx.set('Cache-Control', headers['cache-control'])

  await next()
}

```


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

[User] Show me the implementation of vtex-b2b-core/node/middlewares/validate.ts from the vtex-b2b-core VTEX app.

[Assistant]
Here's the implementation:

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

export async function validate(ctx: Context, next: () => Promise<any>) {
  const {
    vtex: {
      route: { params },
    },
  } = ctx

  console.info('Received params:', params)

  const { code } = params

  if (!code) {
    throw new UserInputError('Code is required')
  }

  const codeNumber = parseInt(code as string, 10)

  ctx.state.code = codeNumber

  await next()
}

```


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

[User] Show me the implementation of search-segment-graphql/graphql/schema.graphql from the search-segment-graphql VTEX app.

[Assistant]
Here's the implementation:

```graphql
type Query {
  searchSegment(
    userEmail: String
    isAuthenticated: Boolean
    selectedFacets: [SelectedFacetsInput]
  ): [SelectedFacets] @cacheControl(scope: PUBLIC, maxAge: SHORT)
}

```


[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 search-segment-graphql/node/package.json from the search-segment-graphql VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "search-graphql",
  "description": "Don't delete this file, it's necessary to generate the TypeScript types of the GraphQL"
}

```


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

[User] Show me the implementation of search-segment-graphql/graphql/types/SelectedFacets.graphql from the search-segment-graphql VTEX app.

[Assistant]
Here's the implementation:

```graphql
type SelectedFacets {
  key: String
  value: String
}

input SelectedFacetsInput {
  key: String
  value: String
}

```


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

[User] Show me the implementation of flixmedia/docs/README.md from the flixmedia VTEX app.

[Assistant]
Here's the implementation:

```markdown
📢 Use this project, [contribute](https://github.com/vtex-apps/flixmedia) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).

# Flixmedia

> 🚧 WARNING
>
> This app is no longer supported. Consider using the [Flixmedia](https://apps.vtex.com/acupula-flixmedia/p) app by ACCT as an alternative.

Flixmedia first party integration app. The [solution](https://flixmedia.eu/) enhances your website content, capturing retail partners, engaging shoppers, and increasing sale rates.

## Configuration

### Step 1 - Installing the Flixmedia app

#### Using VTEX App Store

1. Access the Apps section in your account's admin page.
2. Look for the Flixmedia app.
3. Click on the `Install` button.

#### Using VTEX IO Toolbelt

In your terminal, log into your VTEX account and [install](https://vtex.io/docs/recipes/development/installing-an-app/) the `vtex.flixmedia@0.x` app.

> ℹ *You can confirm if the app has been properly installed by running `vtex ls`.*

### Step 2 - Defining the app settings

1. Access the Flixmedia app in your admin's Apps section.
2. Fill out the fields according to your Flixmedia data.
3. Save your changes.

![flixmedia-gif](https://user-images.githubusercontent.com/52087100/101814695-41cca680-3afd-11eb-975e-5db39d825f98.gif)

### Step 3 - Updating your store theme

1. Add the Flixmedia app to your theme's dependencies in the `manifest.json` file:

```diff
 dependencies: {
+  "vtex.flixmedia": "0.x"
 }
```

2. Declare the `product-details.flixmedia` block in the `store.product`'s children list, as shown below:

```json
"store.product": {
  "children": [
    "product-description.flixmedia",
  ]
}
```

3. [Deploy your changes](https://vtex.io/docs/recipes/store-management/making-your-theme-content-public/).

## Customization

No CSS Handles are available yet for the app customization.

## Contributors ✨

Thanks goes to these wonderful people:

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!

<!-- DOCS-IGNORE:end -->

```


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

[Assistant]
Here's the implementation:

```graphql
# Default GraphQL Type. You can learn more about GraphQL here: http://graphql.org/learn/

# Specifies the available queries.
# The resolvers for this query are implemented in here: node/graphql/index.ts

type Query {
  publicAppSettings: Settings @cacheControl(scope: SEGMENT, maxAge: MEDIUM)
}

type Settings {
  flixDistributor: String
  flixLanguage: String
  flixBrand: String
  flixButton: String
  flixInpage: String
  flixButtonImage: String
  flixPrice: String
  flixFallback: String
}
```


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

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

[Assistant]
Here's the implementation:

```json
{
  "name": "node",
  "version": "0.1.9",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "axios": "^0.18.0"
  },
  "devDependencies": {
    "@vtex/api": "^3.3.1",
    "eslint": "^5.16.0",
    "eslint-config-vtex": "^10.1.0",
    "prettier": "^1.18.2",
    "typescript": "3.5.2"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

```


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

[Assistant]
Here's the implementation:

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

declare var process: {
  env: {
    VTEX_APP_ID: string
  }
}

export default new Service({
  graphql: {
    resolvers: {
      Query: {
        publicAppSettings: async function publicAppSettings(
          _: any,
          __: any,
          ctx: Context<IOClients>
        ) {
          const {
            clients: { apps },
          } = ctx
          const settings = await apps.getAppSettings(process.env.VTEX_APP_ID)
          return settings
        },
      },
    },
  },
})
```


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

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

[Assistant]
Here's the implementation:

```json
{
  "name": "reviews",
  "dependencies": {
    "apollo-client": "2.4.12",
    "graphql": "14.1.1",
    "prop-types": "15.6.2",
    "react": "16.3.2",
    "react-apollo": "2.4.1"
  },
  "devDependencies": {
    "@types/classnames": "^2.2.7",
    "@types/graphql": "^14.2.0",
    "@types/jest": "^24.0.11",
    "@types/node": "^11.13.0",
    "@types/prop-types": "^15.7.0",
    "@types/ramda": "^0.26.5",
    "@types/react": "^16.8.10",
    "@types/react-intl": "^2.3.17",
    "@vtex/test-tools": "^0.2.0",
    "apollo-client": "^2.5.1",
    "eslint": "^5.16.0",
    "eslint-config-vtex": "^10.1.0",
    "eslint-config-vtex-react": "^4.1.0",
    "prettier": "^1.18.2",
    "tslint-eslint-rules": "^5.4.0",
    "typescript": "3.5.2"
  },
  "version": "0.1.9"
}

```


[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 flixmedia/react/FlixMedia.js from the flixmedia VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React, { useEffect } from 'react'
import publicAppSettings from './graphql/publicAppSettings.gql'
import { graphql } from 'react-apollo'
import withProductContext from './components/withProductContext'

function FlixMedia({
  data: { loading, publicAppSettings },
  product,
  selectedItem,
}) {
  useEffect(() => {
    if (loading) {
      return
    }

    const sku = selectedItem ? selectedItem : product.items[0]

    const referenceId =
      sku && sku.referenceId && sku.referenceId.length > 0
        ? sku.referenceId[0].Value
        : ''

    const script = document.createElement('script')
    script.src = '//media.flixfacts.com/js/loader.js'
    script.async = true
    script.setAttribute('id', 'flixmedia')
    script.setAttribute(
      'data-flix-distributor',
      publicAppSettings.flixDistributor
    )

    if (sku.ean) {
      script.setAttribute('data-flix-ean', sku.ean)
    } else {
      script.setAttribute('data-flix-mpn', referenceId)
    }

    script.setAttribute('data-flix-language', publicAppSettings.flixLanguage)
    script.setAttribute('data-flix-brand', publicAppSettings.flixBrand)
    script.setAttribute('data-flix-sku', sku.itemId)
    script.setAttribute('data-flix-inpage', publicAppSettings.flixInpage)
    script.setAttribute('data-flix-button', publicAppSettings.flixButton || '')
    script.setAttribute('data-flix-price', publicAppSettings.flixPrice || '')
    script.setAttribute(
      'data-flix-fallback',
      publicAppSettings.flixFallback || ''
    )

    document.body.appendChild(script)

    return () => {
      const previousScript = document.getElementById('flixmedia')
      if (previousScript && previousScript.parentNode) {
        previousScript.parentNode.removeChild(previousScript)
      }
    }
  }, [loading, product, selectedItem, publicAppSettings])

  return (
    <div>
      <div id="flix-minisite"></div>
      <div id="flix-inpage"></div>
    </div>
  )
}

const withPublicAppSettings = graphql(publicAppSettings, {
  options: () => ({
    ssr: false,
  }),
})

export default withPublicAppSettings(withProductContext(FlixMedia))

```


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

[Assistant]
Here's the implementation:

```json
{
  "product-description.flixmedia": {
    "component": "FlixMedia"
  }
}

```


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

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.product-context' {
  import { Context } from 'react'

  interface ProductContext {
    product: any
  }

  export const ProductContext = Context
}

```


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

[Assistant]
Here's the implementation:

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

  const value: DocumentNode
  export default value
}

```


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

[User] Show me the implementation of flixmedia/react/components/withProductContext.js from the flixmedia VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React, { useContext } from 'react'
import { ProductContext } from 'vtex.product-context'

function withProductContext(Component) {
  return function ProductContextWrapper(props) {
    const { product, selectedItem } = useContext(ProductContext)
    return (
      <Component {...props} product={product} selectedItem={selectedItem} />
    )
  }
}

export default withProductContext

```


[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 flixmedia/react/graphql/publicAppSettings.gql from the flixmedia VTEX app.

[Assistant]
Here's the implementation:

```graphql
query publicAppSettings {
  publicAppSettings {
    flixDistributor
    flixLanguage
    flixBrand
    flixButton
    flixInpage
    flixButtonImage
    flixPrice
    flixFallback
  }
}
```


[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 admin-organizations/messages/pt.json from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin-authorization.navigation.label-group": "Autorizações",
  "admin-authorization.navigation.label-details": "Exemplo de detalhes",
  "admin-authorization.navigation.label-table": "Exemplo de tabela",
  "admin-authorization.navigation.search.kws": "teste, mock, fake",
  "admin-authorization.navigation.details.search.kws": "detalhe, mock, test, oi",
  "admin-authorization.navigation.table.search.kws": "tabela, mock, test, tchau",
  "admin-authorization.hello-world": "Admin de exemplo",
  "admin-authorization.navigation.label-permissions": "All Permissions",
  "admin-authorization.navigation.label-roles": "All Roles",
  "admin-authorization.navigation.roles.search.kws": "roles, vtex",
  "admin-authorization.navigation.label-user-roles": "User roles",
  "admin-authorization.navigation.user-roles.search.kws": "user role, vtex",
  "admin-authorization.permissions.title": "Permissions",
  "admin-authorization.roles.title": "Roles",
  "admin-authorization.user-roles.title": "User roles"
}
```


[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 admin-organizations/messages/en.json from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin-authorization.navigation.label-group": "Authorizations",
  "admin-authorization.navigation.label-details": "All Permissions",
  "admin-authorization.navigation.label-table": "Example table",
  "admin-authorization.navigation.search.kws": "test, mock, fake",
  "admin-authorization.navigation.details.search.kws": "details, mock, test, hello",
  "admin-authorization.navigation.table.search.kws": "table, mock, test, bye",
  "admin-authorization.hello-world": "Example Admin",
  "admin-authorization.navigation.label-permissions": "All Permissions",
  "admin-authorization.navigation.permissions.search.kws": "permissions, vtex",
  "admin-authorization.navigation.label-roles": "All Roles",
  "admin-authorization.navigation.roles.search.kws": "roles, vtex",
  "admin-authorization.navigation.label-user-roles": "User roles",
  "admin-authorization.navigation.user-roles.search.kws": "user role, vtex",
  "admin-authorization.permissions.title": "Permissions",
  "admin-authorization.roles.title": "Roles",
  "admin-authorization.user-roles.title": "User roles"
}

```


[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 admin-organizations/messages/ro.json from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin-authorization.navigation.label-group": "Autorizări",
  "admin-authorization.navigation.label-details": "Toate permisiunile",
  "admin-authorization.navigation.label-table": "Exemplu tabel",
  "admin-authorization.navigation.search.kws": "test, simulare, fals",
  "admin-authorization.navigation.details.search.kws": "detalii, simulare, test, bună",
  "admin-authorization.navigation.table.search.kws": "tabel, simulare, test, pa",
  "admin-authorization.hello-world": "Exemplu Admin",
  "admin-authorization.navigation.label-permissions": "Toate permisiunile",
  "admin-authorization.navigation.permissions.search.kws": "permisiuni, VTEX",
  "admin-authorization.navigation.label-roles": "Toate rolurile",
  "admin-authorization.navigation.roles.search.kws": "roluri, VTEX",
  "admin-authorization.navigation.label-user-roles": "Roluri utilizator",
  "admin-authorization.navigation.user-roles.search.kws": "rol utilizator, VTEX",
  "admin-authorization.permissions.title": "Permisiuni",
  "admin-authorization.roles.title": "Roluri",
  "admin-authorization.user-roles.title": "Roluri utilizator"
}

```


[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 admin-organizations/messages/context.json from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin-authorization.navigation.label": "Example admin",
  "admin-authorization.hello-world": "",
  "appframe.navigation.example": ""
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "admin-authorization.navigation.label-group": "Autorizaciones",
  "admin-authorization.navigation.label-details": "Ejemplo de detalhes",
  "admin-authorization.navigation.label-table": "Ejemplo de tabela",
  "admin-authorization.navigation.search.kws": "teste, mock, fake",
  "admin-authorization.navigation.details.search.kws": "detalhe, mock, test, oi",
  "admin-authorization.navigation.table.search.kws": "tabela, mock, test, tchau",
  "admin-authorization.hello-world": "Admin de ejemplo",
  "admin-authorization.navigation.label-permissions": "All Permissions",
  "admin-authorization.navigation.label-roles": "All Roles",
  "admin-authorization.navigation.roles.search.kws": "roles, vtex",
  "admin-authorization.navigation.label-user-roles": "User roles",
  "admin-authorization.navigation.user-roles.search.kws": "user role, vtex",
  "admin-authorization.permissions.title": "Permissions",
  "admin-authorization.roles.title": "Roles",
  "admin-authorization.user-roles.title": "User roles"
}
```


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

[Assistant]
Here's the implementation:

```json
{
  "section": "accountSettings",
  "titleId": "admin-authorization.navigation.label-group",
  "subSection": "authorization",
  "searchKeyWordsHelpers": "admin-authorization.navigation.search.kws",
  "subSectionItems": [
    {
      "labelId": "admin-authorization.navigation.label-permissions",
      "path": "/admin/authorization/permissions",
      "searchKeyWordsHelpers": "admin-authorization.navigation.permissions.search.kws"
    },
    {
      "labelId": "admin-authorization.navigation.label-roles",
      "path": "/admin/authorization/roles",
      "searchKeyWordsHelpers": "admin-authorization.navigation.roles.search.kws"
    }
  ]
}

```


[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 admin-organizations/admin/routes.json from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin.app.authorization-permissions": {
    "component": "Permissions",
    "path": "/admin/app/authorization/permissions"
  },
  "admin.app.authorization-roles": {
    "component": "Roles",
    "path": "/admin/app/authorization/roles"
  }
}

```


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

[Assistant]
Here's the implementation:

```markdown
# Admin Organizations

This is a admin application for managing `Roles` and `Permissions` for organizations on a B2B Store.

## Usage

Install latest version of this app, then you can see the features in admin view.

```js
vtex install vtex.admin-organizations@1.x
```

### Prerequisites

In order to run this application following master data schemas should be created.
Use `MASTER DATA API - V2` in vtex api documentation to create those schemas (https://developers.vtex.com/reference#master-data-api-v2-overview)

These schemas are shared among several applications `admin-organizations`, `organizations-challenge` and `organizations`, therefore if you have already created these schemas you can ignore this step

<details><summary>Permissions</summary>

```

Data Entity Name: BusinessPermission
Schema Name: business-permission-schema-v1

{
	"properties": {
		"name": {
			"type": "string"
		},
		"label": {
			"type": "string"
		}
	},
	"v-default-fields": [
		"name",
		"label",
		"id"
	],
	"required": [
		"name"
	],
	"v-indexed": [
		"name"
	],
	"v-security": {
		"allowGetAll": true,
		"publicRead": [
			"name",
			"label",
			"id"
		],
		"publicWrite": [
			"name",
			"label"
		],
		"publicFilter": [
			"name",
			"id"
		]
	}
}

```
</details>

<details><summary>Roles</summary>

```

Data Entity Name: BusinessRole
Schema Name: business-role-schema-v1

{
	"properties": {
		"name": {
			"type": "string"
		},
		"label": {
			"type": "string"
		},
		"permissions": {
			"type": "string"
		}
	},
	"definitions": {
		"permission": {
			"type": "string"
		}
	},
	"v-default-fields": [
		"name",
		"label",
		"id",
		"permissions"
	],
	"required": [
		"name"
	],
	"v-indexed": [
		"name"
	],
	"v-security": {
		"allowGetAll": true,
		"publicRead": [
			"name",
			"label",
			"permissions",
			"id"
		],
		"publicWrite": [
			"name",
			"label",
			"permissions"
		],
		"publicFilter": [
			"name",
			"id"
		]
	}
}

```
</details>

### Add Required roles
You will need `manager` role to be created for fully functioning other related applications
Use `label` as `Manager` and `name` as `manager` to create `Manager` role

```


[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 admin-organizations/react/Roles.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```tsx
import Roles from './components/roles/Roles'

export default Roles

```


[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 admin-organizations/react/Permissions.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```tsx
import Permissions from './components/permissions/Permissions'

export default Permissions

```


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

[Assistant]
Here's the implementation:

```json
{
  "name": "vtex.admin-example",
  "version": "1.1.0",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "@types/node": "^11.12.1",
    "@types/react": "^16.8.10",
    "@types/react-intl": "^2.3.17",
    "@types/ramda": "^0.26.21",
    "prop-types": "^15.7.2",
    "typescript": "3.8.3",
    "prettier": "^1.16.4",
    "tslint": "^5.16.0",
    "tslint-config-vtex": "^2.1.0"
  },
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-intl": "3.9.1",
    "@types/faker": "^4.1.5",
    "faker": "^4.1.0",
    "react-apollo": "^3.1.3",
    "apollo-client": "^2.4.7",
    "graphql": "^14.0.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 admin-organizations/react/styles.global.css from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```css
html,
body,
#render-container,
#render-provider,
.render-container,
.render-provider {
  height: 100%;
}

.addPermissionLabel{
  padding-top: 8px;
}

.addPermissionMenu {
  margin-left: 10px;
}

.vtex-modal__overlay {
  z-index: 998 !important;
}

```


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

[User] Show me the implementation of admin-organizations/react/Toast.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useEffect, useState } from 'react'
import { FormattedMessage } from 'react-intl'
import { Alert } from 'vtex.styleguide'

interface Props {
  showToast: boolean
  message: string
  type: string
  onClose: () => void
}

const Toast = ({ showToast = false, type, message, onClose }: Props) => {
  const [isClosing, setIsClosing] = useState(!showToast)

  let closingTimeout: any
  let openTimeout: any

  useEffect(() => {
    setIsClosing(false)
    openTimeout = setTimeout(() => {
      setIsClosing(true)
      closingTimeout = setTimeout(() => {
        onClose()
      }, 3000)
    }, 5000)

    return () => {
      clearTimeout(openTimeout)
      clearTimeout(closingTimeout)
    }
  }, [showToast])

  return (
    <div
      className={`animated ${
        isClosing ? 'fadeOutDown' : 'fadeInUp'
      }  slower bottom--1 fixed z-5 ma7-ns mb5-s left-2-ns w-100-s w-30-ns`}
    >
      <Alert type={type} onClose={onClose}>
        {message}
      </Alert>
    </div>
  )
}

export default Toast

```


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

[Assistant]
Here's the implementation:

```typescript
import { ReactNode } from "react";
import { ApolloError } from "apollo-client";

declare global {
  interface ChallengeProps {
    children: ReactNode[];
  }

  interface MDField {
    key: string;
    value: string;
  }

  interface MDSearchResult {
    loading: boolean;
    error?: ApolloError;
    data: MDSearchData;
  }

  interface MDSearchData {
    documents: MDSearchDocumentResult[];
  }

  interface MDSearchDocumentResult {
    id: string;
    fields: MDField[];
  }

  interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {
    schema?: object;
    getSchema?(props?: P): object;
  }

  interface Role {
    id: string
    label: string;
    name: string;
    permissions: string;
  }

  interface Permission {
    name: string;
    label: string;
    id?: string;
  }

  interface TostMessage {
    showToast: boolean
    message: string
    type: string
  }
}

```


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

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

[Assistant]
Here's the implementation:

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

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

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

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

  interface ChildBlock<BlockProps> {
    props: BlockProps
  }

  export const ExtensionPoint: ComponentType<ExtensionPointProps>
  export const useChildBlock: <BlockProps>({
    id,
  }: {
    id: string
  }) => ChildBlock<BlockProps> | null
  export const Helmet: ReactElement
  export const Link: ReactType
  export const NoSSR: ReactElement
  export const RenderContextConsumer: any
  export const TreePathContextConsumer: any
  export const useTreePath: any
  export const useRuntime: any
  export const canUseDOM: boolean
  export const withRuntimeContext: <TOriginalProps extends {}>(
    Component: ComponentType<TOriginalProps & RenderContextProps>
  ) => ComponentType<TOriginalProps>

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

  interface KeyValue {
    value: string
  }

  interface Session {
    id: string
    namespaces: {
      profile: {
        isAuthenticated: KeyValue
      }
    }
  }

  interface SessionUnauthorized {
    type: 'Unauthorized'
    message: string
  }

  export interface RenderSession {
    sessionPromise: Promise<SessionPromise>
  }

  export interface SessionPromise {
    response: Session | SessionUnauthorized
  }
}

```


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

[Assistant]
Here's the implementation:

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

  const value: DocumentNode
  export default value
}

```


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

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

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.styleguide' {
  import { ComponentType } from 'react'
  export const Button: ComponentType<InputProps>
  export const Dropdown: ComponentType<InputProps>
  export const Input: ComponentType<InputProps>
  export const Table: ComponentType<InputProps>
  export const EmptyState: ComponentType<InputProps>
  export const PageHeader: ComponentType<InputProps>
  export const Layout: ComponentType<InputProps>
  export const PageBlock: ComponentType<InputProps>
  export const Divider: ComponentType<InputProps>
  export const ButtonWithIcon: ComponentType<InputProps>
  export const IconCheck: ComponentType<InputProps>
  export const Modal: ComponentType<InputProps>
  export const ModalDialog: ComponentType<InputProps>
  export const Alert: ComponentType<InputProps>
  export const ToastProvider: ComponentType<InputProps>
  export const ToastConsumer: ComponentType<InputProps>
  export const Spinner: ComponentType<InputProps>
  export const ActionMenu: ComponentType<InputProps>

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

```


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

[User] Show me the implementation of admin-organizations/react/utils/documentSerializer.ts from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const documentSerializer = (documents: any) => {

  if (!documents || documents.length === 0) {
    return []
  }

  const fieldReducer = (fieldsAccumulator: any, field: any) => {
    fieldsAccumulator[field.key] = field.value
    return fieldsAccumulator
  }

  const documentReducer = (documentAccumulator: any, document: any) => {
    documentAccumulator.push(document.fields.reduce(fieldReducer, {}))
    return documentAccumulator
  }

  return documents.reduce(documentReducer, [])
}

```


[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 admin-organizations/react/utils/consts.ts from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const PERMISSIONS_ACRONYM = 'BusinessPermission'
export const PERMISSIONS_FIELDS = ['id', 'name', 'label']
export const PERMISSIONS_SCHEMA = 'business-permission-schema-v1'

export const ROLES_ACRONYM = 'BusinessRole'
export const ROLES_SCHEMA = 'business-role-schema-v1'
export const ROLES_FIELDS = ['id', 'name', 'label', 'permissions']

```


[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 admin-organizations/react/utils/stringFormatter.ts from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const formatString = (str?: string) => (str? str: '')
```


[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 admin-organizations/react/utils/graphqlErrorHandler.ts from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { pathOr } from 'ramda'

export const getErrorMessage = (e: any) => {
  const message = pathOr(
    '',
    [
      'graphQLErrors',
      0,
      'extensions',
      'exception',
      'response',
      'data',
      'Message',
    ],
    e
  )
  return message
}

export const handleGlobalError = () => {
  return (e: Error) => {
    var message: string = pathOr(
      '',
      [
        'graphQLErrors',
        0,
        'extensions',
        'exception',
        'response',
        'data',
        'Message',
      ],
      e
    )
    return Promise.reject(message)
  }
}

```


[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 admin-organizations/react/utils/cacheUtils.ts from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { find, pathOr, propEq, reject } from 'ramda'
import GET_DOCUMENTS from '../graphql/queries/documents.graphql'
import {
  PERMISSIONS_ACRONYM,
  PERMISSIONS_FIELDS,
  PERMISSIONS_SCHEMA,
  ROLES_ACRONYM,
  ROLES_FIELDS,
  ROLES_SCHEMA
} from './consts'

export const updateCacheAddPermission = (
  cache: any,
  data: any,
  name: string,
  label: string
) => {
  try {
    const response: any = cache.readQuery(getPermissions())
    const idC = pathOr('', ['createMyDocument', 'cacheId'], data)
    const writeData = {
      ...getPermissions(),
      data: {
        myDocuments: [
          ...response.myDocuments,
          {
            __typename: 'Document',
            fields: [
              { key: 'id', value: idC, __typename: 'Field' },
              { key: 'name', value: name, __typename: 'Field' },
              { key: 'label', value: label, __typename: 'Field' },
            ],
            id: idC,
          },
        ],
      },
    }
    cache.writeQuery(writeData)
  } catch (e) {
    console.log(e)
  }
}

export const updateCacheUpdatePermission = (
  cache: any,
  data: any,
  name: string,
  label: string
) => {
  try {
    const response: any = cache.readQuery(getPermissions())
    const idC = pathOr('', ['updateMyDocument', 'cacheId'], data)

    // const selectedPermission = find(propEq('id', idC), pathOr([], ['myDocuments'],response))

    const permissions = pathOr([], ['myDocuments'], response).map((x: any) => {
      if (x.id === idC) {
        x.fields = [
          { key: 'id', value: idC, __typename: 'Field' },
          { key: 'name', value: name, __typename: 'Field' },
          { key: 'label', value: label, __typename: 'Field' },
        ]
      }
      return x
    })

    const writeData = {
      ...getPermissions(),
      data: {
        myDocuments: permissions,
      },
    }
    cache.writeQuery(writeData)
  } catch (e) {
    console.log(e)
  }
}

export const updateCacheDeletePermission = (cache: any, data: any) => {
  try {
    const id = pathOr('', ['deleteMyDocument', 'cacheId'], data)
    const response: any = cache.readQuery(getPermissions())

    const writeData = {
      ...getPermissions(),
      data: { myDocuments: reject(propEq('id', id), response.myDocuments) },
    }

    cache.writeQuery(writeData)
  } catch (e) {
    console.log(e)
  }
}

export const updateCacheAddRole = (
  cache: any,
  data: any,
  name: string,
  label: string,
  selectedPermissions: Permission[]
) => {
  try {
    const response: any = cache.readQuery(getRoles())
    const idC = pathOr('', ['createMyDocument', 'cacheId'], data)

    const permissions = selectedPermissions && selectedPermissions.length > 0 ? selectedPermissions.map(x => x.id): []
    const writeData = {
      ...getRoles(),
      data: {
        myDocuments: [
          ...response.myDocuments,
          {
            __typename: 'Document',
            fields: [
              { key: 'id', value: idC, __typename: 'Field' },
              { key: 'name', value: name, __typename: 'Field' },
              { key: 'label', value: label, __typename: 'Field' },
              {
                key: 'permissions',
                value: JSON.stringify(permissions),
                __typename: 'Field',
              },
            ],
            id: idC,
          },
        ],
      },
    }
    cache.writeQuery(writeData)
  } catch (e) {
    console.log(e)
  }
}

export const updateCacheEditRole = (
  cache: any,
  data: any,
  name: string,
  label: string,
  selectedPermissions: Permission[]
) => {
  try {
    const response: any = cache.readQuery(getRoles())
    const idC = pathOr('', ['updateMyDocument', 'cacheId'], data)
    const permissions = selectedPermissions && selectedPermissions.length > 0 ? selectedPermissions.map(x => x.id): []
    const roles = pathOr([], ['myDocuments'], response).map((x: any) => {
      if (x.id === idC) {
        x.fields = [
          { key: 'id', value: idC, __typename: 'Field' },
          { key: 'name', value: name, __typename: 'Field' },
          { key: 'label', value: label, __typename: 'Field' },
          {
            key: 'permissions',
            value: JSON.stringify(permissions),
            __typename: 'Field',
          },
        ]
      }
      return x
    })

    const writeData = {
      ...getRoles(),
      data: {
        myDocuments: roles,
      },
    }
    cache.writeQuery(writeData)
  } catch (e) {
    console.log(e)
  }
}

export const updateCacheDeleteRole = (cache: any, data: any) => {
  try {
    const id = pathOr('', ['deleteMyDocument', 'cacheId'], data)
    const response: any = cache.readQuery(getRoles())

    const writeData = {
      ...getRoles(),
      data: { myDocuments: reject(propEq('id', id), response.myDocuments) },
    }

    cache.writeQuery(writeData)
  } catch (e) {
    console.log(e)
  }
}

const getPermissions = () => {
  return {
    query: GET_DOCUMENTS,
    variables: {
      acronym: PERMISSIONS_ACRONYM,
      fields: PERMISSIONS_FIELDS,
      page: 1,
      pageSize: 100,
      schema: PERMISSIONS_SCHEMA,
    },
  }
}

const getRoles = () => {
  return {
    query: GET_DOCUMENTS,
    variables: {
      acronym: ROLES_ACRONYM,
      fields: ROLES_FIELDS,
      page: 1,
      pageSize: 100,
      schema: ROLES_SCHEMA,
    },
  }
}

```


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

[User] Show me the implementation of admin-organizations/react/components/roles/Roles.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

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

import RolesList from './RolesList'

const Roles = () => {
  return (
    <Layout
      pageHeader={
        <PageHeader
          title={<FormattedMessage id="admin-authorization.roles.title" />}
        />
      }
    >
      <PageBlock variation="full">
        <RolesList />
      </PageBlock>
    </Layout>
  )
}

export default Roles

```


[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 admin-organizations/react/components/roles/RolesList.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { find, pathOr, propEq } from 'ramda'
import React, { useState } from 'react'
import { useQuery } from 'react-apollo'
import { Spinner, Table } from 'vtex.styleguide'
import DOCUMENTS from '../../graphql/queries/documents.graphql'
import '../../styles.global.css'
import '../../styles.global.css'
import Toast from '../../Toast'
import {
  PERMISSIONS_ACRONYM,
  PERMISSIONS_FIELDS,
  PERMISSIONS_SCHEMA,
  ROLES_ACRONYM,
  ROLES_FIELDS,
  ROLES_SCHEMA
} from '../../utils/consts'
import { documentSerializer } from '../../utils/documentSerializer'
import RoleDelete from './RoleDelete'
import RoleModal from './RoleModal'

const RolesList = () => {
  const {
    loading: loadingPermissions,
    error: errorPermissions,
    data: permissionsData,
  } = useQuery(DOCUMENTS, {
    variables: {
      acronym: PERMISSIONS_ACRONYM,
      fields: PERMISSIONS_FIELDS,
      page: 1,
      pageSize: 100,
      schema: PERMISSIONS_SCHEMA,
    },
  })

  const {
    loading: loadingRoles,
    error: errorRoles,
    data: rolesData,
  } = useQuery(DOCUMENTS, {
    variables: {
      acronym: ROLES_ACRONYM,
      fields: ROLES_FIELDS,
      page: 1,
      pageSize: 100,
      schema: ROLES_SCHEMA,
    },
  })

  const permissions: Permission[] = documentSerializer(
    pathOr([], ['myDocuments'], permissionsData)
  )
  const roles: Role[] = documentSerializer(
    pathOr([], ['myDocuments'], rolesData)
  )

  const [tableDensity, setTableDensity] = useState('low')
  const [searchValue, setSearchValue] = useState('')
  const [sharedRole, setSharedRole] = useState({} as Role)
  const [openRoleModal, setOpenRoleModal] = useState(false)
  const [openRoleDelete, setOpenRoleDelete] = useState(false)

  const [tostMessage, setTostMessage] = useState({showToast: false, message: '', type: '' } as TostMessage)

  const createNewRole = () => {
    setSharedRole({} as Role)
    setOpenRoleModal(true)
  }

  const editRole = (cellData: Role) => {
    setSharedRole(cellData)
    setOpenRoleModal(true)
  }

  const deleteRole = (cellData: Role) => {
    setSharedRole(cellData)
    setOpenRoleDelete(true)
  }

  const closeCreateEditModal = (message: string, messageType: string) => {

    setSharedRole({} as Role)
    setOpenRoleModal(false)

    if(messageType === 'error' || messageType === 'success'){
      setTostMessage({showToast: true, message, type: messageType } as TostMessage)
    }
  }

  const closeDeleteModal = (message: string, messageType: string) => {
    setSharedRole({} as Role)
    setOpenRoleDelete(false)

    if(messageType === 'error' || messageType === 'success'){
      setTostMessage({showToast: true, message, type: messageType } as TostMessage)
    }
  }

  const handleCloseToast = () => {
    setTostMessage({showToast: false, message: '', type: '' } as TostMessage)
  }

  const lineActions = [
    {
      label: () => `Edit`,
      onClick: ({ rowData }: any) => editRole(rowData),
    },
    {
      isDangerous: true,
      label: () => `Delete`,
      onClick: ({ rowData }: any) => deleteRole(rowData),
    },
  ]

  const getPermission = (id: string) => {
    const permission: Permission = permissions
      ? find(propEq('id', id))(permissions)
      : null
    return permission ? permission.label : ''
  }

  const getSchema = () => {
    let fontSize = 'f5'
    switch (tableDensity) {
      case 'low': {
        fontSize = 'f5'
        break
      }
      case 'medium': {
        fontSize = 'f6'
        break
      }
      case 'high': {
        fontSize = 'f7'
        break
      }
      default: {
        fontSize = 'f5'
        break
      }
    }
    return {
      properties: {
        label: {
          cellRenderer: ({ cellData }: any) => {
            return <span className={`ws-normal ${fontSize}`}>{cellData}</span>
          },
          title: 'Label',
        },
        name: {
          cellRenderer: ({ cellData }: any) => {
            return <span className={`ws-normal ${fontSize}`}>{cellData}</span>
          },
          title: 'Name',
        },
        permissions: {
          cellRenderer: ({ cellData }: any) => {
            return cellData ? (
              <div className={`ws-normal ${fontSize}`}>
                {cellData === null || cellData === '' || cellData === 'null' ? (
                  <div />
                ) : (
                  (JSON.parse(cellData) as any[]).map(x => (
                    <div>
                      <span className={`ws-normal ${fontSize}`}>
                        { getPermission(x) }
                      </span>
                    </div>
                  ))
                )}
              </div>
            ) : (
              <span />
            )
          },
          title: 'Permissions',
        },
      },
    }

  }
  return loadingPermissions || loadingRoles ? (
    <Spinner />
  ) : errorPermissions || errorRoles ? (
    <div>Error loading data</div>
  ) : (
    <div>
      <Table
        fullWidth
        updateTableKey={tableDensity}
        items={roles}
        schema={getSchema()}
        density="low"
        lineActions={lineActions}
        toolbar={{
          density: {
            buttonLabel: 'Line density',
            handleCallback: (density: string) => setTableDensity(density),
            highOptionLabel: 'High',
            lowOptionLabel: 'Low',
            mediumOptionLabel: 'Medium',
          },
          newLine: {
            handleCallback: () => createNewRole(),
            label: 'New',
          },
        }}
      />
      <RoleModal
        {...{
          allPermissions: permissions,
          closeModal: closeCreateEditModal,
          isModalOpen: openRoleModal,
          role: sharedRole,
        }}
      />
      <RoleDelete
        {...{
          closeModal: closeDeleteModal,
          isModalOpen: openRoleDelete,
          role: sharedRole,
        }}
      />
      {tostMessage.showToast && (
          <Toast
            type={tostMessage.type}
            showToast={tostMessage.showToast}
            message={tostMessage.message}
            onClose={handleCloseToast}
          />
        )}
    </div>
  )
}

export default RolesList

```


[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 admin-organizations/react/components/roles/RoleModal.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { contains, equals, find, propEq, reject } from 'ramda'
import React, { useEffect, useState } from 'react'
import { useMutation } from 'react-apollo'
import { ActionMenu, Button, Input, Modal, Table } from 'vtex.styleguide'
import CREATE_DOCUMENT from '../../graphql/mutations/createDocument.graphql'
import UPDATE_DOCUMENT from '../../graphql/mutations/updateDocument.graphql'
import '../../styles.global.css'
import { updateCacheAddRole, updateCacheEditRole } from '../../utils/cacheUtils'
import { ROLES_ACRONYM, ROLES_SCHEMA } from '../../utils/consts'
import { getErrorMessage } from '../../utils/graphqlErrorHandler'

interface Props {
  isModalOpen: boolean
  role: Role
  allPermissions: Permission[]
  closeModal: (message: string, type: string) => void
}

const RoleModal = (props: Props) => {
  const [isEdit, setIsEdit] = useState(false)
  const [id, setId] = useState('')
  const [name, setName] = useState('')
  const [label, setLabel] = useState('')
  const [selectedPermissions, setSelectedPermissions] = useState([] as Permission[])

  const [addRole] = useMutation(CREATE_DOCUMENT, {
    update: (cache: any, { data }: any) =>
      updateCacheAddRole(
        cache,
        data,
        name,
        label,
        selectedPermissions
      ),
  })
  const [editRole] = useMutation(UPDATE_DOCUMENT, {
    update: (cache: any, { data }: any) =>
      updateCacheEditRole(
        cache,
        data,
        name,
        label,
        selectedPermissions
      ),
  })

  const handleCloseModal = () => {
    props.closeModal('', 'close')
  }

  useEffect(() => {
    setIsEdit(props.role && props.role.id !== undefined && props.role.id !== '')
    setId(props.role && props.role.id ? props.role.id : '')
    setName(props.role && props.role.name ? props.role.name : '')
    setLabel(props.role && props.role.label ? props.role.label : '')
    setSelectedPermissions(
      props.role && props.role.permissions
        ? getSelectedPermissions(props.role.permissions): [] as Permission[]
      )
  }, [props.role])

  const getSelectedPermissions = (ids: any) => {
    if(ids === null || ids === '' || ids === 'null' || !ids || ids.length === 0) { return [] as Permission[] }
    const { allPermissions } = props
    return (JSON.parse(ids) as string[]).map(x => find(propEq('id', x))(allPermissions)) as Permission[]
  }

  const options = props.allPermissions.map(p => ({
    label: p.label,
    onClick: () => permissionSelected(p),
  }))

  const permissionSelected = (selected: Permission) => {
    if(!contains(selected, selectedPermissions)){
      setSelectedPermissions([...selectedPermissions, selected])
    }
  }

  const handleSave = () => {
    const roleFields = [
      { key: 'name', value: name },
      { key: 'label', value: label },
    ]

    if (isEdit) {
      roleFields.push({ key: 'id', value: id })
    }

    if(selectedPermissions && selectedPermissions.length > 0){
      const permissions = selectedPermissions.map(x => x.id)
      roleFields.push({ key: 'permissions', value: JSON.stringify(permissions) })
    }

    const save = isEdit ? editRole : addRole

    save({
      variables: {
        acronym: ROLES_ACRONYM,
        document: { fields: roleFields },
        schema: ROLES_SCHEMA,
      },
    }).catch((e) => {
      const message = getErrorMessage(e)
      props.closeModal(message, 'error')
    }).then(() => {
      props.closeModal(`successfully ${ isEdit? 'updated': 'created' } role "${label}"`, 'success')
    })
  }

  const tableScheme = {
    properties: {
      label: {
        cellRenderer: ({ cellData }: any) => {
          return (
            <span className={`ws-normal `}>
              {cellData}
            </span>
          )
        },
        title: 'Label',
      },
      name: {
        cellRenderer: ({ cellData }: any) => {
          return (
            <span className={`ws-normal `}>
              {cellData}
            </span>
          )
        },
        title: 'Name',
      },
    },
  }

  const lineActions = [
    {
      label: () => `Remove`,
      onClick: ({ rowData }: any) => removePermission(rowData),
    },
  ]

  const removePermission = (permission: Permission) => {
    setSelectedPermissions(reject(equals(permission), selectedPermissions))
  }

  return (
    <Modal
      isOpen={props.isModalOpen}
      title="Role"
      responsiveFullScreen
      centered
      bottomBar={
        <div className="nowrap">
          <span className="mr4">
            <Button variation="tertiary" onClick={handleCloseModal}>
              Cancel
            </Button>
          </span>
          <span>
            <Button variation="secondary" onClick={handleSave}>
              Save
            </Button>
          </span>
        </div>
      }
      onClose={handleCloseModal}
      className="rolesModal"
    >
      <div className="mb5">
        <Input
          placeholder="e.g. sales_manager"
          dataAttributes={{ 'hj-white-list': true, test: 'string' }}
          label="Name"
          value={name}
          onChange={(e: any) => setName(e.target.value)}
        />
      </div>
      <div className="mb5">
        <Input
          placeholder="e.g. Sales Manager"
          dataAttributes={{ 'hj-white-list': true, test: 'string' }}
          label="Label"
          value={label}
          onChange={(e: any) => setLabel(e.target.value)}
        />
      </div>
      <div className="ma3 flex">
        <div className="addPermissionLabel">Add Permissions</div>
        <div className="addPermissionMenu">
          <ActionMenu
            buttonProps={{
              variation: 'primary',
            }}
            options={options}
          />
        </div>
      </div>
      <Table fullWidth schema={tableScheme} items={selectedPermissions} lineActions={lineActions}/>
    </Modal>
  )
}

export default RoleModal

```


[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 admin-organizations/react/components/roles/RoleDelete.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useEffect, useState } from 'react'
import { useMutation } from 'react-apollo'
import { ModalDialog } from 'vtex.styleguide'
import DELETE_DOCUMENT from '../../graphql/mutations/deleteDocument.graphql'
import { updateCacheDeleteRole } from '../../utils/cacheUtils'
import { ROLES_ACRONYM } from '../../utils/consts'
import { getErrorMessage } from '../../utils/graphqlErrorHandler'

interface Props {
  isModalOpen: boolean
  role: Role
  closeModal: (message: string, type: string) => void
}

const RoleDelete = (props: Props) => {
  const [id, setId] = useState('')

  const [deleteRole] = useMutation(DELETE_DOCUMENT, {
    update: (cache: any, { data }: any) =>
    updateCacheDeleteRole(
        cache,
        data
      ),
  })

  useEffect(() => {
    setId(props.role && props.role.id ? props.role.id : '')
  }, [props.role])

  const handleConfirmation = () => {
    deleteRole({
      variables: {
        acronym: ROLES_ACRONYM,
        documentId: id,
      },
    }).catch((e) => {
      const message = getErrorMessage(e)
      props.closeModal(message, 'error')
    }).then(() => {
      props.closeModal(`successfully deleted role "${props.role.label}"`, 'success')
    })
  }

  const handleCancelation = () => {
    props.closeModal('', 'close')
  }

  return (
    <ModalDialog
      centered
      confirmation={{
        isDangerous: true,
        label: 'Delete',
        onClick: handleConfirmation,
      }}
      cancelation={{
        label: 'Cancel',
        onClick: handleCancelation,
      }}
      isOpen={props.isModalOpen}
      onClose={handleCancelation}
    >
      <h3>
        Confirm delete role "{props.role && props.role.name}"
      </h3>
    </ModalDialog>
  )
}

export default RoleDelete

```


[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 admin-organizations/react/components/permissions/PermissionDelete.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useEffect, useState } from 'react'
import { useMutation } from 'react-apollo'
import { Button, Input, ModalDialog } from 'vtex.styleguide'
import DELETE_DOCUMENT from '../../graphql/mutations/deleteDocument.graphql'
import { updateCacheDeletePermission } from '../../utils/cacheUtils'
import { PERMISSIONS_ACRONYM } from '../../utils/consts'
import { getErrorMessage } from '../../utils/graphqlErrorHandler'

interface Props {
  isModalOpen: boolean
  permission: Permission
  closeModal: (message: string, type: string) => void
}

const PermissionDelete = (props: Props) => {
  const [id, setId] = useState('')

  const [deletePermission] = useMutation(DELETE_DOCUMENT, {
    update: (cache: any, { data }: any) =>
      updateCacheDeletePermission(
        cache,
        data
      ),
  })

  useEffect(() => {
    setId(props.permission && props.permission.id ? props.permission.id : '')
  }, [props.permission])

  const handleConfirmation = () => {
    deletePermission({
      variables: {
        acronym: PERMISSIONS_ACRONYM,
        documentId: id,
      },
    }).catch((e) => {
      const message = getErrorMessage(e)
      props.closeModal(message, 'error')
    }).then(() => {
      props.closeModal(`successfully deleted permission "${props.permission.label}"`, 'success')
    })
  }

  const handleCancelation = () => {
    props.closeModal('', 'close')
  }

  return (
    <ModalDialog
      centered
      confirmation={{
        isDangerous: true,
        label: 'Delete',
        onClick: handleConfirmation,
      }}
      cancelation={{
        label: 'Cancel',
        onClick: handleCancelation,
      }}
      isOpen={props.isModalOpen}
      onClose={handleCancelation}
    >
      <h3>
        Confirm delete permission "{props.permission && props.permission.name}"
      </h3>
    </ModalDialog>
  )
}

export default PermissionDelete

```


[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 admin-organizations/react/components/permissions/PermissionsList.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { pathOr } from 'ramda'
import React, { useState } from 'react'
import { useQuery } from 'react-apollo'
import { Spinner, Table } from 'vtex.styleguide'
import DOCUMENTS from '../../graphql/queries/documents.graphql'
import '../../styles.global.css'
import {
  PERMISSIONS_ACRONYM,
  PERMISSIONS_FIELDS,
  PERMISSIONS_SCHEMA
} from '../../utils/consts'
import { documentSerializer } from '../../utils/documentSerializer'
import PermissionDelete from './PermissionDelete'
import PermissionModal from './PermissionModal'

import Toast from '../../Toast'

const PermissionsList = () => {

  const { data, loading, error } = useQuery(DOCUMENTS, {
    variables: {
      acronym: PERMISSIONS_ACRONYM,
      fields: PERMISSIONS_FIELDS,
      page: 1,
      pageSize: 100,
      schema: PERMISSIONS_SCHEMA,
    },
  })

  const permissionsList = documentSerializer(pathOr([], ['myDocuments'], data))

  const [tableDensity, setTableDensity] = useState('low')
  const [searchValue, setSearchValue] = useState('')
  const [sharedPermission, setSharedPermission] = useState({} as Permission)
  const [openPermissionModal, setOpenPermissionModal] = useState(false)
  const [openPermissionDelete, setOpenPermissionDelete] = useState(false)

  const [tostMessage, setTostMessage] = useState({showToast: false, message: '', type: '' } as TostMessage)

  const getSchema = () => {
    let fontSize = 'f5'
    switch (tableDensity) {
      case 'low': {
        fontSize = 'f5'
        break
      }
      case 'medium': {
        fontSize = 'f6'
        break
      }
      case 'high': {
        fontSize = 'f7'
        break
      }
      default: {
        fontSize = 'f5'
        break
      }
    }
    return {
      properties: {
        label: {
          cellRenderer: ({ cellData }: any) => {
            return <span className={`ws-normal ${fontSize}`}>{cellData}</span>
          },
          title: 'Label',
        },
        name: {
          cellRenderer: ({ cellData }: any) => {
            return <span className={`ws-normal ${fontSize}`}>{cellData}</span>
          },
          title: 'Name',
        },
      },
    }
  }

  const createNewPermission = () => {
    setSharedPermission({} as Permission)
    setOpenPermissionModal(true)
  }

  const editPermission = (cellData: Permission) => {
    setSharedPermission(cellData)
    setOpenPermissionModal(true)
  }

  const deletePermission = (cellData: Permission) => {
    setSharedPermission(cellData)
    setOpenPermissionDelete(true)
  }

  const closeCreateEditModal = (message: string, messageType: string) => {
    setSharedPermission({} as Permission)
    setOpenPermissionModal(false)

    if(messageType === 'error' || messageType === 'success'){
      setTostMessage({showToast: true, message, type: messageType } as TostMessage)
    }
  }

  const closeDeleteModal = (message: string, messageType: string) => {
    setSharedPermission({} as Permission)
    setOpenPermissionDelete(false)

    if(messageType === 'error' || messageType === 'success'){
      setTostMessage({showToast: true, message, type: messageType } as TostMessage)
    }
  }

  const handleCloseToast = () => {
    setTostMessage({showToast: false, message: '', type: '' } as TostMessage)
  }

  const lineActions = [
    {
      label: () => `Edit`,
      onClick: ({ rowData }: any) => editPermission(rowData),
    },
    {
      isDangerous: true,
      label: () => `Delete`,
      onClick: ({ rowData }: any) => deletePermission(rowData),
    },
  ]

  return loading ? (
    <Spinner />
  ) : error ? (
    <div>Failed to load permissions</div>
  ) : (
    <div>
      <Table
        fullWidth
        updateTableKey={tableDensity}
        items={permissionsList}
        schema={getSchema()}
        density="low"
        lineActions={lineActions}
        toolbar={{
          density: {
            buttonLabel: 'Line density',
            handleCallback: (density: string) => setTableDensity(density),
            highOptionLabel: 'High',
            lowOptionLabel: 'Low',
            mediumOptionLabel: 'Medium',
          },
          newLine: {
            handleCallback: () => createNewPermission(),
            label: 'New',
          },
        }}
      />
      <PermissionModal
        closeModal={closeCreateEditModal}
        isModalOpen={openPermissionModal}
        permission={sharedPermission}
      />
      <PermissionDelete
        closeModal={closeDeleteModal}
        isModalOpen={openPermissionDelete}
        permission={sharedPermission}
      />
      {tostMessage.showToast && (
        <Toast
          type={tostMessage.type}
          showToast={tostMessage.showToast}
          message={tostMessage.message}
          onClose={handleCloseToast}
        />
      )}
    </div>
  )
}

export default PermissionsList

```


[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 admin-organizations/react/components/permissions/Permissions.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

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

import PermissionsList from './PermissionsList'

const Permissions = () => {
  return (
    <Layout
      pageHeader={
        <PageHeader
          title={
            <FormattedMessage id="admin-authorization.permissions.title" />
          }
        />
      }
    >
      <PageBlock variation="full">
        <PermissionsList />
      </PageBlock>
    </Layout>
  )
}

export default Permissions

```


[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 admin-organizations/react/components/permissions/PermissionModal.tsx from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useEffect, useState } from 'react'
import { useMutation } from 'react-apollo'
import { Button, Input, Modal } from 'vtex.styleguide'
import CREATE_DOCUMENT from '../../graphql/mutations/createDocument.graphql'
import UPDATE_DOCUMENT from '../../graphql/mutations/updateDocument.graphql'
import { updateCacheAddPermission, updateCacheUpdatePermission } from '../../utils/cacheUtils'
import { PERMISSIONS_ACRONYM, PERMISSIONS_SCHEMA } from '../../utils/consts'
import { getErrorMessage } from '../../utils/graphqlErrorHandler'

interface Props {
  isModalOpen: boolean
  permission: Permission
  closeModal: (message: string, type: string) => void
}

const PermissionModal = (props: Props) => {
  const [isEdit, setIsEdit] = useState(false)
  const [id, setId] = useState('')
  const [name, setName] = useState('')
  const [label, setLabel] = useState('')

  const [addPermission] = useMutation(CREATE_DOCUMENT, {
    update: (cache: any, { data }: any) =>
      updateCacheAddPermission(
        cache,
        data,
        name,
        label
      ),
  })
  const [editPermission] = useMutation(UPDATE_DOCUMENT, {
    update: (cache: any, { data }: any) =>
      updateCacheUpdatePermission(
        cache,
        data,
        name,
        label
      ),
  })

  const handleCloseModal = () => {
    props.closeModal('', 'close')
  }

  useEffect(() => {
    setIsEdit(
      props.permission &&
        props.permission.id !== undefined &&
        props.permission.id !== ''
    )
    setId(props.permission && props.permission.id ? props.permission.id : '')
    setName(props.permission && props.permission.name ? props.permission.name : '')
    setLabel(props.permission && props.permission.label ? props.permission.label : '')
  }, [props.permission])

  const handleSave = () => {
    const permissionFields = [
      { key: 'name', value: name },
      { key: 'label', value: label },
    ]
    if (isEdit) {
      permissionFields.push({ key: 'id', value: id })
    }
    const save = isEdit? editPermission: addPermission

    save({
      variables: {
        acronym: PERMISSIONS_ACRONYM,
        document: { fields: permissionFields },
        schema: PERMISSIONS_SCHEMA,
      },
    }).catch((e) => {
      const message = getErrorMessage(e)
      props.closeModal(message, 'error')
    }).then(() => {
      props.closeModal(`successfully ${ isEdit? 'updated': 'created' } permission "${label}"`, 'success')
    })
  }

  return (
    <Modal
      isOpen={props.isModalOpen}
      title="Permission"
      responsiveFullScreen
      centered
      bottomBar={
        <div className="nowrap">
          <span className="mr4">
            <Button variation="tertiary" onClick={handleCloseModal}>
              Cancel
            </Button>
          </span>
          <span>
            <Button variation="secondary" onClick={handleSave}>
              Save
            </Button>
          </span>
        </div>
      }
      onClose={handleCloseModal}
    >
      <div className="mb5">
        <Input
          placeholder="e.g. view_order"
          dataAttributes={{ 'hj-white-list': true, test: 'string' }}
          label="Name"
          value={name}
          onChange={(e: any) => setName(e.target.value)}
        />
      </div>
      <div className="mb5">
        <Input
          placeholder="e.g. View Order"
          dataAttributes={{ 'hj-white-list': true, test: 'string' }}
          label="Label"
          value={label}
          onChange={(e: any) => setLabel(e.target.value)}
        />
      </div>
    </Modal>
  )
}

export default PermissionModal

```


[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 admin-organizations/react/graphql/mutations/deleteDocument.graphql from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation deleteDocument($acronym: String!, $documentId: String!) {
  deleteMyDocument(acronym: $acronym, documentId: $documentId) {
    id
    cacheId
  }
}

```


[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 admin-organizations/react/graphql/mutations/createDocument.graphql from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation createDocument($acronym: String!, $document: DocumentInput, $schema: String) {
  createMyDocument(acronym: $acronym, document: $document, schema: $schema) {
    id
    cacheId
  }
}
```


[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 admin-organizations/react/graphql/mutations/updateDocument.graphql from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation updateDocument($acronym: String!, $document: DocumentInput, $schema: String) {
  updateMyDocument(acronym: $acronym, document: $document, schema: $schema) {
    id
    cacheId
  }
}
```


[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 admin-organizations/react/graphql/queries/documents.graphql from the admin-organizations VTEX app.

[Assistant]
Here's the implementation:

```graphql
query mediaDocumentsQuery ($acronym: String, $fields: [String], $page: Int, $pageSize: Int, $where: String, $schema: String){
  myDocuments(acronym: $acronym, fields: $fields, page: $page, pageSize:$pageSize, where:$where, schema: $schema) {
    id
    fields
    {
      key
      value
    }
  }
}

```


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

[User] Show me the implementation of regionalization-theme/docs/README.md from the regionalization-theme VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Store theme
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
Our boilerplate theme to create stores in the VTEX IO platform.

## Preview
![store-theme-default](https://user-images.githubusercontent.com/1354492/63937047-e8d81c80-ca37-11e9-86fc-61e88847bbfb.png)

## Features

### Delivery Promises & Regionalization
This theme includes enhanced delivery promise functionality and regionalization features to provide customers with accurate shipping information based on their location.

**Key components:**
- **Shipping Option Components (`vtex.shipping-option-components`)**: Provides comprehensive shipping option display and selection interface with delivery promise integration
- **Shipping Option Location Selector**: Allows customers to input their location (ZIP code, address) to see accurate delivery estimates and shipping costs
- **Delivery Promise Display**: Shows estimated delivery dates, shipping methods, and costs based on customer's selected location
- **Enhanced Regional Experience**: Improved user experience with location-aware content and shipping options

These features help improve customer experience by:
- Providing transparent shipping information upfront
- Reducing cart abandonment through clear delivery expectations
- Enabling location-based shopping decisions
- Supporting regionalized content and pricing

## Tutorial
To understand how things work check our tutorial [Build a store using VTEX IO](https://vtex.io/docs/getting-started/build-stores-with-store-framework/1/)

## Dependencies
All store components that you see on this document are open source too. Production ready, you can found those apps in this GitHub organization.

Store framework is the baseline to create any store using _VTEX IO Web Framework_.
- [Store](https://github.com/vtex-apps/store/blob/master/README.md)

Store GraphQL is a middleware to access all VTEX APIs.
- [Store GraphQL](https://github.com/vtex-apps/store-graphql/blob/master/docs/README.md)

### Store Component Apps
- [Header](https://github.com/vtex-apps/store-header/blob/master/docs/README.md)
- [Footer](https://github.com/vtex-apps/store-footer/blob/master/docs/README.md)
- [Slider Layout](https://github.com/vtex-apps/slider-layout/blob/master/docs/README.md)
- [Shelf](https://github.com/vtex-apps/shelf/blob/master/docs/README.md)
- [Telemarketing](https://github.com/vtex-apps/telemarketing/blob/master/docs/README.md)
- [Menu](https://github.com/vtex-apps/menu/blob/master/docs/README.md)
- [Login](https://github.com/vtex-apps/login/blob/master/docs/README.md)
- [Minicart](https://github.com/vtex-apps/minicart/blob/master/docs/README.md)
- [Category Menu](https://github.com/vtex-apps/category-menu/blob/master/docs/README.md)
- [Product Summary](https://github.com/vtex-apps/product-summary/blob/master/docs/README.md)
- [Breadcrumb](https://github.com/vtex-apps/breadcrumb/blob/master/docs/README.md)
- [Search Result](https://github.com/vtex-apps/search-result/blob/master/docs/README.md)
- [Product Details](https://github.com/vtex-apps/product-details/blob/master/docs/README.md)
- [Store Components](https://github.com/vtex-apps/store-components/blob/master/docs/README.md)
- [Order Placed](https://github.com/vtex-apps/order-placed/blob/master/docs/README.md)
- [Shipping Option Components](https://github.com/vtex-apps/shipping-option-components/blob/master/docs/README.md)

### Store Pixel Apps

 - [Google Tag Manager](https://github.com/vtex-apps/google-tag-manager/blob/master/docs/README.md)

## Contributing

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

## Contributors ✨

Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
  <tr>
    <td align="center"><a href="http://www.hugoccosta.com"><img src="https://avatars2.githubusercontent.com/u/20212776?v=4" width="100px;" alt=""/><br /><sub><b>Hugo Costa</b></sub></a><br /><a href="https://github.com/vtex-apps/store-theme/commits?author=hugocostadev" title="Documentation">📖</a></td>
  </tr>
</table>

<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!

```


[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 regionalization-theme/docs/contact-schema.json from the regionalization-theme VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "title": "Contact",
  "type": "object",
  "properties": {
    "title": {
      "type": "string",
      "title": "Title"
    },
    "name": {
      "type": "string",
      "title": "Name"
    },
    "email": {
      "type": "string",
      "format": "email",
      "title": "Email address"
    },
    "message": {
      "type": "string",
      "title": "Message"
    }
  },
  "required": ["email", "message"],
  "v-security": {
    "publicJsonSchema": 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 regionalization-theme/store/blocks.jsonc from the regionalization-theme VTEX app.

[Assistant]
Here's the implementation:

```json
/* Blocks can be defined both on the store/blocks.json file, and in any number of json
 * files inside the store/blocks directory, with any arbitrary directory structure.
 *
 * Additionally, all blocks files can support comments, such as this one, if given the
 * .jsonc file extension.
 *
 * The store/blocks.json file is intended for backwards compatibility, for miscellaneous
 * blocks, or if the app is simple enough that it doesn't warrant splitting the file.
 */
{
  "store.orderplaced": {
    "blocks": ["order-placed"]
  },

  "store.account": {
    "blocks": ["my-account"],
    "parent": {
      "challenge": "challenge.profile"
    }
  },

  "store.login": {
    "blocks": ["login-content#default"]
  },

  "login-content#default": {
    "props": {
      "isInitialScreenOptionOnly": false,
      "defaultOption": 1,
      "showPasswordVerificationIntoTooltip": true
    }
  },

  "store.not-found#product": {
    "blocks": ["rich-text#not-found"]
  },

  "store.not-found#search": {
    "blocks": ["rich-text#not-found"]
  },

  "rich-text#not-found": {
    "props": {
      "textAlignment": "CENTER",
      "textPosition": "CENTER",
      "text": "**PAGE NOT FOUND**",
      "font": "t-heading-1"
    }
  }
}

```


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

[User] Show me the implementation of regionalization-theme/store/routes.json from the regionalization-theme VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store.custom#about-us": {
    "path": "/about-us"
  },
  "store.custom#faq": {
    "path": "/faq"
  },
  "store.custom#contact-us": {
    "path": "/contact-us"
  }
}

```


[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 regionalization-theme/styles/css/vtex.store-video.css from the regionalization-theme VTEX app.

[Assistant]
Here's the implementation:

```css
.videoContainer {
  width: 100%;
  height: 300px;
  margin-top: 2%;
}

@media only screen and (min-width: 640px) {
  .videoContainer {
    height: 700px;
  }
}

```


[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 regionalization-theme/styles/css/vtex.search.css from the regionalization-theme VTEX app.

[Assistant]
Here's the implementation:

```css
.tileListItem{
    max-width: 150px;
    margin: 10px
}
```


[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 regionalization-theme/styles/css/vtex.product-price.css from the regionalization-theme VTEX app.

[Assistant]
Here's the implementation:

```css
.listPrice {
  color: #727273;
  margin-bottom: .25rem;
  font-size: 1rem;
}

.sellingPrice {
  color: #3f3f40;
  font-size: 1.25rem;
}

.sellingPriceValue {
  font-size: 2.25rem;
  font-weight: 700;
}

.installments {
  color: #727273;
  margin-bottom: 1rem;
}

.savings {
  font-weight: 500;
  color: #79B03A;
}

.sellingPriceValue--summary {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2E2E2E;
}

.savings--summary {
  background: #8BC34A;
  border-radius: 1000px;
  align-items: center;
  display: flex;

  padding-left: 0.5rem;
  padding-right: 0.5rem;
  font-size: 0.875rem;
  font-weight: 600;
  vertical-align: baseline;
  color: #FFFFFF;
}

.savings-discount--summary {
  font-size: 0.875rem;
  font-weight: 600;
  vertical-align: baseline;
  color: #FFFFFF;
  padding-left: 0.5rem;
  padding-right: 0.5rem;
}

.listPrice--summary {
  margin-bottom: 0.25rem;
  font-size: .875rem;
}

.installments--summary {
  margin-bottom: 2rem;
  font-size: 0.875rem;
}

.savings--summaryPercentage {
  background: #0f3e99;
  border-radius: 1000px;
  align-items: center;
  display: flex;
}

.savingsPercentage--summaryPercentage {
  font-size: 0.875rem;
  font-weight: 600;
  vertical-align: baseline;
  color: #FFFFFF;
  padding: 0.25rem 0.5rem 0.25rem 0.5rem;
}

```


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

[User] Show me the implementation of regionalization-theme/styles/css/vtex.rich-text.css from the regionalization-theme VTEX app.

[Assistant]
Here's the implementation:

```css
.container--deals {
  color: #ffffff;
  text-align: center;
  justify-content: center;
}

.container--shelfTitle {
  color: #727273;
  justify-content: center;
  text-align: center;
}

.headingLevel2--shelfTitle {
  font-weight: 200;
}

.container--deals .paragraph {
  margin: 0;
}

.container--link {
  justify-content: center;
}

.container--question {
  justify-content: center;
}

.container--question .paragraph {
  text-align: center;
  max-width: 540px;
  margin: 0 16px;
  padding-top: 120px;
  color: #03034E;
}

.container--question .strong {
  font-size: 32px;
  line-height: 2rem;
  font-weight: 700;
}

.container--link .paragraph {
  text-align: center;
  max-width: 540px;
  padding-top: 36px;
  padding-bottom: 84px;
  color: #03034E;
}

.container--link .strong {
  font-size: 16px;
  font-weight: 700;
  text-transform: uppercase;
}

.container--link .link {
  text-decoration: none;
  font-size: 36px;
  font-weight: 300;
  color: #03034E;
}

.container--title {
  color: #03034E;
  font-size: 28px;
  font-weight: 700;
}

@media only screen and (min-width: 640px) {
  .container--question .strong {
    font-size: 40px;
    line-height: 3rem;
  }

  .container--about {
    max-width: 85%;
  }

  .container--title {
    color: #03034E;
    font-size: 40px;
    font-weight: 700;
    max-width: 60%;
  }

  .container--title .paragraph {
    line-height: 1.3em;
  }
}

```


[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 regionalization-theme/styles/css/vtex.product-summary.css from the regionalization-theme VTEX app.

[Assistant]
Here's the implementation:

```css
.skuSelectorContainer--quickview .skuSelectorItemImage .frameAround, .skuSelectorContainer--quickview .skuSelectorItemImage .skuSelectorInternalBox {
  border-radius: 50%;
}

.container :global(.vtex-modal-layout-0-x-triggerContainer) {
  opacity: 0;
  transition: opacity 200ms ease-in-out;
}

.container:hover :global(.vtex-modal-layout-0-x-triggerContainer) {
  opacity: 1;
}

@media screen and (max-width: 40em) {
  .container :global(.vtex-modal-layout-0-x-triggerContainer) {
    display: none;
  }
}

.nameContainer {
  justify-content: start;
  padding-top: 1rem;
  padding-bottom: 1rem;
}

.brandName {
  font-weight: 600;
  font-size: 18px;
  color: #2E2E2E;
}

.container {
  text-align: start;
}

.imageContainer {
  text-align: center;
}

.image {
  border-radius: 0.25rem;
}

```


[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 regionalization-theme/styles/css/vtex.modal-layout.css from the regionalization-theme VTEX app.

[Assistant]
Here's the implementation:

```css
@media screen and (min-width: 40em) {
  .paper--quickview {
    height: 260px;
    width: 580px;
  }

  .actionsContainer--quickview {
    padding: 0 2rem 2rem 2rem;
  }
}

@media screen and (min-width: 50em) {
  .paper--quickview {
    height: 450px;
    width: 900px;
  }
}

@media screen and (min-width: 75em) {
  .paper--quickview {
    width: calc(100% - 4rem);
    height: auto;
  }
}

@media screen and (min-width: 82em) {
  .actionsContainer--quickview {
    padding: 0 2.5rem 2.5rem 2.5rem;
  }
}

.paper--quickview {
  min-width: 320px;
  max-width: 96rem;
}

.headerContainer--quickview {
  border: none;
  position: absolute;
  right: 0;
}

.actionsContainer--quickview {
  height: 100%;
  width: 100%;
  transition: box-shadow 150ms ease-in-out, border-top 150ms ease-in-out;
  border-top-style: solid;
  border-top-width: 1px;
  border-top-color: transparent;
  box-shadow: -4px 0px 27px -12px transparent;
}

.actionsContentWrapper {
  border-top-width: 1px;
  border-top-style: solid;
  border-top-color: #aaa;
  padding-top: 1.5rem;
}

.contentContainer--quickviewContent {
  padding: 2.5rem 0 2.5rem 2rem;
  overflow-x: hidden;
}

.triggerContainer--quickview {
  padding: .75rem;
}

.triggerContainer {
  outline: none;
}

.actionsContainer--quickview:not(.actionsContainerEndOfContent--quickview) {
  border-top-color: rgb(238, 238, 238);
  box-shadow: -4px 0px 27px -12px rgba(0,0,0,0.64);
}

.actionsContainer--quickview:not(.actionsContainerEndOfContent--quickview) .actionsContentWrapper {
  border-top-color: transparent;
}

.closeButton {
  padding-right: 1rem;
}

.paper--product-gifts {
  padding: 1.5rem;
}

```