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

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

[Assistant]
Here's the implementation:

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

import { Clients } from './clients'
import { resolvers } from './resolvers'
import { schemaDirectives } from './resolvers/directives'

const TIMEOUT_MS = 3000

// Create a LRU memory cache for the Status client.
// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.
const memoryCache = new LRUCache<string, Cached>({ max: 5000 })

metrics.trackCache('status', memoryCache)

// This is the configuration for clients available in `ctx.clients`.
const clients: ClientsConfig<Clients> = {
  // We pass our custom implementation of the clients bag, containing the Status client.
  implementation: Clients,
  options: {
    // All IO Clients will be initialized with these options, unless otherwise specified.
    default: {
      retries: 2,
      timeout: TIMEOUT_MS,
    },
    // This key will be merged with the default options and add this cache to our Status client.
    status: {
      memoryCache,
    },
  },
}

declare global {
  type Context = ServiceContext<Clients>
}

export default new Service<Clients, RecorderState, ParamsContext>({
  clients,
  routes: resolvers.Routes,
  graphql: {
    resolvers: {
      Query: resolvers.Query,
      Mutation: resolvers.Mutation,
    },
    schemaDirectives,
  },
})

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "name": "b2b-checkout-settings",
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "dependencies": {
    "react-apollo": "^3.1.5",
    "react-intl": "^5.24.6"
  },
  "devDependencies": {
    "@types/jest": "^26.0.4",
    "@types/node": "^14.0.14",
    "@types/react": "^16.9.41",
    "@types/react-intl": "^3.0.0",
    "@vtex/test-tools": "^3.1.0",
    "@vtex/tsconfig": "^0.5.6",
    "vtex.b2b-organizations-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.b2b-organizations-graphql@0.9.2/public/@types/vtex.b2b-organizations-graphql",
    "vtex.graphql-server": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.graphql-server@1.67.0/public/_types/react",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.3/public/@types/vtex.render-runtime",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.0/public/@types/vtex.styleguide"
  },
  "version": "3.1.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 b2b-checkout-settings/react/B2BCheckoutAdmin.tsx from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```tsx
import B2BCheckoutAdmin from './components/B2BCheckoutAdmin'

export default B2BCheckoutAdmin

```


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

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

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { InstanceOptions, IOContext } from '@vtex/api'
import { AppGraphQLClient } from '@vtex/api'

import { QUERIES } from '../resolvers/Routes/queries'
import { getTokenToHeader } from './index'

export default class StorefrontPermissions extends AppGraphQLClient {
  constructor(ctx: IOContext, options?: InstanceOptions) {
    super('vtex.storefront-permissions@3.x', ctx, options)
  }

  public checkUserPermission = async (): Promise<any> => {
    return this.graphql.query(
      {
        extensions: {
          persistedQuery: {
            provider: 'vtex.storefront-permissions@3.x',
            sender: 'vtex.b2b-checkout-settings@3.x',
          },
        },
        query: QUERIES.getPermission,
        variables: {},
      },
      {
        headers: getTokenToHeader(this.context),
        params: {
          locale: this.context.locale,
        },
      }
    )
  }
}

```


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

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

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { InstanceOptions, IOContext } from '@vtex/api'
import { AppGraphQLClient } from '@vtex/api'

import { QUERIES } from '../resolvers/Routes/queries'
import { getTokenToHeader } from './index'

export class OrganizationsGraphQLClient extends AppGraphQLClient {
  constructor(ctx: IOContext, options?: InstanceOptions) {
    super('vtex.b2b-organizations-graphql@2.x', ctx, options)
  }

  public getAddresses = async (costCenterId: string): Promise<any> => {
    return this.graphql.query(
      {
        extensions: {
          persistedQuery: {
            provider: 'vtex.b2b-organizations-graphql@2.x',
            sender: 'vtex.b2b-checkout-settings@3.x',
          },
        },
        query: QUERIES.getAddresses,
        variables: {
          id: costCenterId,
        },
      },
      {
        headers: getTokenToHeader(this.context),
        params: {
          locale: this.context.locale,
        },
      }
    )
  }

  public getOrganization = async (organizationId: string): Promise<any> => {
    return this.graphql.query(
      {
        extensions: {
          persistedQuery: {
            provider: 'vtex.b2b-organizations-graphql@2.x',
            sender: 'vtex.b2b-checkout-settings@3.x',
          },
        },
        query: QUERIES.getOrganizationDetails,
        variables: {
          id: organizationId,
        },
      },
      {
        headers: getTokenToHeader(this.context),
        params: {
          locale: this.context.locale,
        },
      }
    )
  }
}

```


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

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

[Assistant]
Here's the implementation:

```typescript
import type {
  InstanceOptions,
  IOContext,
  RequestTracingConfig,
} from '@vtex/api'
import { JanusClient } from '@vtex/api'

import { createTracing } from '../utils'

const CHECKOUT_ENDPOINT = 'api/checkout/pvt/configuration/orderForm'

export class Checkout extends JanusClient {
  constructor(ctx: IOContext, options?: InstanceOptions) {
    super(ctx, {
      ...options,
      headers: {
        ...(ctx.adminUserAuthToken
          ? {
              VtexIdclientAutCookie: ctx.adminUserAuthToken,
            }
          : {}),
      },
    })
  }

  public getOrderFormConfiguration(tracingConfig?: RequestTracingConfig) {
    const metric = 'b2b-checkout-settings-getOrderForm'

    return this.http.get<OrderFormConfiguration>(CHECKOUT_ENDPOINT, {
      metric,
      tracing: createTracing(metric, tracingConfig),
    })
  }

  public setOrderFormConfiguration(
    body: OrderFormConfiguration,
    userToken: string,
    tracingConfig?: RequestTracingConfig
  ) {
    const metric = 'b2b-checkout-settings-setOrderForm'

    return this.http.post(CHECKOUT_ENDPOINT, body, {
      headers: {
        VtexIdclientAutCookie: userToken,
      },
      metric,
      tracing: createTracing(metric, tracingConfig),
    })
  }
}

```


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

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

[Assistant]
Here's the implementation:

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

export class AuthUser extends JanusClient {
  constructor(ctx: IOContext, options?: InstanceOptions) {
    super(ctx, {
      ...options,
      headers: {
        ...options?.headers,
      },
    })
  }

  public async validateToken(token: any): Promise<any> {
    return this.http.post(`/api/vtexid/credential/validate`, token)
  }
}

```


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

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

[Assistant]
Here's the implementation:

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

import { AuthUser } from './AuthUser'
import { Checkout } from './Checkout'
import { OrganizationsGraphQLClient } from './Organizations'
import StorefrontPermissions from './StorefrontPermissions'

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

  public get organizations() {
    return this.getOrSet('organizations', OrganizationsGraphQLClient)
  }

  public get checkout() {
    return this.getOrSet('checkout', Checkout)
  }

  public get authUser() {
    return this.getOrSet('authUser', AuthUser)
  }
}

export const getTokenToHeader = (ctx: IOContext) => {
  const adminToken = ctx.authToken
  const userToken = ctx.storeUserAuthToken
  const { sessionToken, account } = ctx

  let allCookies = `VtexIdclientAutCookie=${adminToken}`

  if (userToken) {
    allCookies += `; VtexIdclientAutCookie_${account}=${userToken}`
  }

  return {
    'x-vtex-credential': ctx.authToken,
    VtexIdclientAutCookie: adminToken,
    cookie: allCookies,
    ...(sessionToken && {
      'x-vtex-session': sessionToken,
    }),
  }
}

```


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

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

[Assistant]
Here's the implementation:

```typescript
export default class GraphQLError extends Error {
  public extensions: any

  constructor(message: string, details?: any) {
    super(message)
    this.extensions = { message, ...details }
  }
}

```


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

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

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as crypto from 'crypto'

import type { AxiosError } from 'axios'
import type { RequestTracingConfig } from '@vtex/api'
import { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'

export const toHash = (obj: any) => {
  return crypto.createHash('md5').update(JSON.stringify(obj)).digest('hex')
}

export function statusToError(e: any) {
  if (!e.response) {
    throw e
  }

  const { response } = e as AxiosError
  const { status } = response!

  if (status === 401) {
    throw new AuthenticationError(e)
  }

  if (status === 403) {
    throw new ForbiddenError(e)
  }

  if (status === 400) {
    throw new UserInputError(e)
  }

  throw e
}

export const createTracing = (
  metric: string,
  tracingConfig?: RequestTracingConfig
) => ({
  requestSpanNameSuffix: metric,
  ...tracingConfig?.tracing,
})

```


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

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

[Assistant]
Here's the implementation:

```typescript
import { WithPermissions } from './directives/withAdminAccess'

export const schemaDirectives = {
  withAdminAccess: WithPermissions as 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 b2b-checkout-settings/node/resolvers/constants.ts from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const VBASE_BUCKET = 'b2b-checkout-settings'
export const VBASE_SETTINGS_FILE = 'settings'
export const DEFAULTS = {
  showPONumber: false,
  hasPONumber: false,
  showQuoteButton: 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 b2b-checkout-settings/node/resolvers/index.ts from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/no-explicit-any */
// import { ForbiddenError } from '@vtex/api'

import Mutation from './Mutations'
import Query from './Queries'
import Routes from './Routes'

export const resolvers = {
  Routes,
  Query,
  Mutation,
}

```


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

[User] Show me the implementation of b2b-checkout-settings/node/resolvers/directives/withAdminAccess.ts from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable max-params */
import type { GraphQLField } from 'graphql'
import { defaultFieldResolver } from 'graphql'
import { SchemaDirectiveVisitor } from 'graphql-tools'
import { AuthenticationError, ForbiddenError } from '@vtex/api'

export class WithPermissions extends SchemaDirectiveVisitor {
  public visitFieldDefinition(field: GraphQLField<any, any>) {
    const { resolve = defaultFieldResolver } = field

    field.resolve = async (root: any, args: any, ctx: Context, info: any) => {
      const {
        clients: { authUser },
        vtex: { adminUserAuthToken, logger },
      } = ctx

      if (!adminUserAuthToken) {
        throw new AuthenticationError('Unauthorized')
      }

      try {
        await authUser.validateToken({
          token: adminUserAuthToken,
        })

        return resolve(root, args, ctx, info)
      } catch (error) {
        const {
          response: { status },
        } = error

        switch (status) {
          case 401: {
            throw new AuthenticationError('Unauthorized')
          }

          case 403: {
            throw new ForbiddenError('Unauthorized Access')
          }

          default: {
            logger.error({
              message: 'saveAppSettings-authUser-error',
              error,
            })
          }
        }
      }
    }
  }
}

```


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

[User] Show me the implementation of b2b-checkout-settings/node/resolvers/Mutations/index.ts from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { GraphQLError } from 'graphql'

import { VBASE_BUCKET, VBASE_SETTINGS_FILE } from '../constants'

export interface Settings {
  showPONumber: boolean
  hasPONumber: boolean
  showQuoteButton: boolean
}

export default {
  saveAppSettings: async (
    _: void,
    { settings }: { settings: Settings },
    ctx: Context
  ) => {
    const {
      clients: { vbase },
      vtex: { logger },
    } = ctx

    if (!settings) throw new GraphQLError('Input not provided')

    try {
      await vbase.saveJSON(VBASE_BUCKET, VBASE_SETTINGS_FILE, settings)

      return settings
    } catch (error) {
      logger.error({
        message: 'appSettings-saveVbaseError',
        error,
      })

      throw new GraphQLError('Failed to save settings')
    }
  },
}

```


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

[User] Show me the implementation of b2b-checkout-settings/node/resolvers/Queries/index.ts from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { VBASE_BUCKET, VBASE_SETTINGS_FILE, DEFAULTS } from '../constants'

export default {
  appSettings: async (_: void, __: void, ctx: Context) => {
    const {
      clients: { vbase },
      vtex: { logger },
    } = ctx

    let settings = null

    try {
      settings = await vbase.getJSON(VBASE_BUCKET, VBASE_SETTINGS_FILE, true)
    } catch (error) {
      logger.error({
        message: 'appSettings-getVbaseError',
        error,
      })
    }

    if (!settings) {
      settings = DEFAULTS
    }

    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 b2b-checkout-settings/node/resolvers/Routes/index.test.ts from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { randUuid } from '@ngneat/falso'
import type { PaymentTerm } from 'vtex.b2b-organizations-graphql'

import index from './index'

const costCenterPaymentTerms = 'costCenterPaymentTerms'
const organizationPaymentTerms = 'organizationPaymentTerms'

interface ResponseBody {
  paymentTerms: PaymentTerm[]
}

const getAddressMocked = jest.fn().mockResolvedValueOnce({
  data: {
    getCostCenterById: {
      addresses: {},
      customFields: {},
      paymentTerms: [
        { id: costCenterPaymentTerms, name: costCenterPaymentTerms },
      ],
    },
  },
})

const getOrganizationMocked = jest
  .fn()
  .mockImplementationOnce(() =>
    Promise.resolve({
      data: {
        getOrganizationById: {
          addresses: {},
          customFields: {},
          paymentTerms: [
            {
              id: costCenterPaymentTerms,
              name: costCenterPaymentTerms,
            },
          ],
        },
      },
    })
  )
  .mockImplementationOnce(() =>
    Promise.resolve({
      data: {
        getOrganizationById: {
          addresses: {},
          customFields: {},
          paymentTerms: [
            {
              id: organizationPaymentTerms,
              name: organizationPaymentTerms,
            },
          ],
        },
      },
    })
  )

const mockContext = () => {
  return {
    clients: {
      storefrontPermissions: {
        checkUserPermission: jest.fn().mockResolvedValueOnce({ data: {} }),
      },
      organizations: {
        getAddresses: getAddressMocked,
        getOrganization: getOrganizationMocked,
      },
      session: {
        getSession: jest.fn().mockResolvedValueOnce({
          sessionData: {
            namespaces: {
              'storefront-permissions': {
                costcenter: {
                  value: randUuid(),
                },
                organization: {
                  value: randUuid(),
                },
              },
            },
          },
        }),
      },
      vbase: {
        getJSON: jest.fn().mockResolvedValueOnce({}),
      },
    },
    response: {} as Response,
    set: jest.fn(),
    vtex: {
      logger: jest.fn(),
      sessionToken: jest.fn().mockResolvedValueOnce({}),
      storeUserAuthToken: jest.fn().mockResolvedValueOnce({ data: {} }),
    },
  } as unknown as Context
}

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

describe('given Routes to call b2b checkout settings', () => {
  describe('when have the cost center and organization with payment terms', () => {
    let context: Context

    beforeEach(async () => {
      context = mockContext()
      await index.settings(context)
    })

    it('should return payments terms from cost center', () => {
      const { response } = context

      expect(response.status).toEqual(200)
      expect(
        (response.body as ResponseBody)?.paymentTerms.some(
          (item: PaymentTerm) => item.id === costCenterPaymentTerms
        )
      ).toBeTruthy()

      expect(
        (response.body as ResponseBody)?.paymentTerms.some(
          (item: PaymentTerm) => item.id === organizationPaymentTerms
        )
      ).toBeFalsy()
    })
  })

  describe('when have just the organization with payment terms', () => {
    let context: Context

    beforeEach(async () => {
      getAddressMocked.mockResolvedValueOnce({
        data: {
          getCostCenterById: {
            addresses: {},
            customFields: {},
            paymentTerms: [],
          },
        },
      })

      context = mockContext()
      await index.settings(context)
    })

    it('should return payments terms from organization', () => {
      const { response } = context

      expect(response.status).toEqual(200)
      expect(
        (response.body as ResponseBody)?.paymentTerms.some(
          (item: PaymentTerm) => item.id === costCenterPaymentTerms
        )
      ).toBeFalsy()

      expect(
        (response.body as ResponseBody)?.paymentTerms.some(
          (item: PaymentTerm) => item.id === organizationPaymentTerms
        )
      ).toBeTruthy()
    })
  })
})

```


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

[User] Show me the implementation of b2b-checkout-settings/node/resolvers/Routes/queries.ts from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const QUERIES = {
  getPermission: `query permissions {
    checkUserPermission {
      role {
        id
        name
        slug
      }
      permissions
    }
  }`,
  getOrganizationDetails: `query OrganizationDetails($id: ID!) {
    getOrganizationById(id: $id) {
      status
      paymentTerms {
        id
        name
      }
      customFields {
        name
        value
      }
    }
  }
  `,
  getAddresses: `query addressByCostCenter($id: ID!) {
    getCostCenterById(id: $id) {
      paymentTerms {
        id
        name
      }
      customFields {
        name
        value
      }
      addresses {
        addressId
        addressType
        addressQuery
        postalCode
        country
        receiverName
        city
        state
        street
        number
        complement
        neighborhood
        geoCoordinates
        reference
      }
    }
  }
  `,
}

```


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

[User] Show me the implementation of b2b-checkout-settings/node/resolvers/Routes/index.ts from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { PaymentTerm } from 'vtex.b2b-organizations-graphql'

import { DEFAULTS, VBASE_BUCKET, VBASE_SETTINGS_FILE } from '../constants'

const CACHE = 180

export default {
  settings: async (ctx: Context) => {
    const {
      clients: {
        organizations,
        storefrontPermissions,
        checkout,
        session,
        vbase,
      },
      vtex: { host, logger, storeUserAuthToken, production },
    } = ctx

    const token: any = storeUserAuthToken

    ctx.set('Content-Type', 'application/json')
    ctx.set('Cache-Control', 'no-cache, no-store')

    if (!token && !host?.includes('myvtex.com')) {
      ctx.response.body = {
        error: 'User not authenticated',
      }
      ctx.response.status = 200

      ctx.set('cache-control', 'no-cache')
    } else {
      const accountSettings: any = await vbase
        .getJSON(VBASE_BUCKET, VBASE_SETTINGS_FILE, true)
        .catch((error) => {
          logger.error({
            message: 'settings-getJSON-error',
            error,
          })
        })

      if (accountSettings?.showPONumber && !accountSettings?.hasPONumber) {
        const checkoutConfig: any = await checkout
          .getOrderFormConfiguration()
          .catch((error) => {
            logger.error({
              message: 'settings-getOrderformConfiguration-error',
              error,
            })
          })

        accountSettings.hasPONumber = true

        // Check if checkout has b2b-checkout-settings app
        if (
          checkoutConfig?.apps.findIndex(
            (currApp: any) => currApp.id === 'b2b-checkout-settings'
          ) === -1
        ) {
          checkoutConfig.apps.push({
            major: 1,
            id: 'b2b-checkout-settings',
            fields: ['purchaseOrderNumber'],
          })

          const setCheckoutConfig: any = await checkout
            .setOrderFormConfiguration(checkoutConfig, ctx.vtex.authToken)
            .then(() => true)
            .catch((error) => {
              accountSettings.hasPONumber = false

              logger.error({
                message: 'settings-setOrderformConfiguration-error',
                error,
              })

              return false
            })

          if (setCheckoutConfig) {
            await vbase
              .saveJSON(VBASE_BUCKET, VBASE_SETTINGS_FILE, accountSettings)
              .catch((error) => {
                logger.error({
                  message: 'settings-saveJSON-error',
                  error,
                })
              })
          }
        }
      }

      const {
        data: { checkUserPermission },
      }: any = await storefrontPermissions
        .checkUserPermission()
        .catch((error: any) => {
          logger.error({
            message: 'checkUserPermission-error',
            error,
          })

          return {
            data: {
              checkUserPermission: {
                permissions: [],
              },
            },
          }
        })

      const sessionToken =
        ctx.vtex.sessionToken ?? ctx.request.header?.sessiontoken

      const userSession = await session
        .getSession(sessionToken as string, ['*'])
        .then((currentSession: any) => {
          return currentSession.sessionData
        })
        .catch((error) => {
          logger.error({
            message: 'getSession-error',
            error,
          })
        })

      let settings = {
        ...DEFAULTS,
        ...accountSettings,
        ...checkUserPermission,
      }

      // allow users without organization or cost center to access checkout
      if (
        !userSession?.namespaces?.['storefront-permissions']?.organization ||
        !userSession?.namespaces?.['storefront-permissions']?.costcenter
      ) {
        settings = {}
      }

      if (
        userSession?.namespaces?.['storefront-permissions']?.costcenter?.value
      ) {
        settings.costCenterId =
          userSession?.namespaces?.['storefront-permissions']?.costcenter?.value
        const {
          data: { getCostCenterById },
        }: any = await organizations
          .getAddresses(settings.costCenterId)
          .then((res: any) => {
            const { addresses, paymentTerms, customFields } =
              res?.data?.getCostCenterById ?? {}

            return {
              data: {
                getCostCenterById: {
                  addresses,
                  customFields,
                  paymentTerms,
                },
              },
            }
          })
          .catch((error: any) => {
            logger.error({
              message: 'getCostCenterAddresses-error',
              error,
            })

            return {
              data: {
                getCostCenterById: null,
              },
            }
          })

        if (getCostCenterById?.addresses) {
          settings.addresses = getCostCenterById.addresses
        }

        if (getCostCenterById?.customFields) {
          settings.costCenterCustomFields = getCostCenterById.customFields
        }

        if (getCostCenterById?.paymentTerms?.length > 0) {
          settings.paymentTerms = getCostCenterById.paymentTerms
        }
      }

      if (
        userSession?.namespaces?.['storefront-permissions']?.organization?.value
      ) {
        settings.organizationId =
          userSession?.namespaces?.[
            'storefront-permissions'
          ]?.organization?.value

        const {
          data: { getOrganizationById },
        }: any = await organizations
          .getOrganization(settings.organizationId)
          .then((res: any) => {
            const { customFields, status, paymentTerms } =
              res?.data?.getOrganizationById ?? {}

            return {
              data: {
                getOrganizationById: {
                  customFields,
                  paymentTerms,
                  status,
                },
              },
            }
          })
          .catch((error: any) => {
            logger.error({
              message: 'getOrganizationById-error',
              error,
            })

            return {
              data: {
                getOrganizationById: null,
              },
            }
          })

        // fix to only show the payment terms that are in common between the organization and the cost center
        if (settings.paymentTerms && getOrganizationById?.paymentTerms) {
          const intersection = settings.paymentTerms.filter(
            (ccPaymentTerms: PaymentTerm) =>
              getOrganizationById.paymentTerms.some(
                (orgPaymentTerms: PaymentTerm) =>
                  ccPaymentTerms.id === orgPaymentTerms.id &&
                  ccPaymentTerms.name === orgPaymentTerms.name
              )
          )

          settings.paymentTerms = intersection
        }

        if (!settings.paymentTerms && getOrganizationById?.paymentTerms) {
          settings.paymentTerms = getOrganizationById.paymentTerms
        }

        if (!settings.customFields && getOrganizationById?.customFields) {
          settings.customFields = getOrganizationById.customFields
        }

        // if organization status is "on-hold" or "inactive", remove "can-checkout" permission
        if (getOrganizationById?.status !== 'active') {
          const newPermissions = settings.permissions?.filter(
            (permission: string) => permission !== 'can-checkout'
          )

          settings.permissions = newPermissions ?? []
        }
      }

      ctx.set(
        'cache-control',
        `public, max-age=${production ? CACHE : 'no-cache'}`
      )

      ctx.response.body = settings

      ctx.response.status = 200
    }
  },
}

```


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

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

[Assistant]
Here's the implementation:

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

  const value: DocumentNode
  export default value
}

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

```


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

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

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.styleguide' {
  export const PageHeader
  export const Alert
  export const Modal
  export const Box
  export const Card
  export const Checkbox
  export const Dropdown
  export const Spinner
  export const Table
  export const Button
  export const ButtonPlain
  export const IconWarning
  export const IconCheck
  export const Input
  export const InputButton
  export const InputSearch
  export const IconCaretDown
  export const IconCaretUp
  export const IconArrowDown
  export const IconArrowBack
  export const IconArrowUp
  export const IconClose
  export const IconExternalLink
  export const IconSearch
  export const IconSuccess
  export const IconCopy
  export const IconCog
  export const Tooltip
  export const ToastConsumer
  export const ToastProvider
  export const withToast
  export const ButtonWithIcon
  export const Pagination
  export const Collapsible
  export const Textarea
  export const NumericStepper
  export const EmptyState
  export const Tab
  export const Tag
  export const Toggle
  export const Layout
  export const Tabs
  export const Divider
  export const ModalDialog
  export const PageBlock
}

```


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

[User] Show me the implementation of b2b-checkout-settings/react/components/B2BCheckoutAdmin.tsx from the b2b-checkout-settings VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { FC } from 'react'
import React, { useState, useEffect } from 'react'
import { useQuery, useMutation } from 'react-apollo'
import { useIntl, FormattedMessage } from 'react-intl'
import {
  Layout,
  PageHeader,
  PageBlock,
  Button,
  ToastConsumer,
  ToastProvider,
  Toggle,
} from 'vtex.styleguide'

import APP_SETTINGS from '../graphql/appSettings.graphql'
import SAVE_APP_SETTINGS from '../graphql/saveAppSettings.graphql'

const AppSettings: FC = () => {
  const { formatMessage } = useIntl()

  const [settingsState, setSettingsState] = useState({
    showPONumber: false,
    hasPONumber: false,
    showQuoteButton: false,
  })

  const [settingsLoading, setSettingsLoading] = useState(false)

  const { data } = useQuery(APP_SETTINGS, {
    ssr: false,
  })

  const [saveSettings] = useMutation(SAVE_APP_SETTINGS)

  useEffect(() => {
    if (!data?.appSettings) return

    setSettingsState(data.appSettings)
  }, [data])

  const handleSaveSettings = async (showToast: any) => {
    setSettingsLoading(true)

    await saveSettings({
      variables: {
        settings: settingsState,
      },
    })
      .then(() => {
        showToast({
          message: formatMessage({
            id: 'admin/b2bCheckoutSettings.saveSettings.success',
          }),
          duration: 5000,
        })
        setSettingsLoading(false)
      })
      .catch((err) => {
        console.error(err)
        showToast({
          message: formatMessage({
            id: 'admin/b2bCheckoutSettings.saveSettings.failure',
          }),
          duration: 5000,
        })
        setSettingsLoading(false)
      })
  }

  return (
    <ToastProvider positioning="window">
      <ToastConsumer>
        {({ showToast }: { showToast: any }) => (
          <Layout
            pageHeader={
              <PageHeader
                title={
                  <FormattedMessage id="admin/b2bCheckoutSettings.settings.title" />
                }
              />
            }
          >
            <PageBlock>
              <section className="pv4">
                <Toggle
                  semantic
                  label={formatMessage({
                    id: 'admin/b2bCheckoutSettings.settings.showPONumber.label',
                  })}
                  size="large"
                  checked={settingsState.showPONumber}
                  onChange={() => {
                    setSettingsState({
                      ...settingsState,
                      showPONumber: !settingsState.showPONumber,
                    })
                  }}
                  helpText={formatMessage({
                    id: 'admin/b2bCheckoutSettings.settings.showPONumber.helpText',
                  })}
                />
              </section>
              <section className="pv4">
                <Toggle
                  semantic
                  label={formatMessage({
                    id: 'admin/b2bCheckoutSettings.settings.showQuoteButton.label',
                  })}
                  size="large"
                  checked={settingsState.showQuoteButton}
                  onChange={() => {
                    setSettingsState({
                      ...settingsState,
                      showQuoteButton: !settingsState.showQuoteButton,
                    })
                  }}
                  helpText={formatMessage({
                    id: 'admin/b2bCheckoutSettings.settings.showQuoteButton.helpText',
                  })}
                />
              </section>
              <section className="pt4">
                <Button
                  variation="primary"
                  onClick={() => handleSaveSettings(showToast)}
                  isLoading={settingsLoading}
                >
                  {formatMessage({
                    id: 'admin/b2bCheckoutSettings.saveSettings.buttonText',
                  })}
                </Button>
              </section>
            </PageBlock>
          </Layout>
        )}
      </ToastConsumer>
    </ToastProvider>
  )
}

export default AppSettings

```


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

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

[Assistant]
Here's the implementation:

```graphql
mutation SaveAppSettings($settings: SettingsInput!) {
  saveAppSettings(settings: $settings)
    @context(provider: "vtex.b2b-checkout-settings") {
    showPONumber
    hasPONumber
    showQuoteButton
  }
}

```


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

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

[Assistant]
Here's the implementation:

```graphql
query AppSettings {
  appSettings @context(provider: "vtex.b2b-checkout-settings") {
    showPONumber
    hasPONumber
    showQuoteButton
  }
}

```


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

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

[Assistant]
Here's the implementation:

```markdown
# store-resources

> Common Store Resources

**Upcoming documentation:**

 - [Added InstallmentCriteria variable](https://github.com/vtex-apps/store-resources/pull/104)
```


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

[User] Show me the implementation of store-resources/react/Mutations.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
/** DEPRECATED, being kept just for retrocompatibility.
 * Create individual entry points for each mutation instead */

import addToCart from './mutations/addToCart.gql'
import updateItems from './mutations/updateItems.gql'
import updateOrderFormProfile from './mutations/updateOrderFormProfile.gql'
import updateOrderFormShipping from './mutations/updateOrderFormShipping.gql'
import updateOrderFormCheckin from './mutations/updateOrderFormCheckin.gql'

export default {
  addToCart,
  updateItems,
  updateOrderFormProfile,
  updateOrderFormShipping,
  updateOrderFormCheckin,
}

```


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

[User] Show me the implementation of store-resources/react/OrderFormContext.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React, { Component, useContext } from 'react'
import hoistNonReactStatics from 'hoist-non-react-statics'
import PropTypes from 'prop-types'

const OrderFormContext = React.createContext({})
const { Provider } = OrderFormContext

function orderFormConsumer(WrappedComponent) {
  const WithOrderForm = props => {
    const { orderFormContext } = useContext(OrderFormContext)

    return <WrappedComponent {...props} orderFormContext={orderFormContext} />
  }

  WithOrderForm.displayName = `OrderFormContext(${
    Component.displayName || Component.name || 'Component'
  })`
  WithOrderForm.WrappedComponent = WrappedComponent

  return hoistNonReactStatics(WithOrderForm, WrappedComponent)
}

const useOrderForm = () => {
  const context = useContext(OrderFormContext)

  return context.orderFormContext
}

const contextPropTypes = PropTypes.shape({
  /* Toast message that will be displayed  */

  message: PropTypes.shape({
    isSuccess: PropTypes.bool,
    message: PropTypes.string,
  }).isRequired,
  /* Is information still loading */

  loading: PropTypes.bool.isRequired,
  /* Function to refetch the orderForm query */

  refetch: PropTypes.func.isRequired,
  /* Function to add a new item into the orderForm */

  addItem: PropTypes.func.isRequired,
  /* Function to update the orderForm */

  updateOrderForm: PropTypes.func.isRequired,
  /* Function to update the orderForm profile data */

  updateOrderFormProfile: PropTypes.func.isRequired,
  /* Function to update the orderForm and refetch the data */

  updateAndRefetchOrderForm: PropTypes.func.isRequired,
  /* Function to update the message */

  updateToastMessage: PropTypes.func.isRequired,
  /* Function to update the shipping data */

  updateOrderFormShipping: PropTypes.func.isRequired,
  /* Order form */

  orderForm: PropTypes.shape({
    /* Order form id */

    orderFormId: PropTypes.string,
    /* Total price of the order */

    value: PropTypes.number,
    /* Items in the mini cart */

    items: PropTypes.arrayOf(PropTypes.object),
    /* CustomData in the OrderForm */

    customData: PropTypes.shape({
      customApps: PropTypes.arrayOf(
        PropTypes.shape({
          id: PropTypes.string,
          fields: PropTypes.object,
        })
      ),
    }),
    /* Shipping Address */

    shippingData: PropTypes.shape({
      address: PropTypes.shape({
        addressName: PropTypes.string,
        addressType: PropTypes.string,
        city: PropTypes.string,
        complement: PropTypes.string,
        country: PropTypes.string,
        id: PropTypes.string,
        neighborhood: PropTypes.string,
        number: PropTypes.string,
        postalCode: PropTypes.string,
        receiverName: PropTypes.string,
        reference: PropTypes.string,
        state: PropTypes.string,
        street: PropTypes.string,
        userId: PropTypes.string,
      }),
      /* Available Addresses */

      availableAddresses: PropTypes.arrayOf(PropTypes.object),
    }),
  }),
}).isRequired

export default {
  orderFormConsumer,
  contextPropTypes,
  Provider,
  useOrderForm,
}

```


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

[User] Show me the implementation of store-resources/react/useQueryProducts.tsx from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { QueryHookOptions } from 'react-apollo'
import { useQuery } from 'react-apollo'

import type { Data, Variables } from './QueryProductsTypes'
import products from './queries/products.gql'

export default function useQueryProducts(
  options: QueryHookOptions<Data, Variables>
) {
  return useQuery<Data, Variables>(products, options)
}

```


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

[User] Show me the implementation of store-resources/react/QueryRecommendationsAndBenefits.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import recommendationsAndBenefits from './queries/recommendationsAndBenefits.gql'

export default recommendationsAndBenefits

```


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

[User] Show me the implementation of store-resources/react/QueryAddress.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import address from './queries/address.gql'

export default address

```


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

[User] Show me the implementation of store-resources/react/QuerySuggestionProducts.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import productSuggestions from './queries/productSuggestions.gql'

export default productSuggestions

```


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

[User] Show me the implementation of store-resources/react/MutationUpdateOrderFormCheckin.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import updateOrderFormCheckin from './mutations/updateOrderFormCheckin.gql'

export default updateOrderFormCheckin

```


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

[User] Show me the implementation of store-resources/react/QuerySponsoredProducts.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import QuerySponsoredProducts from './queries/sponsoredProducts.gql'

export default QuerySponsoredProducts

```


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

[User] Show me the implementation of store-resources/react/QuerySession.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import session from './queries/session.gql'

export default session

```


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

[User] Show me the implementation of store-resources/react/QueryBanners.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import banners from './queries/banners.gql'

export default banners

```


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

[User] Show me the implementation of store-resources/react/QueryProductSearchV2.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import productSearchV2 from './queries/productSearchV2.gql'

export default productSearchV2

```


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

[User] Show me the implementation of store-resources/react/MutationAddToCart.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import addToCart from './mutations/addToCart.gql'

export default addToCart

```


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

[User] Show me the implementation of store-resources/react/QueryProductsTypes.tsx from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { InstallmentsCriteria, ItemsFilter } from 'vtex.search-graphql'

import type { CommertialOfferFragment } from './fragments/CommertialOfferType'
import CommertialOfferType from './fragments/CommertialOfferType'
import type { InstallmentFragment } from './fragments/InstallmentType'
import InstallmentType from './fragments/InstallmentType'
import type { SkuFragment } from './fragments/ItemType'
import ItemType from './fragments/ItemType'
import type { ProductFragment } from './fragments/ProductType'
import ProductType from './fragments/ProductType'
import type { SellerFragment } from './fragments/SellerType'
import SellerType from './fragments/SellerType'

type Installment = {
  Installments: InstallmentFragment[]
}

type CommertialOffer = CommertialOfferFragment & Installment

type Seller = SellerFragment & CommertialOffer

type Item = SkuFragment & { sellers: Seller[] }

export type Data = {
  products: Array<ProductFragment & { items: Item[] }>
}

export type Variables = {
  category?: string
  collection?: string
  specificationFilters?: string[]
  orderBy?: string
  from?: number
  to?: number
  hideUnavailableItems?: boolean
  skusFilter?: ItemsFilter
  installmentCriteria?: InstallmentsCriteria
  shippingOptions?: string[]
  advertisementOptions: AdvertisementOptions
}

type AdvertisementOptions = {
  showSponsored?: boolean
  sponsoredCount?: number
  repeatSponsoredProducts?: boolean
  advertisementPlacement?: string
}

// We need to fake usage of some JS from the other modules so they
// are not removed out from the type generation
export {
  CommertialOfferType,
  InstallmentType, ItemType, ProductType, SellerType
}

```


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

[User] Show me the implementation of store-resources/react/QuerySearchSuggestions.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import searchSuggestions from './queries/searchSuggestions.gql'

export default searchSuggestions

```


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

[User] Show me the implementation of store-resources/react/QueryItemsWithSimulation.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import productWithSimulation from './queries/itemsWithSimulation.gql'

export default productWithSimulation

```


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

[User] Show me the implementation of store-resources/react/QueryProductSearchV3.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import productSearchV3 from './queries/productSearchV3.gql'

export default productSearchV3

```


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

[User] Show me the implementation of store-resources/react/QueryCorrection.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import correction from './queries/correction.gql'

export default correction

```


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

[User] Show me the implementation of store-resources/react/MutationUpdateOrderFormProfile.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import updateOrderFormProfile from './mutations/updateOrderFormProfile.gql'

export default updateOrderFormProfile

```


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

[User] Show me the implementation of store-resources/react/QueryRecommendationShelf.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import recommendationShelf from './queries/recommendationShelf.gql'

export default recommendationShelf

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "version": "0.104.3",
  "dependencies": {
    "apollo-client": "^2.6.8",
    "react": "^16.12.0",
    "react-apollo": "^3.1.3",
    "react-dom": "^16.12.0",
    "react-intl": "^3.12.0"
  },
  "devDependencies": {
    "@apollo/react-testing": "^3.1.3",
    "@types/jest": "^25.1.4",
    "@types/node": "^13.9.8",
    "@types/react": "^16.9.31",
    "@vtex/tsconfig": "^0.4.4",
    "apollo-cache-inmemory": "^1.6.5",
    "graphql": "^14.6.0",
    "typescript": "3.9.7",
    "vtex.pixel-manager": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-manager@1.7.0/public/@types/vtex.pixel-manager",
    "vtex.pwa-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pwa-graphql@1.16.0/public/@types/vtex.pwa-graphql",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.128.2/public/@types/vtex.render-runtime",
    "vtex.search-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-graphql@0.60.1/public/@types/vtex.search-graphql",
    "vtex.store-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.139.0/public/@types/vtex.store-graphql",
    "vtex.store-resources": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-resources@0.78.0/public/@types/vtex.store-resources"
  }
}

```


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

[User] Show me the implementation of store-resources/react/QueryProduct.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import product from './queries/product.gql'

export default product

```


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

[User] Show me the implementation of store-resources/react/QueryFacets.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import facets from './queries/facets.gql'

export default facets

```


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

[User] Show me the implementation of store-resources/react/MutationUpdateItems.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import updateItems from './mutations/updateItems.gql'

export default updateItems

```


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

[User] Show me the implementation of store-resources/react/QueryProductSearch.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import productSearch from './queries/productSearch.gql'

export default productSearch

```


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

[User] Show me the implementation of store-resources/react/QuerySearchMetadataV2.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import searchMetadataV2 from './queries/searchMetadataV2.gql'

export default searchMetadataV2

```


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

[User] Show me the implementation of store-resources/react/QueryFacetsV2.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import facetsV2 from './queries/facetsV2.gql'

export default facetsV2

```


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

[User] Show me the implementation of store-resources/react/QueryProductPreviewFragment.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import productPreviewFragment from './queries/productPreview.gql'

export default productPreviewFragment

```


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

[User] Show me the implementation of store-resources/react/PWAContext.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import React, {
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react'
import { Helmet, useRuntime } from 'vtex.render-runtime'
import { graphql } from 'react-apollo'
import { usePixel } from 'vtex.pixel-manager/PixelContext'

import pwaData from './queries/pwaData.gql'

const PWAContext = React.createContext(null)

const PWAProvider = ({ rootPath, children, data = {} }) => {
  const { manifest, iOSIcons, splashes, pwaSettings, loading, error } = data
  const { push } = usePixel()
  const { workspace } = useRuntime()

  const deferredPrompt = useRef(null)
  /* beforeinstallprompt event is fired even after the userChoice is to cancel (and there is no need to re-render) */
  const captured = useRef(false)

  const [alreadyInstalled, setAlreadyInstalled] = useState(false)
  const [installDismissed, setInstallDismissed] = useState(false)

  useEffect(() => {
    const handleBeforeInstall = e => {
      const { promptOnCustomEvent, disablePrompt } = pwaSettings

      if (promptOnCustomEvent !== 'default' && !captured.current) {
        e.preventDefault()

        if (disablePrompt) {
          return false
        }

        deferredPrompt.current = e
        captured.current = true

        return false
      }

      return true
    }

    window.addEventListener('beforeinstallprompt', handleBeforeInstall)

    return () =>
      window.removeEventListener('beforeinstallprompt', handleBeforeInstall)
  }, [captured, pwaSettings])

  useEffect(() => {
    const webAppInstalled = localStorage.getItem('webAppInstalled')

    if (webAppInstalled) {
      setAlreadyInstalled(webAppInstalled)
    }

    const webAppInstallDismissed = localStorage.getItem(
      'webAppInstallDismissed'
    )

    if (webAppInstallDismissed) {
      setInstallDismissed(webAppInstallDismissed)
    }
  }, [])

  const showInstallPrompt = useCallback(() => {
    const prompt = deferredPrompt.current

    if (prompt) {
      prompt.prompt()
      prompt.userChoice.then(choiceResult => {
        if (choiceResult.outcome === 'accepted') {
          localStorage.setItem('webAppInstalled', 'true')
        } else {
          localStorage.setItem('webAppInstallDismissed', 'true')
        }

        push({
          event: 'installWebApp',
          userChoice: choiceResult.outcome,
        })
        deferredPrompt.current = null
      })
    }
  }, [])

  const context = useMemo(() => {
    if (pwaSettings) {
      const { disablePrompt, promptOnCustomEvent } = pwaSettings
      /* browsers for ios devices doesn't support install prompt */
      const isIOS =
        navigator && !!navigator.userAgent.match(/(iPod|iPhone|iPad)/)

      return {
        showInstallPrompt,
        settings: {
          promptOnCustomEvent:
            disablePrompt || isIOS || installDismissed || alreadyInstalled
              ? ''
              : promptOnCustomEvent,
        },
      }
    }
  }, [showInstallPrompt, pwaSettings, alreadyInstalled])

  const hasManifest = !loading && manifest && !error

  const manifestHrefSuffix =
    workspace === 'master' ? '' : `?workspace=${workspace}`

  return (
    <PWAContext.Provider value={context}>
      {hasManifest && (
        <Helmet
          meta={[
            { name: 'theme-color', content: manifest.theme_color },
            { name: 'apple-mobile-web-app-capable', content: 'yes' },
          ]}
          link={[
            {
              rel: 'manifest',
              href: `${rootPath}/pwa/manifest.json${manifestHrefSuffix}`,
            },
            ...(iOSIcons
              ? iOSIcons.map(icon => ({
                  rel: 'apple-touch-icon',
                  sizes: icon.sizes,
                  href: `${rootPath}${icon.src}`,
                }))
              : []),
            ...(splashes
              ? splashes.map(splash => ({
                  href: `${rootPath}${splash.src}`,
                  sizes: splash.sizes,
                  rel: 'apple-touch-startup-image',
                }))
              : []),
          ].filter(Boolean)}
        />
      )}
      {children}
    </PWAContext.Provider>
  )
}

const usePWA = () => {
  return useContext(PWAContext)
}

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

export default {
  PWAContext,
  PWAProvider: graphql(pwaData, options)(PWAProvider),
  usePWA,
}

```


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

[User] Show me the implementation of store-resources/react/Queries.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
/** DEPRECATED, being kept just for retrocompatibility.
 * Create individual entry points for each query instead */

import orderForm from './queries/orderForm.gql'
import product from './queries/product.gql'
import productPreviewFragment from './queries/productPreview.gql'
import recommendationsAndBenefits from './queries/recommendationsAndBenefits.gql'
import search from './queries/search.gql'
import productSearch from './queries/productSearch.gql'
import productSearchV2 from './queries/productSearchV2.gql'
import session from './queries/session.gql'
import productBenefits from './queries/productBenefits.gql'
import address from './queries/address.gql'
import searchMetadata from './queries/searchMetadata.gql'
import productCategoryTree from './queries/UNSTABLE__productCategoryTree.gql'
import facets from './queries/facets.gql'

export default {
  address,
  orderForm,
  product,
  productSearch,
  productSearchV2,
  productPreviewFragment,
  recommendationsAndBenefits,
  search,
  session,
  productBenefits,
  UNSTABLE__productCategoryTree: productCategoryTree,
  searchMetadata,
  facets,
}

```


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

[User] Show me the implementation of store-resources/react/QuerySearchMetadata.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import searchMetadata from './queries/searchMetadata.gql'

export default searchMetadata

```


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

[User] Show me the implementation of store-resources/react/QueryTopSearches.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import topSearches from './queries/topSearches.gql'

export default topSearches

```


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

[User] Show me the implementation of store-resources/react/QueryProducts.tsx from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { DocumentNode } from 'graphql'

import products from './queries/products.gql'

export default products as DocumentNode

```


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

[User] Show me the implementation of store-resources/react/MutationUpdateOrderFormShipping.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import updateOrderFormShipping from './mutations/updateOrderFormShipping.gql'

export default updateOrderFormShipping

```


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

[User] Show me the implementation of store-resources/react/QueryOrderForm.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import orderForm from './queries/orderForm.gql'

export default orderForm

```


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

[User] Show me the implementation of store-resources/react/QueryProductBenefits.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import productBenefits from './queries/productBenefits.gql'

export default productBenefits

```


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

[User] Show me the implementation of store-resources/react/QueryUNSTABLEProductCategoryTree.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import productCategoryTree from './queries/UNSTABLE__productCategoryTree.gql'

export default productCategoryTree

```


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

[User] Show me the implementation of store-resources/react/QueryProductRecommendations.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import productRecommendations from './queries/productRecommendations.gql'

export default productRecommendations

```


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

[User] Show me the implementation of store-resources/react/QuerySearch.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import search from './queries/search.gql'

export default search

```


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

[User] Show me the implementation of store-resources/react/QueryAutocompleteSearchSuggestions.js from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```javascript
import autocompleteSearchSuggestions from './queries/autocompleteSearchSuggestions.gql'

export default autocompleteSearchSuggestions

```


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

[User] Show me the implementation of store-resources/react/fragments/commertialOffer.graphql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
fragment CommertialOfferFragment on Offer {
  discountHighlights {
    name
  }
  teasers {
    name
    conditions {
      minimumQuantity
      parameters {
        name
        value
      }
    }
    effects {
      parameters {
        name
        value
      }
    }
  }
  Price
  ListPrice
  Tax
  taxPercentage
  spotPrice
  PriceWithoutDiscount
  RewardValue
  PriceValidUntil
  AvailableQuantity
}

```


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

[User] Show me the implementation of store-resources/react/fragments/CommertialOfferType.ts from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { Offer } from 'vtex.search-graphql'

export type CommertialOfferFragment = Pick<
  Offer,
  | 'discountHighlights'
  | 'teasers'
  | 'Price'
  | 'ListPrice'
  | 'Tax'
  | 'taxPercentage'
  | 'spotPrice'
  | 'PriceWithoutDiscount'
  | 'RewardValue'
  | 'PriceValidUntil'
  | 'AvailableQuantity'
>

export default {}

```


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

[User] Show me the implementation of store-resources/react/fragments/seller.graphql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
fragment SellerFragment on Seller {
  sellerId
  sellerName
  sellerDefault
}

```


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

[User] Show me the implementation of store-resources/react/fragments/ProductType.tsx from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```tsx
import type { Product } from 'vtex.search-graphql'

export type ProductFragment = Pick<
  Product,
  | 'advertisement'
  | 'cacheId'
  | 'productId'
  | 'description'
  | 'productName'
  | 'productReference'
  | 'linkText'
  | 'brand'
  | 'brandId'
  | 'link'
  | 'categories'
  | 'priceRange'
  | 'specificationGroups'
  | 'skuSpecifications'
  | 'productClusters'
  | 'clusterHighlights'
  | 'properties'
>

export default {}

```


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

[User] Show me the implementation of store-resources/react/fragments/item.graphql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
fragment ItemFragment on SKU {
  itemId
  name
  nameComplete
  complementName
  ean
  variations {
    name
    values
  }
  referenceId {
    Key
    Value
  }
  measurementUnit
  unitMultiplier
  images {
    cacheId
    imageId
    imageLabel
    imageTag
    imageUrl
    imageText
  }
}

```


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

[User] Show me the implementation of store-resources/react/fragments/InstallmentType.ts from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { Installment } from 'vtex.search-graphql'

export type InstallmentFragment = Pick<
  Installment,
  | 'Value'
  | 'InterestRate'
  | 'TotalValuePlusInterestRate'
  | 'NumberOfInstallments'
  | 'Name'
  | 'PaymentSystemName'
>

export default {}

```


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

[User] Show me the implementation of store-resources/react/fragments/SellerType.ts from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { Seller } from 'vtex.search-graphql'

export type SellerFragment = Pick<
  Seller,
  'sellerId' | 'sellerName' | 'sellerDefault'
>

export default {}

```


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

[User] Show me the implementation of store-resources/react/fragments/installment.graphql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
fragment InstallmentFragment on Installment {
  Value
  InterestRate
  TotalValuePlusInterestRate
  NumberOfInstallments
  Name
  PaymentSystemName
}

```


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

[User] Show me the implementation of store-resources/react/fragments/ItemType.ts from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { Sku } from 'vtex.search-graphql'

export type SkuFragment = Pick<
  Sku,
  | 'itemId'
  | 'name'
  | 'nameComplete'
  | 'complementName'
  | 'ean'
  | 'variations'
  | 'referenceId'
  | 'measurementUnit'
  | 'unitMultiplier'
  | 'images'
>

export default {}

```


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

[User] Show me the implementation of store-resources/react/fragments/product.graphql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
fragment ProductFragment on Product {
  advertisement {
    adId
    adResponseId
    adRequestId
  }
  cacheId
  productId
  description
  productName
  productReference
  linkText
  brand
  brandId
  link
  categories
  categoryId
  releaseDate
  priceRange {
    sellingPrice {
      highPrice
      lowPrice
    }
    listPrice {
      highPrice
      lowPrice
    }
  }
  specificationGroups {
    name
    originalName
    specifications {
      name
      originalName
      values
    }
  }
  skuSpecifications {
    field {
      name
      originalName
    }
    values {
      name
      originalName
    }
  }
  productClusters {
    id
    name
  }
  clusterHighlights {
    id
    name
  }
  properties {
    name
    values
  }
}

```


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

[User] Show me the implementation of store-resources/react/mutations/updateItems.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation updateItems($orderFormId: String, $items: [OrderFormItemInput]) {
  updateItems(orderFormId: $orderFormId, items: $items) {
    cacheId
    orderFormId
    value
    totalizers {
      id
      name
      value
    }
    items {
      id
      productId
      name
      imageUrl
      detailUrl
      productRefId
      additionalInfo {
        brandName
      }
      canHaveAttachment
      productCategoryIds
      productCategories
      skuName
      quantity
      sellingPrice
      listPrice
      parentItemIndex
      parentAssemblyBinding
      seller
      cartIndex
      sellingPriceWithAssemblies
      assemblyOptions {
        added {
          item {
            name
            sellingPrice
            quantity
            sellingPriceWithAssemblies
            assemblyOptions {
              added {
                item {
                  name
                  sellingPrice
                  quantity
                  sellingPriceWithAssemblies
                }
                normalizedQuantity
                choiceType
                extraQuantity
              }
              removed {
                removedQuantity
                initialQuantity
                name
              }
              parentPrice
            }
          }
          normalizedQuantity
          choiceType
          extraQuantity
        }
        removed {
          removedQuantity
          initialQuantity
          name
        }
        parentPrice
      }
      priceDefinition {
        calculatedSellingPrice
        total
        sellingPrices {
          quantity
          value
        }
      }
    }
    shippingData {
      address {
        id
        neighborhood
        complement
        number
        street
        postalCode
        city
        reference
        addressName
        addressType
      }
      availableAddresses {
        id
        neighborhood
        complement
        number
        street
        postalCode
        city
        reference
        addressName
        addressType
      }
    }
    clientProfileData {
      email
      firstName
    }
    storePreferencesData {
      countryCode
      currencyCode
      timeZone
    }
    checkedInPickupPointId
    isCheckedIn
  }
}

```


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

[User] Show me the implementation of store-resources/react/mutations/updateOrderFormCheckin.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation updateOrderFormCheckin(
  $orderFormId: String
  $checkin: OrderFormCheckinInput
) {
  updateOrderFormCheckin(orderFormId: $orderFormId, checkin: $checkin) {
    isCheckedIn
    checkedInPickupPointId
    shippingData {
      selectedAddresses {
        id
        street
        number
        receiverName
        complement
        neighborhood
        country
        state
        geoCoordinates
        postalCode
        city
        reference
        addressName
        addressType
      }
    }
  }
}
```


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

[User] Show me the implementation of store-resources/react/mutations/updateOrderFormProfile.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation updateOrderFormProfile(
  $orderFormId: String
  $fields: OrderFormProfileInput
) {
  updateOrderFormProfile(orderFormId: $orderFormId, fields: $fields) {
    orderFormId
  }
}

```


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

[User] Show me the implementation of store-resources/react/mutations/addToCart.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation addItem($orderFormId: String, $items: [OrderFormItemInput], $utmParams: OrderFormInputUTMParams, $utmiParams: OrderFormInputUTMIParams) {
  addItem(orderFormId: $orderFormId, items: $items, utmParams: $utmParams, utmiParams: $utmiParams) {
    cacheId
    orderFormId
    value
    totalizers {
      id
      name
      value
    }
    items {
      id
      productId
      name
      imageUrl
      detailUrl
      productRefId
      additionalInfo {
        brandName
      }
      canHaveAttachment
      productCategoryIds
      productCategories
      skuName
      quantity
      sellingPrice
      listPrice
      parentItemIndex
      parentAssemblyBinding
      seller
      cartIndex
      sellingPriceWithAssemblies
      assemblyOptions {
        added {
          item {
            name
            sellingPrice
            quantity
            sellingPriceWithAssemblies
            assemblyOptions {
              added {
                item {
                  name
                  sellingPrice
                  quantity
                  sellingPriceWithAssemblies
                }
                normalizedQuantity
                choiceType
                extraQuantity
              }
              removed {
                removedQuantity
                initialQuantity
                name
              }
              parentPrice
            }
          }
          normalizedQuantity
          choiceType
          extraQuantity
        }
        removed {
          removedQuantity
          initialQuantity
          name
        }
        parentPrice
      }
      priceDefinition {
        calculatedSellingPrice
        total
        sellingPrices {
          quantity
          value
        }
      }
    }
    shippingData {
      address {
        id
        neighborhood
        complement
        number
        street
        postalCode
        city
        reference
        addressName
        addressType
      }
      availableAddresses {
        id
        neighborhood
        complement
        number
        street
        postalCode
        city
        reference
        addressName
        addressType
      }
    }
    clientProfileData {
      email
      firstName
    }
    storePreferencesData {
      countryCode
      currencyCode
      timeZone
    }
    checkedInPickupPointId
    isCheckedIn
  }
}

```


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

[User] Show me the implementation of store-resources/react/mutations/updateOrderFormShipping.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation updateOrderFormShipping(
  $orderFormId: String
  $address: OrderFormAddressInput
) {
  updateOrderFormShipping(orderFormId: $orderFormId, address: $address) {
    orderFormId
    isCheckedIn
    checkedInPickupPointId
    shippingData {
      address {
        id
        neighborhood
        complement
        number
        street
        postalCode
        city
        reference
        addressName
        addressType
        geoCoordinates
        state
        receiverName
        country
      }
      availableAddresses {
        id
        neighborhood
        complement
        number
        street
        postalCode
        city
        reference
        addressName
        addressType
        geoCoordinates
        state
        receiverName
        country
      }
    }
  }
}

```


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

[User] Show me the implementation of store-resources/react/queries/recommendationsAndBenefits.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
# File deprecated. To be removed in next major!
query RecommendationsAndBenefits(
  $slug: String
  $identifier: ProductUniqueIdentifier
) {
  product(slug: $slug, identifier: $identifier)
    @context(provider: "vtex.search-graphql") {
    cacheId
    recommendations {
      view {
        cacheId
        productId
        productName
        description
        link
        linkText
        brand
        items {
          name
          itemId
          referenceId {
            Value
          }
          images {
            imageId
            imageLabel
            imageTag
            imageUrl
            imageText
          }
          sellers {
            sellerId
            sellerName
            addToCartLink
            sellerDefault
            commertialOffer {
              Price
              ListPrice
              PriceWithoutDiscount
              RewardValue
              PriceValidUntil
              AvailableQuantity
              Tax
              CacheVersionUsedToCallCheckout
              Installments(criteria: MAX) {
                Value
                InterestRate
                TotalValuePlusInterestRate
                NumberOfInstallments
                Name
                PaymentSystemName
              }
            }
          }
        }
      }
      buy {
        cacheId
        productId
        productName
        description
        link
        linkText
        brand
        items {
          name
          itemId
          referenceId {
            Value
          }
          images {
            imageId
            imageLabel
            imageTag
            imageUrl
            imageText
          }
          sellers {
            sellerId
            sellerName
            addToCartLink
            sellerDefault
            commertialOffer {
              Price
              ListPrice
              PriceWithoutDiscount
              RewardValue
              PriceValidUntil
              AvailableQuantity
              Tax
              CacheVersionUsedToCallCheckout
              Installments(criteria: MAX) {
                Value
                InterestRate
                TotalValuePlusInterestRate
                NumberOfInstallments
                Name
                PaymentSystemName
              }
            }
          }
        }
      }
      similars {
        cacheId
        productId
        productName
        description
        link
        linkText
        brand
        items {
          name
          itemId
          referenceId {
            Value
          }
          images {
            imageId
            imageLabel
            imageTag
            imageUrl
            imageText
          }
          sellers {
            sellerId
            sellerName
            addToCartLink
            sellerDefault
            commertialOffer {
              Price
              ListPrice
              PriceWithoutDiscount
              RewardValue
              PriceValidUntil
              AvailableQuantity
              Tax
              CacheVersionUsedToCallCheckout
              Installments(criteria: MAX) {
                Value
                InterestRate
                TotalValuePlusInterestRate
                NumberOfInstallments
                Name
                PaymentSystemName
              }
            }
          }
        }
      }
    }
    benefits {
      featured
      id
      name
      items {
        benefitProduct {
          cacheId
          productName
          productId
          description
          linkText
          categoryId
          brand
          properties {
            name
            values
          }
          items {
            itemId
            name
            nameComplete
            complementName
            ean
            referenceId {
              Key
              Value
            }
            measurementUnit
            unitMultiplier
            images {
              imageId
              imageLabel
              imageTag
              imageUrl
              imageText
            }
            sellers {
              sellerId
              sellerName
              addToCartLink
              sellerDefault
              commertialOffer {
                Price
                ListPrice
                PriceWithoutDiscount
                RewardValue
                PriceValidUntil
                AvailableQuantity
                Tax
                CacheVersionUsedToCallCheckout
                Installments(criteria: MAX) {
                  Value
                  InterestRate
                  TotalValuePlusInterestRate
                  NumberOfInstallments
                  Name
                  PaymentSystemName
                }
              }
            }
            variations {
              name
            }
          }
        }
        discount
        minQuantity
        benefitSKUIds
      }
      teaserType
    }
  }
}

```


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

[User] Show me the implementation of store-resources/react/queries/productRecommendations.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
#import '../fragments/product.graphql'
#import '../fragments/item.graphql'
#import '../fragments/seller.graphql'
#import '../fragments/commertialOffer.graphql'
#import '../fragments/installment.graphql'

query ProductRecommendations(
  $identifier: ProductUniqueIdentifier
  $type: CrossSelingInputEnum
  $searchState: String
) {
  productRecommendations(
    identifier: $identifier
    type: $type
    searchState: $searchState
  ) @context(provider: "vtex.search-graphql") {
    ...ProductFragment
    items {
      ...ItemFragment
      sellers {
        ...SellerFragment
        commertialOffer {
          ...CommertialOfferFragment
          Installments(criteria: MAX) {
            ...InstallmentFragment
          }
        }
      }
    }
  }
}

```


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

[User] Show me the implementation of store-resources/react/queries/product.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
#import '../fragments/product.graphql'
#import '../fragments/item.graphql'
#import '../fragments/seller.graphql'
#import '../fragments/commertialOffer.graphql'
#import '../fragments/installment.graphql'

query Product(
  $slug: String
  $identifier: ProductUniqueIdentifier
  $skipCategoryTree: Boolean = false
) {
  product(slug: $slug, identifier: $identifier)
    @context(provider: "vtex.search-graphql") {
    ...ProductFragment
    titleTag
    metaTagDescription
    categoryId
    categoryTree @skip(if: $skipCategoryTree) {
      id
      name
      href
    }
    items {
      ...ItemFragment
      videos {
        videoUrl
      }
      sellers {
        ...SellerFragment
        addToCartLink
        sellerDefault
        commertialOffer {
          ...CommertialOfferFragment
          CacheVersionUsedToCallCheckout
          Installments {
            ...InstallmentFragment
          }
        }
      }
      kitItems {
        itemId
        amount
        product {
          productName
          productId
          description
          linkText
          categoryTree {
            id
            name
            href
          }
          categoryId
          brand
          properties {
            name
            values
          }
        }
        sku {
          itemId
          name
          referenceId {
            Key
            Value
          }
          images {
            imageId
            imageLabel
            imageTag
            imageUrl
            imageText
          }
          sellers {
            ...SellerFragment
            addToCartLink
            sellerDefault
            commertialOffer {
              ...CommertialOfferFragment
              Installments(criteria: MAX) {
                ...InstallmentFragment
              }
            }
          }
        }
      }
      attachments {
        id
        name
        required
      }
      estimatedDateArrival
    }
    itemMetadata {
      items {
        id
        name
        imageUrl
        seller
        assemblyOptions {
          id
          name
          required
          inputValues {
            label
            maxLength
            type
            domain
            defaultValue
          }
          composition {
            minQuantity
            maxQuantity
            items {
              id
              minQuantity
              maxQuantity
              priceTable
              seller
              initialQuantity
            }
          }
        }
      }
      priceTable {
        type
        values {
          id
          assemblyId
          price
        }
      }
    }
  }
}

```


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

[User] Show me the implementation of store-resources/react/queries/searchSuggestions.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query searchSuggestions($fullText: String!, $searchState: String) {
  searchSuggestions(fullText: $fullText, searchState: $searchState)
    @context(provider: "vtex.search-graphql") {
    searches {
      term
      count
    }
  }
}

```


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

[User] Show me the implementation of store-resources/react/queries/productBenefits.gql from the store-resources VTEX app.

[Assistant]
Here's the implementation:

```graphql
query ProductBenefits($slug: String, $identifier: ProductUniqueIdentifier) {
  product(slug: $slug, identifier: $identifier)
    @context(provider: "vtex.search-graphql") {
    cacheId
    benefits {
      featured
      id
      name
      items {
        benefitProduct {
          cacheId
          productName
          productId
          description
          linkText
          categoryId
          brand
          properties {
            name
            values
          }
          specificationGroups {
            name
            originalName
            specifications {
              name
              originalName
              values
            }
          }
          items {
            itemId
            name
            nameComplete
            complementName
            ean
            referenceId {
              Key
              Value
            }
            measurementUnit
            unitMultiplier
            images {
              imageId
              imageLabel
              imageTag
              imageUrl
              imageText
            }
            sellers {
              sellerId
              sellerName
              addToCartLink
              sellerDefault
              commertialOffer {
                Price
                ListPrice
                PriceWithoutDiscount
                RewardValue
                PriceValidUntil
                AvailableQuantity
                Tax
                CacheVersionUsedToCallCheckout
                Installments {
                  Value
                  InterestRate
                  TotalValuePlusInterestRate
                  NumberOfInstallments
                  Name
                  PaymentSystemName
                }
              }
            }
            variations {
              name
            }
          }
        }
        discount
        minQuantity
        benefitSKUIds
      }
      teaserType
    }
  }
}

```