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

[User] Show me the implementation of marketplace-financial-commission-cron/node/utils.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const generateToken = async (length: number): Promise<string> => {
  const characters =
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'.split('')

  const token = []

  for (let i = 0; i < length; i++) {
    const j: any = (Math.random() * (characters.length - 1)).toFixed(0)

    token[i] = characters[j]
  }

  return token.join('')
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/package.json from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "dependencies": {
    "co-body": "^6.0.0",
    "ramda": "^0.25.0"
  },
  "devDependencies": {
    "@types/co-body": "^0.0.3",
    "@types/jest": "^24.0.18",
    "@types/node": "^12.0.0",
    "@types/ramda": "types/npm-ramda#dist",
    "@vtex/api": "6.45.10",
    "@vtex/test-tools": "^3.4.3",
    "@vtex/tsconfig": "^0.5.6",
    "typescript": "3.9.7"
  },
  "scripts": {
    "lint": "tsc --noEmit --pretty"
  },
  "version": "0.2.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 marketplace-financial-commission-cron/node/constants.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const constants = {
  SCHEDULER_CONFIGURATIONS_BUCKET: 'configs',
  SCHEDULER_KEY: 'bearerToken',
  SCHEDULER_KEY_INVOICE: 'bearerTokenInvoice',
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/index.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

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

import type { Clients } from './clients'
import { clients } from './clients'
import { events } from './events'
import { routes } from './routes'

export default new Service<Clients, RecorderState, ParamsContext>({
  clients,
  events,
  routes,
})

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/clients/scheduler.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

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

export default class Scheduler extends JanusClient {
  constructor(context: IOContext, options?: InstanceOptions) {
    super(context, {
      ...options,
      headers: {
        ...options?.headers,
        VtexIdclientAutCookie: context.authToken,
      },
    })
  }

  public setInitialScheduler = async (
    appName: string,
    schedulerData: SchedulerRequest
  ): Promise<void> => {
    await this.http.put(
      `/api/scheduler/master/${appName}/?version=4`,
      schedulerData,
      {
        metric: `schedulerMFC-setup`,
      }
    )
  }

  public deleteScheduler = async (
    appName: string,
    id: string
  ): Promise<void> => {
    await this.http.delete(`/api/scheduler/master/${appName}/${id}?version=4`, {
      metric: `schedulerMFC-delete`,
    })
  }
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/clients/invoiceFinancialComission.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

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

export default class InvoiceFinancialCommission extends AppClient {
  private routes: Routes = {
    generateInvoice: {
      endpoint: 'invoice/generate',
      metric: 'GenerateInvoice',
    },
  }

  constructor(context: IOContext, options?: InstanceOptions) {
    // TODO: update the app version
    super('vtex.marketplace-financial-commission@0.x', context, options)
  }

  private generateInvoiceFinancialCommission = async (
    route: Route,
    retries = 3
  ): Promise<any> => {
    const response = await this.http
      .get(route.endpoint, {
        metric: `marketplaceFinancialCommission-${route.metric}`,
        headers: {
          VtexIdclientAutCookie: this.context.authToken,
        },
        // TODO: update the app version
        baseURL: `http://app.io.vtex.com/vtex.marketplace-financial-commission/v0/${this.context.account}/${this.context.workspace}`,
      })
      .catch((error) => {
        console.error({
          msj: `Error to generate invoice - Endpoint ${route.endpoint}`,
          messageError: error.message,
          statusError: error.status,
        })

        this.context.logger.error({
          message: 'generateInvoiceError',
          error,
          route: route.endpoint,
        })

        if (retries > 0) {
          console.info(`Starting retry Invoices --------> ${retries}`)

          return this.generateInvoiceFinancialCommission(route, retries - 1)
        }

        const resultError = {
          msj: `Error to generate invoice - Endpoint ${route.endpoint}`,
          messageError: error.message,
          statusError: error.status,
        }

        return resultError
      })

    return response
  }

  public generateInvoice = async (): Promise<any> => {
    try {
      const response = await this.generateInvoiceFinancialCommission(
        this.routes.generateInvoice
      )

      return response
    } catch (error) {
      this.context.logger.error({
        message: 'generateInvoiceError',
        error,
      })

      throw new Error('generateInvoice 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 marketplace-financial-commission-cron/node/clients/index.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

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

import InvoiceFinancialCommission from './invoiceFinancialComission'
import MarketFinancialCommission from './marketplaceFinancialCommission'
import Scheduler from './scheduler'
import TypeIntegration from './typeIntegration'

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

  public get scheduler() {
    return this.getOrSet('scheduler', Scheduler)
  }

  public get invoiceFinancialComission() {
    return this.getOrSet(
      'invoiceFinancialComission',
      InvoiceFinancialCommission
    )
  }

  public get typeIntegration() {
    return this.getOrSet('typeIntegration', TypeIntegration)
  }
}

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

metrics.trackCache('financial-commission-cron', memoryCache)

export const clients: ClientsConfig<Clients> = {
  implementation: Clients,
  options: {
    default: {
      retries: 2,
      timeout: TIMEOUT_MS,
      memoryCache,
    },
    events: {
      exponentialTimeoutCoefficient: 2,
      exponentialBackoffCoefficient: 2,
      initialBackoffDelay: 50,
      retries: 1,
      timeout: TIMEOUT_MS,
      concurrency: CONCURRENCY,
    },
  },
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/clients/typeIntegration.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

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

export default class TypeIntegration extends AppClient {
  private baseURL = `http://app.io.vtex.com/vtex.marketplace-financial-commission/v0/${this.context.account}/${this.context.workspace}`

  constructor(context: IOContext, options?: InstanceOptions) {
    // TODO: update the app version
    super('vtex.marketplace-financial-commission@0.x', context, options)
  }

  private getTypeIntegration = async (route: string) => {
    const response = await this.http.get(route, {
      headers: {
        VtexIdclientAutCookie: this.context.authToken,
      },
      baseURL: this.baseURL,
    })

    return response
  }

  public typeIntegration = async (): Promise<any> => {
    try {
      const response = await this.getTypeIntegration(
        this.routes.typeIntegration()
      )

      return response
    } catch (error) {
      this.context.logger.error({
        message: 'Get Type Integration Error',
        error,
      })

      throw new Error('Get Type Integration Error')
    }
  }

  private get routes() {
    const baseRoute = `_v/policy/financial-commission`

    return {
      typeIntegration: () => `/${baseRoute}/typeIntegration`,
    }
  }
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/clients/marketplaceFinancialCommission.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

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

export default class MarketFinancialCommission extends AppClient {
  private routes: Routes = {
    dashboardGenerate: {
      endpoint: 'dashboard/generate',
      metric: 'dashboardGenerate',
    },
  }

  constructor(context: IOContext, options?: InstanceOptions) {
    // TODO: update the app version
    super('vtex.marketplace-financial-commission@0.x', context, options)
  }

  private getMarketplaceFinancialCommission = async (
    route: Route,
    retries = 3
  ): Promise<any> => {
    const response = await this.http
      .post(route.endpoint, {
        metric: `marketplaceFinancialCommission-${route.metric}`,
        headers: {
          VtexIdclientAutCookie: this.context.authToken,
        },
        // TODO: update the app version
        baseURL: `http://app.io.vtex.com/vtex.marketplace-financial-commission/v0/${this.context.account}/${this.context.workspace}`,
      })
      .catch((error) => {
        console.error({
          msj: `Error to generate dashboard - Endpoint ${route.endpoint}`,
          messageError: error.message,
          statusError: error.status,
        })

        this.context.logger.error({
          message: 'dashboardGenerateError',
          error,
          route: route.endpoint,
        })

        if (retries > 0) {
          console.info(`Starting retry --------> ${retries}`)

          return this.getMarketplaceFinancialCommission(route, retries - 1)
        }

        const resultError = {
          msj: `Error to generate dashboard - Endpoint ${route.endpoint}`,
          messageError: error.message,
          statusError: error.status,
        }

        return resultError
      })

    return response
  }

  public dashboardGenerate = async (params?: any): Promise<any> => {
    try {
      if (params) {
        const route: Route = {
          endpoint: `${this.routes.dashboardGenerate.endpoint}?${params}`,
          metric: 'dashboardGenerate',
        }

        const reponse = await this.getMarketplaceFinancialCommission(route)

        return reponse
      }

      const reponse = await this.getMarketplaceFinancialCommission(
        this.routes.dashboardGenerate
      )

      return reponse
    } catch (error) {
      this.context.logger.error({
        message: 'dashboardGenerateError',
        error,
      })

      throw new Error('dashboardGenerate 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 marketplace-financial-commission-cron/node/typings/marketplaceFinancialCommission.d.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface Routes {
  [k: string]: Route
}

interface Route {
  endpoint: string
  metric: string
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/typings/scheduler.d.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface SchedulerRequest {
  id: string
  scheduler: {
    expression: string
    endDate: string
  }
  retry: {
    delay: {
      addMinutes: number
      addHours: number
      addDays: number
    }
    times: number
    backOffRate: number
  }
  request: {
    uri: string
    method: string
    headers: { [k: string]: unknown }
    body: { [k: string]: unknown }
  }
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/typings/global.d.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { ServiceContext } from '@vtex/api'
import type { Clients } from '../clients'

declare global {
  type Context = ServiceContext<Clients>
}

export {}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/configs/schedulerTemplate.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const schedulerTemplate = {
  id: 'TO_BE_REPLACED',
  scheduler: {
    expression: '1 0 * * *',
    endDate: '2029-12-30T23:29:00',
  },
  retry: {
    delay: {
      addMinutes: 5,
      addHours: 0,
      addDays: 0,
    },
    times: 2,
    backOffRate: 1,
  },
  request: {
    uri: '',
    method: 'POST',
    headers: {},
    body: {},
  },
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/events/setupSchedulerInvoice.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable no-await-in-loop */
import type { EventContext } from '@vtex/api'

import type { Clients } from '../clients'
import { schedulerTemplate } from '../configs/schedulerTemplate'
import { constants } from '../constants'
import { generateToken } from '../utils'

const setupSchedulerInvoice = async (ctx: EventContext<Clients>) => {
  const {
    clients: { scheduler, vbase },
    body: { to, from },
    vtex: { logger, production },
  } = ctx

  if (production !== true) {
    logger.info({
      message: 'setupSchedulerInvoice-notProduction',
      data: `production: ${production}`,
    })

    return true
  }

  if (to) {
    const [appName] = to?.id?.split('@')

    if (
      appName.length &&
      `${process.env.VTEX_APP_VENDOR}.${process.env.VTEX_APP_NAME}` === appName
    ) {
      const bearerToken = await generateToken(256)

      logger.info({
        message: 'setupSchedulerInvoice-bearerToken',
        data: bearerToken,
      })

      await vbase.saveJSON(
        constants.SCHEDULER_CONFIGURATIONS_BUCKET,
        constants.SCHEDULER_KEY_INVOICE,
        bearerToken
      )

      logger.info({
        message: 'setupSchedulerInvoice-savedOnVbase',
      })

      const schedulerRequest: SchedulerRequest = schedulerTemplate

      schedulerRequest.id = 'invoice-generate'
      schedulerRequest.request.uri = `https://${ctx.vtex.workspace}--${ctx.vtex.account}.myvtex.com/_v/scheduler/invoice/generate`
      schedulerRequest.request.headers = {
        'cache-control': 'no-cache',
        Authorization: `Bearer ${bearerToken}`,
      }

      try {
        await scheduler.setInitialScheduler(appName, schedulerRequest)
        logger.info({
          message: 'setupSchedulerInvoice-setInvoiceGenerate',
        })
      } catch (error) {
        logger.error({
          message: 'setupSchedulerInvoice-setInvoiceGenerateError',
          error,
        })
      }

      return true
    }
  } else if (from) {
    const [appName] = from?.id?.split('@')

    if (
      appName.length &&
      `${process.env.VTEX_APP_VENDOR}.${process.env.VTEX_APP_NAME}` === appName
    ) {
      await vbase.deleteFile(
        constants.SCHEDULER_CONFIGURATIONS_BUCKET,
        constants.SCHEDULER_KEY_INVOICE
      )

      logger.info({
        message: 'setupSchedulerInvoice-deleteBearerTokenVBase',
      })

      const idName = 'invoice-generate'

      try {
        await scheduler.deleteScheduler(appName, idName)
        logger.info({
          message: 'setupSchedulerInvoice-deleteInvoiceGenerate',
        })
      } catch (error) {
        logger.error({
          message: 'setupSchedulerInvoice-deleteInvoiceGenerateError',
          error,
        })
      }

      return true
    }
  }

  return null
}

export { setupSchedulerInvoice }

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/events/setupSchedulerDashboard.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable no-await-in-loop */
import type { EventContext } from '@vtex/api'

import type { Clients } from '../clients'
import { schedulerTemplate } from '../configs/schedulerTemplate'
import { constants } from '../constants'
import { generateToken } from '../utils'

const setupSchedulerDashboard = async (ctx: EventContext<Clients>) => {
  const {
    clients: { scheduler, vbase, marketFinancialCommission },
    body: { to, from },
    vtex: { logger, production },
  } = ctx

  if (production !== true) {
    logger.info({
      message: 'setupScheduler-notProduction',
      data: `production: ${production}`,
    })

    return true
  }

  if (to) {
    const [appName] = to?.id?.split('@')

    if (
      appName.length &&
      `${process.env.VTEX_APP_VENDOR}.${process.env.VTEX_APP_NAME}` === appName
    ) {
      const bearerToken = await generateToken(256)

      logger.info({
        message: 'setupScheduler-bearerToken',
        data: bearerToken,
      })

      await vbase.saveJSON(
        constants.SCHEDULER_CONFIGURATIONS_BUCKET,
        constants.SCHEDULER_KEY,
        bearerToken
      )

      logger.info({
        message: 'setupScheduler-savedOnVbase',
      })

      const schedulerRequest: SchedulerRequest = schedulerTemplate

      schedulerRequest.id = 'dashboard-generate'
      schedulerRequest.request.uri = `https://${ctx.vtex.workspace}--${ctx.vtex.account}.myvtex.com/_v/scheduler/dashboard/generate`
      schedulerRequest.request.headers = {
        'cache-control': 'no-cache',
        Authorization: `Bearer ${bearerToken}`,
      }

      try {
        await scheduler.setInitialScheduler(appName, schedulerRequest)
        logger.info({
          message: 'setupScheduler-setDashboardGenerate',
        })
      } catch (error) {
        logger.error({
          message: 'setupScheduler-setDashboardGenerateError',
          error,
        })
      }

      try {
        const dayYesterday = new Date(
          new Date().setDate(new Date().getDate() - 1)
        )

        const dateOneMonthAgo = new Date(
          dayYesterday.getTime() - 30 * 24 * 60 * 60 * 1000
        )

        const result: any[] = []

        let loop = dateOneMonthAgo
        const endLoop = dayYesterday

        const processGenerate = async () => {
          while (loop <= endLoop) {
            const [dayToProcess] = loop.toISOString().split('T')
            let params = ''

            params = `dateStart=${dayToProcess}&dateEnd=${dayToProcess}`

            const responseSer =
              await marketFinancialCommission.dashboardGenerate(params)

            result.push(responseSer)

            logger.info({
              message: `setupScheduler-setDashboardGenerateFor30Days`,
              params,
              generate: JSON.stringify(responseSer),
            })

            const newDate = loop.setDate(loop.getDate() + 1)

            loop = new Date(newDate)
            console.info({ loop })

            await delay(2000)
          }

          logger.info({
            message: `DashboardGenerateFor30Days`,
            generate: JSON.stringify(result),
          })
        }

        processGenerate()
      } catch (error) {
        logger.error({
          message: 'setupScheduler-setDashboardGenerateFor30Days',
          error,
        })
      }

      return true
    }
  } else if (from) {
    const [appName] = from?.id?.split('@')

    if (
      appName.length &&
      `${process.env.VTEX_APP_VENDOR}.${process.env.VTEX_APP_NAME}` === appName
    ) {
      await vbase.deleteFile(
        constants.SCHEDULER_CONFIGURATIONS_BUCKET,
        constants.SCHEDULER_KEY
      )

      logger.info({
        message: 'setupScheduler-deleteBearerTokenVBase',
      })

      const idName = 'dashboard-generate'

      try {
        await scheduler.deleteScheduler(appName, idName)
        logger.info({
          message: 'setupScheduler-deleteDashboardGenerate',
        })
      } catch (error) {
        logger.error({
          message: 'setupScheduler-deleteDashboardGenerateError',
          error,
        })
      }

      return true
    }
  }

  return null
}

export { setupSchedulerDashboard }

function delay(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/events/index.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { setupSchedulerDashboard } from './setupSchedulerDashboard'
import { setupSchedulerInvoice } from './setupSchedulerInvoice'

const events = {
  setupSchedulerDashboard,
  setupSchedulerInvoice,
}

export { events }

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/middlewares/scheduler/schedulerAuthenticationInvoice.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

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

import { constants } from '../../constants'

export async function schedulerAuthenticationInvoice(
  ctx: Context,
  next: () => Promise<any>
) {
  const {
    clients: { vbase },
    request: { header },
    vtex: { logger },
  } = ctx

  const autheticationToken = await vbase.getJSON(
    constants.SCHEDULER_CONFIGURATIONS_BUCKET,
    constants.SCHEDULER_KEY_INVOICE
  )

  const verifyToken = async (): Promise<void> => {
    const bearerHeader = header.authorization

    if (bearerHeader) {
      const bearer = bearerHeader.split(' ')

      if (autheticationToken !== bearer[1]) {
        logger.warn({
          message: 'incoming-wrongApiKey',
        })
        throw new AuthenticationError('Unauthorized')
      }
    } else {
      logger.warn({
        message: 'incoming-missingApiKey',
      })
      throw new AuthenticationError('Unauthorized')
    }
  }

  await verifyToken()

  await next()
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/middlewares/scheduler/schedulerAuthenticationDashboard.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

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

import { constants } from '../../constants'

export async function schedulerAuthenticationDashboard(
  ctx: Context,
  next: () => Promise<any>
) {
  const {
    clients: { vbase },
    request: { header },
    vtex: { logger },
  } = ctx

  const autheticationToken = await vbase.getJSON(
    constants.SCHEDULER_CONFIGURATIONS_BUCKET,
    constants.SCHEDULER_KEY
  )

  const verifyToken = async (): Promise<void> => {
    const bearerHeader = header.authorization

    if (bearerHeader) {
      const bearer = bearerHeader.split(' ')

      if (autheticationToken !== bearer[1]) {
        logger.warn({
          message: 'incoming-wrongApiKey',
        })
        throw new AuthenticationError('Unauthorized')
      }
    } else {
      logger.warn({
        message: 'incoming-missingApiKey',
      })
      throw new AuthenticationError('Unauthorized')
    }
  }

  await verifyToken()

  await next()
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/middlewares/dashboard/generateDashboard.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
export async function generateDashboard(
  ctx: Context,
  next: () => Promise<any>
) {
  const {
    clients: { marketFinancialCommission, typeIntegration },
    vtex: { logger },
  } = ctx

  try {
    const { integration } = await typeIntegration.typeIntegration()

    if (
      integration === '1' ||
      integration === undefined ||
      integration === null
    ) {
      const response = await marketFinancialCommission.dashboardGenerate()

      logger.info({
        message: 'outgoing-dashboardGenerateResponse',
        data: response,
      })
    } else {
      logger.info({
        message:
          'The Dashboard does not perform the automatic generation since the financial-commission app is configured as external integration.',
      })
    }

    ctx.status = 200
    ctx.body = 'ok'
  } catch (error) {
    logger.error({
      message: 'outgoing-dashboardGenerateResponseError',
      error,
    })
    ctx.status = 500
  }

  await next()
}

```


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

[User] Show me the implementation of marketplace-financial-commission-cron/node/middlewares/invoice/generateInvoice.ts from the marketplace-financial-commission-cron VTEX app.

[Assistant]
Here's the implementation:

```typescript
export async function generateInvoice(ctx: Context, next: () => Promise<any>) {
  const {
    clients: { invoiceFinancialComission, typeIntegration },
    vtex: { logger },
  } = ctx

  try {
    const { integration } = await typeIntegration.typeIntegration()

    if (
      integration === '1' ||
      integration === undefined ||
      integration === null
    ) {
      const response = await invoiceFinancialComission.generateInvoice()

      logger.info({
        message: 'outgoing-generateInvoice',
        data: response,
      })
    } else {
      logger.info({
        message:
          'The Invoice does not perform the automatic generation since the financial-commission app is configured as external integration.',
      })
    }

    ctx.status = 200
    ctx.body = 'ok'
  } catch (error) {
    logger.error({
      message: 'outgoing-generateInvoiceError',
      error,
    })
    ctx.status = 500
  }

  await next()
}

```


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

[User] Show me the implementation of product-summary-context/docs/README.md from the product-summary-context VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Product Summary Context

> Provides the product context to the product-summary child blocks.

```


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

[User] Show me the implementation of product-summary-context/react/ProductSummaryTypes.ts from the product-summary-context VTEX app.

[Assistant]
Here's the implementation:

```typescript
export interface State {
  product: Product
  isHovering: boolean
  isLoading: boolean
  isPriceLoading: boolean
  selectedItem: SingleSKU,
  selectedQuantity: number,
  inView: boolean
  productQuery?: string
  listName?: string
  query?: string
  position?: number
  sponsoredBadge?: SponsoredBadgeOptions

}

export interface Product {
  advertisement: Advertisement;
  brand: string;
  brandId: number;
  categoryId: string;
  categoryTree: Category[];
  description: string;
  items: SKU[];
  linkText: string;
  metaTagDescription: string;
  priceRange: PriceRangeOptions;
  productName: string;
  productId: string;
  productReference?: string;
  productClusters: Array<{name: string;}>;
  selectedProperties: SelectedProperty[];
  skuSpecifications: SkuSpecification[];
  sku: SingleSKU;
  titleTag: string;
  deliveryPromisesBadges?: BadgeItem[];
}

interface BadgeItem {
  typeName: String;
  pickupId: String;
  pickupName: String;
}

interface Advertisement {
  adId: string;
  campaignId: string;
  adRequestId: string;
  adResponseId: string;
  actionCost: number;
}

interface Image {
  cacheId: string
  imageId: string
  imageLabel: string
  imageTag: string
  imageText: string
  imageUrl: string
}

export interface SKU {
  name: string
  itemId: string
  ean: string
  referenceId: [{ Value: string }]
  sellers: Seller[]
  images: Image[]
}

export interface SingleSKU extends SKU {
  image: Image
  seller: Seller
}

interface Category {
  id: string
  name: string
}

interface PriceRangeOptions {
  listPrice: PriceRange
  sellingPrice: PriceRange
}

interface PriceRange {
  highPrice: number
  lowPrice: number
}

export interface Seller {
  commertialOffer: CommertialOffer
  sellerId: string
  sellerDefault: boolean
}

interface CommertialOffer {
  AvailableQuantity: number
  Installments: Installment[]
  ListPrice: number
  Price: number
}

interface Installment {
  InterestRate: number
  Name: string
  NumberOfInstallments: number
  PaymentSystemName: string
  Value: number
}

interface SkuSpecification {
  field: SkuSpecificationField
  values: SkuSpecificationValues[]
}

interface SkuSpecificationField {
  name: string
}

interface SkuSpecificationValues {
  name: string
}

interface SelectedProperty {
  key: string;
  value: string
}

export type SponsoredBadgeOptions = {
  label?: string;
  position?: SponsoredBadgePosition
}

export type SponsoredBadgePosition = "titleTop" | "containerTopLeft" | "none";

```


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

[User] Show me the implementation of product-summary-context/react/package.json from the product-summary-context VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "devDependencies": {
    "@types/node": "^11.13.4",
    "@types/query-string": "5",
    "@types/react": "^16.8.13",
    "vtex.product-group-context": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-group-context@0.1.0/public/@types/vtex.product-group-context",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.111.0/public/@types/vtex.render-runtime"
  },
  "dependencies": {
    "query-string": "5",
    "ramda": "^0.26.1"
  },
  "version": "0.13.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 product-summary-context/react/ProductSummaryContext.tsx from the product-summary-context VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useReducer, useEffect, PropsWithChildren } from 'react'
import { createContext, useContext } from 'react'
import querystring from 'query-string'
import { ProductGroupContext } from 'vtex.product-group-context'

import { Product, SingleSKU, SKU, SponsoredBadgeOptions, State } from './ProductSummaryTypes'

const { useProductGroup } = ProductGroupContext

const ProductSummaryContext = createContext<State | undefined>(undefined)
const ProductDispatchContext = createContext<Dispatch | undefined>(undefined)

type Dispatch = (action: Action) => void

type SetProductAction = {
  type: 'SET_PRODUCT',
  args: {
    product: Product
    selectedItem?: SingleSKU
  }
}

type SetProductQueryAction = {
  type: 'SET_PRODUCT_QUERY',
  args: {
    query: string
  }
}

type SetHoverAction = {
  type: 'SET_HOVER'
  args: {
    isHovering: boolean
  }
}

type SetLoadingAction = {
  type: 'SET_LOADING'
  args: {
    isLoading: boolean
  }
}

type SetPriceLoadingAction = {
  type: 'SET_PRICE_LOADING'
  args: {
    isPriceLoading: boolean
  }
}

type SetProductQuantity = {
  type: 'SET_QUANTITY'
  args: {
    quantity: number
  }
}

type SetInView = {
  type: 'SET_IN_VIEW'
  args: {
    inView: boolean
  }
}

type SetPosition = {
  type: 'SET_POSITION'
  args: {
    position: number
  }
}

type Action =
  | SetProductAction
  | SetHoverAction
  | SetLoadingAction
  | SetPriceLoadingAction
  | SetProductQuantity
  | SetProductQueryAction
  | SetInView
  | SetPosition

export function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_PRODUCT': {
      const product = action.args.product
      return {
        ...state,
        product: product,
        //TODO: STOP USING PRODUCT.SKU https://app.clubhouse.io/vtex/story/18547/productsummarycontext-refactor
        selectedItem: action.args.selectedItem ?? product.sku
      }
    }
    case 'SET_HOVER': {
      return {
        ...state,
        isHovering: action.args.isHovering
      }
    }
    case 'SET_LOADING': {
      return {
        ...state,
        isLoading: action.args.isLoading
      }
    }
    case 'SET_PRICE_LOADING': {
      return {
        ...state,
        isPriceLoading: action.args.isPriceLoading,
      }
    }
    case 'SET_QUANTITY': {
      return {
        ...state,
        selectedQuantity: action.args.quantity,
      }
    }
    case 'SET_PRODUCT_QUERY':
      return {
        ...state,
        query: action.args.query,
      }
    case 'SET_IN_VIEW':
      return {
        ...state,
        inView: action.args.inView,
      }
    case 'SET_POSITION':
      return {
        ...state,
        position: action.args.position,
      }

    default:
      return state
  }
}

interface BuildProductQueryParams {
  product: Product
}

const buildProductQuery = (({ product }: BuildProductQueryParams) => {
  const selectedProperties = product?.selectedProperties

  if (!selectedProperties) {
    return
  }

  const query = {}

  selectedProperties.forEach(property => {
    const {key, value} = property
    query[`property__${key}`] = value
  })

  return querystring.stringify(query)
})

interface ProviderProps {
  product: Product
  selectedItem?: SingleSKU
  isLoading?: boolean
  isPriceLoading?: boolean
  listName?: string
  sponsoredBadge?: SponsoredBadgeOptions
}

function ProductSummaryProvider({
  product,
  selectedItem,
  isLoading = false,
  isPriceLoading = false,
  listName = null,
  sponsoredBadge = {},
  children,
}: PropsWithChildren<ProviderProps>) {
  const initialState = {
    product,
    isHovering: false,
    isLoading,
    isPriceLoading,
    selectedItem: selectedItem ?? null,
    selectedQuantity: 1,
    listName,
    sponsoredBadge,
    query: buildProductQuery({ product }),
    inView: false,
    position: null,
  }

  const [state, dispatch] = useReducer(reducer, initialState)

  const productGroupContext = useProductGroup()

  useEffect(() => {
    if (!productGroupContext) {
      return
    }

    const { addItemToGroup } = productGroupContext
    const removeItemFromGroup = addItemToGroup(state.product, state.selectedItem ?? state.product.items[0])

    return () => removeItemFromGroup()
  }, [state.selectedItem, state.product])

  return (
    <ProductSummaryContext.Provider value={state}>
      <ProductDispatchContext.Provider value={dispatch}>
        {children}
      </ProductDispatchContext.Provider>
    </ProductSummaryContext.Provider>
  )
}

function useProductSummaryDispatch() {
  return useContext(ProductDispatchContext)
}

function useProductSummary() {
  return useContext(ProductSummaryContext)
}

export default {
  ProductSummaryProvider,
  useProductSummary,
  useProductSummaryDispatch,
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "store/product-identifier.productReference": "Referência",
  "store/product-identifier.productId": "ID",
  "store/product-identifier.skuEan": "EAN",
  "store/product-identifier.skuReferenceId": "Referência",
  "store/product-identifier.itemId": "Item ID",
  "admin/editor.product-identifier.title": "Identificador do Produto",
  "admin/editor.product-identifier.type.title": "Campo identificador",
  "admin/editor.product-identifier.type.itemId": "Item ID",
  "admin/editor.product-identifier.type.productReference": "Código de referência do produto",
  "admin/editor.product-identifier.type.productId": "Id do produto",
  "admin/editor.product-identifier.type.skuEan": "EAN do SKU",
  "admin/editor.product-identifier.type.skuReferenceId": "Código de referência do SKU",
  "admin/editor.product-identifier.label.title": "Texto identificador",
  "admin/editor.product-identifier.label.default": "Padrão",
  "admin/editor.product-identifier.label.custom": "Customizado",
  "admin/editor.product-identifier.label.hide": "Esconder",
  "admin/editor.product-identifier.customLabel.title": "Texto customizado"
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "store/product-identifier.productReference": "Reference",
  "store/product-identifier.productId": "ID",
  "store/product-identifier.skuEan": "EAN",
  "store/product-identifier.skuReferenceId": "Reference",
  "store/product-identifier.itemId": "Item ID",
  "admin/editor.product-identifier.title": "Product Identifier",
  "admin/editor.product-identifier.type.title": "Identifier Field",
  "admin/editor.product-identifier.type.itemId": "Item ID",
  "admin/editor.product-identifier.type.productReference": "Product Reference",
  "admin/editor.product-identifier.type.productId": "Product ID",
  "admin/editor.product-identifier.type.skuEan": "SKU EAN",
  "admin/editor.product-identifier.type.skuReferenceId": "SKU Reference ID",
  "admin/editor.product-identifier.label.title": "Label",
  "admin/editor.product-identifier.label.default": "Default",
  "admin/editor.product-identifier.label.custom": "Custom",
  "admin/editor.product-identifier.label.hide": "Hide",
  "admin/editor.product-identifier.customLabel.title": "Custom Label"
}

```


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

[User] Show me the implementation of product-identifier/messages/fr.json from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/product-identifier.productReference": "Référence",
  "store/product-identifier.productId": "ID",
  "store/product-identifier.skuEan": "EAN",
  "store/product-identifier.skuReferenceId": "Référence",
  "store/product-identifier.itemId": "ID de l’article",
  "admin/editor.product-identifier.title": "Identifiant du produit",
  "admin/editor.product-identifier.type.title": "Champ Identificateur",
  "admin/editor.product-identifier.type.itemId": "ID de l’article",
  "admin/editor.product-identifier.type.productReference": "Référence du produit",
  "admin/editor.product-identifier.type.productId": "ID du produit",
  "admin/editor.product-identifier.type.skuEan": "EAN de SKU",
  "admin/editor.product-identifier.type.skuReferenceId": "ID de référence de SKU",
  "admin/editor.product-identifier.label.title": "Étiquette",
  "admin/editor.product-identifier.label.default": "Par défaut",
  "admin/editor.product-identifier.label.custom": "Personnaliser",
  "admin/editor.product-identifier.label.hide": "Masquer",
  "admin/editor.product-identifier.customLabel.title": "Étiquette personnalisée"
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "store/product-identifier.productReference": "Reference",
  "store/product-identifier.productId": "ID",
  "store/product-identifier.skuEan": "EAN",
  "store/product-identifier.skuReferenceId": "Reference",
  "store/product-identifier.itemId": "Item ID",
  "admin/editor.product-identifier.title": "Product Identifier",
  "admin/editor.product-identifier.type.title": "Identifier field",
  "admin/editor.product-identifier.type.itemId": "Item ID",
  "admin/editor.product-identifier.type.productReference": "Product Reference",
  "admin/editor.product-identifier.type.productId": "Product ID",
  "admin/editor.product-identifier.type.skuEan": "SKU EAN",
  "admin/editor.product-identifier.type.skuReferenceId": "SKU Reference ID",
  "admin/editor.product-identifier.label.title": "Label",
  "admin/editor.product-identifier.label.default": "Default",
  "admin/editor.product-identifier.label.custom": "Custom",
  "admin/editor.product-identifier.label.hide": "Hide",
  "admin/editor.product-identifier.customLabel.title": "Custom Label"
}

```


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

[User] Show me the implementation of product-identifier/messages/id.json from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/product-identifier.productReference": "Referensi",
  "store/product-identifier.productId": "ID",
  "store/product-identifier.skuEan": "EAN",
  "store/product-identifier.skuReferenceId": "Referensi",
  "store/product-identifier.itemId": "ID Item",
  "admin/editor.product-identifier.title": "Pengenal Produk",
  "admin/editor.product-identifier.type.title": "Bidang Pengenal",
  "admin/editor.product-identifier.type.itemId": "ID Item",
  "admin/editor.product-identifier.type.productReference": "Referensi Produk",
  "admin/editor.product-identifier.type.productId": "ID Produk",
  "admin/editor.product-identifier.type.skuEan": "EAN SKU",
  "admin/editor.product-identifier.type.skuReferenceId": "ID Referensi SKU",
  "admin/editor.product-identifier.label.title": "Label",
  "admin/editor.product-identifier.label.default": "Default",
  "admin/editor.product-identifier.label.custom": "Kustom",
  "admin/editor.product-identifier.label.hide": "Sembunyikan",
  "admin/editor.product-identifier.customLabel.title": "Label Kustom"
}

```


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

[User] Show me the implementation of product-identifier/messages/th.json from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/product-identifier.productReference": "ข้อมูลอ้างอิง",
  "store/product-identifier.productId": "รหัส",
  "store/product-identifier.skuEan": "EAN",
  "store/product-identifier.skuReferenceId": "ข้อมูลอ้างอิง",
  "store/product-identifier.itemId": "รหัสสินค้า",
  "admin/editor.product-identifier.title": "รหัสผลิตภัณฑ์",
  "admin/editor.product-identifier.type.title": "ฟิลด์รหัส",
  "admin/editor.product-identifier.type.itemId": "รหัสสินค้า",
  "admin/editor.product-identifier.type.productReference": "ข้อมูลอ้างอิงผลิตภัณฑ์",
  "admin/editor.product-identifier.type.productId": "รหัสผลิตภัณฑ์",
  "admin/editor.product-identifier.type.skuEan": "SKU EAN",
  "admin/editor.product-identifier.type.skuReferenceId": "รหัสอ้างอิง SKU",
  "admin/editor.product-identifier.label.title": "ป้ายชื่อ",
  "admin/editor.product-identifier.label.default": "ค่าเริ่มต้น",
  "admin/editor.product-identifier.label.custom": "กำหนดเอง",
  "admin/editor.product-identifier.label.hide": "ซ่อน",
  "admin/editor.product-identifier.customLabel.title": "ป้ายที่กำหนดเอง"
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "store/product-identifier.productReference": "Referencia",
  "store/product-identifier.productId": "ID",
  "store/product-identifier.skuEan": "EAN",
  "store/product-identifier.skuReferenceId": "Referencia",
  "store/product-identifier.itemId": "Item ID",
  "admin/editor.product-identifier.title": "Identificador de Producto",
  "admin/editor.product-identifier.type.title": "Campo identificador",
  "admin/editor.product-identifier.type.itemId": "Item ID",
  "admin/editor.product-identifier.type.productReference": "Código de referencia del producto",
  "admin/editor.product-identifier.type.productId": "Id de producto",
  "admin/editor.product-identifier.type.skuEan": "EAN de SKU",
  "admin/editor.product-identifier.type.skuReferenceId": "Código de referencia de SKU",
  "admin/editor.product-identifier.label.title": "Texto identificador",
  "admin/editor.product-identifier.label.default": "Estándar",
  "admin/editor.product-identifier.label.custom": "Personalizado",
  "admin/editor.product-identifier.label.hide": "Ocultar",
  "admin/editor.product-identifier.customLabel.title": "Texto personalizado"
}

```


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

[User] Show me the implementation of product-identifier/messages/ar.json from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/product-identifier.productReference": "المرجع",
  "store/product-identifier.productId": "المعرّف",
  "store/product-identifier.skuEan": "رمز EAN",
  "store/product-identifier.skuReferenceId": "المرجع",
  "store/product-identifier.itemId": "معرّف العنصر",
  "admin/editor.product-identifier.title": "معرف المنتج",
  "admin/editor.product-identifier.type.title": "حقل المعرف",
  "admin/editor.product-identifier.type.itemId": "معرّف العنصر",
  "admin/editor.product-identifier.type.productReference": "مرجع المنتج",
  "admin/editor.product-identifier.type.productId": "معرّف المُنتج",
  "admin/editor.product-identifier.type.skuEan": "SKU EAN",
  "admin/editor.product-identifier.type.skuReferenceId": "معرف مرجع SKU",
  "admin/editor.product-identifier.label.title": "التسمية",
  "admin/editor.product-identifier.label.default": "العنوان الرئيسي",
  "admin/editor.product-identifier.label.custom": "مخصص",
  "admin/editor.product-identifier.label.hide": "إخفاء",
  "admin/editor.product-identifier.customLabel.title": "تسمية مخصصة"
}

```


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

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

[Assistant]
Here's the implementation:

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

# Product Identifier
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->

The Product Identifier app is responsible for showing a product identifier, such as a product reference, product ID, SKU EAN, or SKU reference.

![reference](https://user-images.githubusercontent.com/60782333/90151384-0abbd380-dd5d-11ea-9022-69ba4685e1d0.png)

## Configuration

1. Add the `vtex.product-identifier` app to your Store Theme's dependencies in the `manifest.json` file:

        ```json
        "dependencies": {
            "vtex.product-identifier": "0.x"
        }
        ```

2. Add `product-identifier.product` block as a child of `product-summary.shelf`.

        ```json
        "product-identifier.product": {
          "props": {
            "label": "default", //'default' | 'custom' | 'hide'
            "customLabel": "teste", // text if label is custom
            "idField": "skuReferenceId" //'itemId' | 'productId' | 'productReference' | 'skuEan' | 'skuReferenceId'
          }
        },
        ```

The `product-identifier` interface can also be configured in the [Site Editor](https://developers.vtex.com/docs/guides/store-framework-working-with-site-editor). You can choose to display the following identifiers:

- Product Reference
- Product ID
- SKU EAN
- SKU Reference ID
- Item ID

It's also possible to customize or hide the label text. In the following example, the "Reference" text was substituted by "Foo."

![foo](https://user-images.githubusercontent.com/60782333/90145130-004a0b80-dd56-11ea-9cbd-5ee621da4d69.png)

## Customization

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

| CSS Handles |
| ----------- |
| `product-identifier`           |
| `product-identifier__label`    |
| `product-identifier__separator`|
| `product-identifier__value`    |

## Contributors ✨

Thanks goes to these wonderful people:

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
  <tr>
    <td align="center"><a href="http://carafizi.com/"><img src="https://avatars3.githubusercontent.com/u/51974587?v=4" width="100px;" alt=""/><br /><sub><b>Gabriel Carafizi</b></sub></a><br /><a href="https://github.com/vtex-apps/product-identifier/commits?author=carafizi1" title="Code">💻</a></td>
  </tr>
</table>

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

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

```


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

[User] Show me the implementation of product-identifier/react/styles.css from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```css
.product-identifier {
}
.product-identifier__label {
}
.product-identifier__separator {
}
.product-identifier__value {
}

```


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

[User] Show me the implementation of product-identifier/react/ProductIdentifierSummary.tsx from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { path } from 'ramda'
import BaseProductIdentifier, {
  IdField,
} from './components/BaseProductIdentifier'
import {
  useProductSummary,
  ProductSummaryContext,
} from 'vtex.product-summary-context/ProductSummaryContext'

const allowedIdFields: Record<
  IdField,
  (contex: ProductSummaryContext) => string | null | undefined
> = {
  itemId: context => {
    return path(['selectedItem', 'itemId'], context)
  },
  productId: context => {
    return path(['product', 'productId'], context)
  },
  productReference: context => {
    return path(['product', 'productReference'], context)
  },
  skuEan: context => {
    // TODO: Add `selectedSku` to ProductSummaryContext instead of using `sku`
    return path(['product', 'sku', 'ean'], context)
  },
  skuReferenceId: context => {
    // TODO: Add `selectedSku` to ProductSummaryContext instead of using `sku`
    const refId =
      context &&
      context.product &&
      context.product.sku &&
      context.product.sku.referenceId
        ? context.product.sku.referenceId
        : null

    if (!refId) {
      return null
    }

    const { Value } = refId

    if (!Value) {
      return null
    }

    return Value
  },
}

const sanitizeId = (idField: string): IdField => {
  const valid = idField in allowedIdFields
  return valid ? (idField as IdField) : 'productId'
}

const ProductIdentifierSummary: StorefrontFunctionComponent<
  ProductIdentifierProductProps
> = ({ idField, customLabel, label }) => {
  const context = useProductSummary()

  const sanitizedId = sanitizeId(idField) as IdField

  if (
    (sanitizedId.indexOf('sku') === 0 && !context.product) ||
    !context.product.items
  ) {
    return null
  }

  if (sanitizedId.indexOf('product') === 0 && !context.product) {
    return null
  }

  const value = allowedIdFields[sanitizedId](context)

  return (
    <BaseProductIdentifier
      idField={idField}
      value={value}
      customLabel={customLabel}
      label={label}
    />
  )
}

interface ProductIdentifierProductProps {
  idField: IdField
  customLabel: string
  label: 'default' | 'custom' | 'hide'
}

ProductIdentifierSummary.schema = {
  title: 'admin/editor.product-identifier.title',
  type: 'object',
}

export default ProductIdentifierSummary

```


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

[User] Show me the implementation of product-identifier/react/ProductIdentifierProduct.tsx from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import useProduct, { ProductContext } from 'vtex.product-context/useProduct'
import { path } from 'ramda'
import BaseProductIdentifier, {
  IdField,
} from './components/BaseProductIdentifier'

const allowedIdFields: Record<
  IdField,
  (contex: ProductContext) => string | null | undefined
> = {
  itemId: context => {
    return path(['selectedItem', 'itemId'], context)
  },
  productId: context => {
    return path(['product', 'productId'], context)
  },
  productReference: context => {
    return path(['product', 'productReference'], context)
  },
  skuEan: context => {
    return path(['selectedItem', 'ean'], context)
  },
  skuReferenceId: context => {
    const refIds =
      context && context.selectedItem && context.selectedItem.referenceId
        ? context.selectedItem.referenceId
        : null
    if (!refIds) {
      return null
    }

    const refId = refIds.find(({ Key }) => Key === 'RefId')

    if (!refId) {
      return null
    }

    return refId.Value
  },
}

const sanitizeId = (idField: string): IdField => {
  const valid = idField in allowedIdFields
  return valid ? (idField as IdField) : 'productId'
}

const ProductIdentifierProduct: StorefrontFunctionComponent<
  ProductIdentifierProductProps
> = ({ idField, customLabel, label }) => {
  const context = useProduct()

  const sanitizedId = sanitizeId(idField) as IdField

  if (sanitizedId.indexOf('sku') === 0 && !context.selectedItem) {
    return null
  }

  if (sanitizedId.indexOf('product') === 0 && !context.product) {
    return null
  }

  const value = allowedIdFields[sanitizedId](context)

  return (
    <BaseProductIdentifier
      idField={idField}
      value={value}
      customLabel={customLabel}
      label={label}
    />
  )
}

interface ProductIdentifierProductProps {
  idField: IdField
  customLabel: string
  label: 'default' | 'custom' | 'hide'
}

ProductIdentifierProduct.schema = {
  title: 'admin/editor.product-identifier.title',
  type: 'object',
}

export default ProductIdentifierProduct

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test",
    "lint": "tsc --noEmit && eslint --ext ts,tsx ."
  },
  "dependencies": {
    "@vtex/css-handles": "^1.0.0",
    "classnames": "^2.2.6",
    "ramda": "^0.26.1",
    "react": "^16.8.3",
    "react-dom": "^16.8.3",
    "react-intl": "^2.7.2"
  },
  "devDependencies": {
    "@types/classnames": "^2.2.7",
    "@types/graphql": "^14.2.0",
    "@types/jest": "^24.0.11",
    "@types/node": "^11.13.0",
    "@types/prop-types": "^15.7.0",
    "@types/ramda": "^0.26.5",
    "@types/react": "^16.8.10",
    "@types/react-intl": "^2.3.17",
    "@vtex/test-tools": "^0.2.0",
    "apollo-client": "^2.5.1",
    "eslint": "^5.16.0",
    "eslint-config-vtex-react": "^4.1.0",
    "prettier": "^1.18.2",
    "tslint-eslint-rules": "^5.4.0",
    "typescript": "3.9.7"
  },
  "version": "0.5.1"
}

```


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

[User] Show me the implementation of product-identifier/store/interfaces.json from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "product-identifier": {
    "component": "*"
  },
  "product-identifier.product": {
    "component": "ProductIdentifierProduct",
    "preview": {
      "type": "grid",
      "height": 20
    },
    "content": {
      "dependencies": {
        "label": {
          "oneOf": [
            {
              "properties": {
                "label": {
                  "enum": ["default", "hide"]
                }
              }
            },
            {
              "properties": {
                "label": {
                  "enum": ["custom"]
                },
                "customLabel": {
                  "title": "admin/editor.product-identifier.customLabel.title",
                  "$ref": "app:vtex.native-types#/definitions/text"
                }
              }
            }
          ]
        }
      },
      "properties": {
        "idField": {
          "title": "admin/editor.product-identifier.type.title",
          "type": "string",
          "enum": ["productReference", "productId", "skuEan", "skuReferenceId", "itemId"],
          "enumNames": [
            "admin/editor.product-identifier.type.productReference",
            "admin/editor.product-identifier.type.productId",
            "admin/editor.product-identifier.type.skuEan",
            "admin/editor.product-identifier.type.skuReferenceId",
            "admin/editor.product-identifier.type.itemId"
          ],
          "default": "productReference"
        },
        "label": {
          "title": "admin/editor.product-identifier.label.title",
          "type": "string",
          "enum": ["default", "custom", "hide"],
          "enumNames": [
            "admin/editor.product-identifier.label.default",
            "admin/editor.product-identifier.label.custom",
            "admin/editor.product-identifier.label.hide"
          ],
          "default": "default"
        }
      }
    }
  },
  "product-identifier.summary": {
    "component": "ProductIdentifierSummary",
    "preview": {
      "type": "grid",
      "height": 20
    },
    "content": {
      "dependencies": {
        "label": {
          "oneOf": [
            {
              "properties": {
                "label": {
                  "enum": ["default", "hide"]
                }
              }
            },
            {
              "properties": {
                "label": {
                  "enum": ["custom"]
                },
                "customLabel": {
                  "title": "admin/editor.product-identifier.customLabel.title",
                  "$ref": "app:vtex.native-types#/definitions/text"
                }
              }
            }
          ]
        }
      },
      "properties": {
        "idField": {
          "title": "admin/editor.product-identifier.type.title",
          "type": "string",
          "enum": ["productReference", "productId", "skuEan", "skuReferenceId", "itemId"],
          "enumNames": [
            "admin/editor.product-identifier.type.productReference",
            "admin/editor.product-identifier.type.productId",
            "admin/editor.product-identifier.type.skuEan",
            "admin/editor.product-identifier.type.skuReferenceId",
            "admin/editor.product-identifier.type.itemId"
          ],
          "default": "productReference"
        },
        "label": {
          "title": "admin/editor.product-identifier.label.title",
          "type": "string",
          "enum": ["default", "custom", "hide"],
          "enumNames": [
            "admin/editor.product-identifier.label.default",
            "admin/editor.product-identifier.label.custom",
            "admin/editor.product-identifier.label.hide"
          ],
          "default": "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 product-identifier/react/typings/storefront.d.ts from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

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

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

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

```


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

[User] Show me the implementation of product-identifier/react/typings/vtex.product-context.d.ts from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.product-context/useProduct' {
  const useProduct: () => ProductContext
  export default useProduct

  export interface ProductContext {
    product: {
      productId: string
      productReference: string
    }
    selectedItem: {
      itemId: string
      ean: string
      referenceId: ReferenceId[]
    }
  }

  interface ReferenceId {
    Key: string
    Value: string
  }
}

```


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

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

[Assistant]
Here's the implementation:

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

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

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

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

  export const ExtensionPoint: ComponentType<ExtensionPointProps>

  interface ChildBlockProps {
    id: string
  }

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

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

```


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

[User] Show me the implementation of product-identifier/react/typings/vtex.native-types.d.ts from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.native-types' {
  import { ComponentType } from 'react'
  import { InjectedIntl, InjectedIntlProps } from 'react-intl'

  interface FormatIOMessageParams {
    id: string
    intl: InjectedIntl
  }

  export const formatIOMessage: (params: FormatIOMessageParams) => string

  interface IOMessageProps extends InjectedIntlProps {
    id: string
  }

  export const IOMessage: ComponentType<IOMessageProps>
}

```


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

[User] Show me the implementation of product-identifier/react/typings/css.d.ts from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

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

```


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

[User] Show me the implementation of product-identifier/react/typings/vtex.product-summary-context.d.ts from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.product-summary-context/ProductSummaryContext' {
  interface ProductSummaryContext {
    product: {
      productId: string
      productReference: string
      items: Item[]
      sku: Item
    }
  }

  interface Item {
    itemId: string
    referenceId: Reference
  }

  interface Reference {
    Value: string
  }

  export const useProductSummary = () => ProductSummaryContext
}

```


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

[User] Show me the implementation of product-identifier/react/typings/graphql.d.ts from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

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

  const value: DocumentNode
  export default value
}

```


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

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

[Assistant]
Here's the implementation:

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

  export const Input: ComponentType<InputProps>

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

```


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

[User] Show me the implementation of product-identifier/react/components/BaseProductIdentifier.tsx from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { IOMessage } from 'vtex.native-types'
import styles from '../styles.css'
import {
  defineMessages,
  FormattedMessage,
  injectIntl,
  InjectedIntlProps,
} from 'react-intl'

const messages = defineMessages({
  productReference: {
    id: 'store/product-identifier.productReference',
    defaultMessage: '',
  },
  productId: {
    id: 'store/product-identifier.productId',
    defaultMessage: '',
  },
  skuEan: {
    id: 'store/product-identifier.skuEan',
    defaultMessage: '',
  },
  skuReferenceId: {
    id: 'store/product-identifier.skuReferenceId',
    defaultMessage: '',
  },
  itemId: {
    id: 'store/product-identifier.itemId',
    defaultMessage: '',
  },
})

const ProductIdentifier: StorefrontFunctionComponent<
  ProductIdentifierProps & InjectedIntlProps
> = ({ idField, value, customLabel, label, intl }) => {
  return (
    <span
      className={`${styles['product-identifier']} ${styles['product-identifier']}--${idField} c-muted-1`}
    >
      {label !== 'hide' && (
        <span className={styles['product-identifier__label']}>
          {label === 'custom' && <IOMessage id={customLabel} intl={intl} />}
          {label === 'default' && (
            <FormattedMessage id={messages[idField].id} />
          )}
        </span>
      )}
      {label !== 'hide' && (
        <span className={styles['product-identifier__separator']}>: </span>
      )}
      <span className={styles['product-identifier__value']}>{value}</span>
    </span>
  )
}

export type IdField =
  | 'productReference'
  | 'productId'
  | 'skuEan'
  | 'skuReferenceId'
  | 'itemId'

interface ProductIdentifierProps {
  idField: IdField
  value: string | undefined | null
  customLabel: string
  label: 'default' | 'custom' | 'hide'
}

export default injectIntl(ProductIdentifier)

```


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

[User] Show me the implementation of product-identifier/react/modules/sanitize.tsx from the product-identifier VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { IdField } from '../components/BaseProductIdentifier'

const allowedIdFields = [
  'productId',
  'productReference',
  'skuEan',
  'skuReferenceId',
  'itemId',
]

export const sanitizeId = (idField: string): IdField => {
  const valid = idField in allowedIdFields
  return valid ? (idField as IdField) : 'productId'
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "store/cookiebot.declaration": "Cookie declaration"
}

```


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

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

[Assistant]
Here's the implementation:

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

# Cookiebot

<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->

This is a Cookiebot first party integration app. The [solution](https://www.cookiebot.com/) helps make your use of cookies and online tracking compliant.

![Cookie dialog](https://user-images.githubusercontent.com/284515/77015180-d92c1100-6952-11ea-97e6-f2b94b900399.png)

## Configuration

1. [Install](https://vtex.io/docs/recipes/development/installing-an-app/) the `vtex.cookiebot` app;
2. In your VTEX account's admin, open the **App** section and select the Cookiebot App box;
3. Fill in your **Domain Group ID**. You can find yours at the [Cookiebot Settings page](https://manage.cookiebot.com/en/manage);

![Cookiebot Domain ID](https://user-images.githubusercontent.com/284515/77793196-6acd0a00-7048-11ea-9de5-0da4eb1c1917.png)

4. On the [Settings page](https://manage.cookiebot.com/en/manage), make sure you use **Active Consent**;

<br/> <img width="500" src="https://user-images.githubusercontent.com/284515/78317146-de36b600-7537-11ea-885e-5b8a39d1db8c.png" />

5. On the [Cookies page](https://manage.cookiebot.com/en/cookies), run a Scan. After the scan is complete, make sure the following cookies are categorized as **Necessary**: `ASPXAUTH`, `checkout.vtex.com`, `CookieConsent`, `device`, `vtex_segment`, `vtex_session`, `VtexFingerPrint`, `VtexRCMacIdv7`, `VtexRCRequestCounter`, `VtexRCSessionIdv7`, `VtexWorkspace`;
6. Save your changes.

This pixel app also creates the page `/cookie-declaration` in your store with Cookiebot's Cookie declaration:

![Cookie declaration page](https://user-images.githubusercontent.com/284515/78317698-61a4d700-7539-11ea-9429-1a6275be1123.png)

You can edit the new page using the admin's Site Editor.

<!-- DOCS-IGNORE:start -->

## Contributors ✨

Thanks goes to these wonderful people:

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

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

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

```


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

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

[Assistant]
Here's the implementation:

```css
.declaration {
  max-width: 960px;
  margin: 0 auto;
}

.declarationHeader {}

```


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

[User] Show me the implementation of cookiebot/react/CookieDeclaration.tsx from the cookiebot VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { FC, useCallback } from 'react'
import { FormattedMessage } from 'react-intl'

import styles from './styles.css'

const CookieDeclaration: FC = () => {
  const ref = useCallback(node => {
    if (!node) {
      return
    }
    const cbid = window.__cookiebot_id
    const script = document.createElement('script')
    script.id = 'CookieDeclaration'
    script.type = 'text/javascript'
    script.async = true
    script.src = `https://consent.cookiebot.com/${cbid}/cd.js`
    node.appendChild(script)
  }, [])

  return (
    <div className={`${styles.declaration} lh-copy`}>
      <h1 className={`${styles.declarationHeader} heading-2`}>
        <FormattedMessage id="store/cookiebot.declaration" />
      </h1>
      <div ref={ref} id="CookiebotDeclaration" />
    </div>
  )
}

export default CookieDeclaration

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "dependencies": {
    "ramda": "^0.26.1"
  },
  "devDependencies": {
    "@apollo/react-testing": "^3.1.3",
    "@types/graphql": "^14.5.0",
    "@types/jest": "^24.9.0",
    "@types/node": "^13.1.8",
    "@types/ramda": "^0.26.5",
    "@types/react": "^16.9.19",
    "@types/react-intl": "^3.0.0",
    "@vtex/test-tools": "^3.0.1",
    "apollo-cache-inmemory": "^1.6.5",
    "apollo-client": "^2.6.8",
    "eslint": "^5.16.0",
    "eslint-config-vtex-react": "^4.1.0",
    "graphql": "^14.5.4",
    "prettier": "^1.18.2",
    "react-intl": "^3.11.0",
    "tslint-eslint-rules": "^5.4.0",
    "typescript": "3.9.7"
  },
  "version": "2.0.8"
}

```


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

[User] Show me the implementation of cookiebot/store/blocks.json from the cookiebot VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store.cookie-declaration": {
    "blocks": ["cookie-declaration"]
  }
}

```


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

[User] Show me the implementation of cookiebot/store/interfaces.json from the cookiebot VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store.cookie-declaration": {},
  "cookie-declaration": {
    "component": "CookieDeclaration"
  }
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "store.cookie-declaration": {
    "path": "/cookie-declaration"
  }
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "name": "Cookiebot",
  "headline": "Con unos pocos clics, configure y obtenga una vista previa de su propia declaración de cookies y diálogo de consentimiento.",
  "overview": "Cookiebot trae tres funciones principales completamente automáticas y fáciles de implementar: consentimiento, monitoreo y control de cookies.\nCookiebot permite el verdadero cumplimiento de las leyes de privacidad a través del intercambio de datos respetuoso y transparente, basado en el consentimiento entre los usuarios finales y los sitios web que visitan.",
  "features": [
    "Escaneo automatizado y declaración de cookies",
    "Banner de consentimiento de cookies",
    "Consentimiento masivo para varios dominios",
    "Soporte y detección automática de cualquier idioma",
    "Segmentación geográfica en tiempo real",
    "Estadísticas visuales sobre las elecciones de los visitantes de su sitio web"
  ],
  "additionalInformation": "Para usar el servicio, debe tener una cuenta de Cookiebot activa. Algunas funciones solo están disponibles para planes específicos.",
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "name": "Cookiebot",
  "headline": "Com apenas alguns cliques, configure e visualize sua própria declaração de cookie e caixa de diálogo de consentimento.",
  "overview": "O Cookiebot dá vida a três funções principais totalmente automáticas e fáceis de implementar: consentimento, monitoramento e controle de cookies.\nO Cookiebot permite a verdadeira conformidade com as leis de privacidade por meio de troca de dados respeitosa e transparente, com base no consentimento entre os usuários finais e os sites que eles visitam.",
  "features": [
    "Varredura e declaração automatizadas de cookies",
    "Banner de consentimento de cookies",
    "Consentimento em massa para vários domínios",
    "Suporte e detecção automática de qualquer idioma",
    "Segmentação geográfica em tempo real",
    "Estatísticas visuais sobre as escolhas dos visitantes do seu site"
  ],
  "additionalInformation": "Para utilizar o serviço é preciso ter uma conta ativa do Cookiebot. Algumas funcionalidades só estão disponíveis para planos específicos.",
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "name": "Cookiebot",
  "headline": "With a few clicks configure and preview your own cookie declaration and consent dialog.",
  "overview": "Cookiebot brings this vision to life with three, fully automatic core functions that are easy to implement: cookie consent, cookie monitoring and cookie control.\nCookiebot enables true compliance with privacy legislation through respectful and transparent data exchange, based on consent between end-users and the websites they visit.",
  "features": [
    "Automated cookie scan and declaration",
    "Cookie consent banner",
    "Bulk consent for multiple domains",
    "Support and auto-detect any language",
    "Real-time geographic targeting",
    "Visual statistics on the choices of your website visitors"
  ],
  "additionalInformation": "To use the service, you must have an active Cookiebot account. Some features are only available for specific plans.",
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


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

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

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.render-runtime' {
  export const canUseDOM: boolean
}

```


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

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

[Assistant]
Here's the implementation:

```typescript
interface Window extends Window {
  __cookiebot_id: string
  Cookiebot: Cookiebot
}

interface Cookiebot {
  runScripts: () => void
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "store/coupon.Apply": "Aplicar",
  "store/coupon.ApplyPromoCode": "Aplicar cupom de desconto",
  "store/coupon.PromoCode": "Cupom de Desconto",
  "store/coupon.PromoCodeLabel": "Código do cupom",
  "store/coupon.couponNotFound": "Cupom inválido.",
  "store/coupon.couponExpired": "Cupom expirado."
}

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "store/coupon.Apply": "Apply",
  "store/coupon.ApplyPromoCode": "Apply promo code",
  "store/coupon.PromoCode": "Promo Code",
  "store/coupon.PromoCodeLabel": "Promo code",
  "store/coupon.couponNotFound": "Invalid promo code.",
  "store/coupon.couponExpired": "This promo code has expired."
}

```


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

[User] Show me the implementation of checkout-coupon/messages/id.json from the checkout-coupon VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/coupon.Apply": "Terapkan",
  "store/coupon.ApplyPromoCode": "Masukkan kode voucher",
  "store/coupon.PromoCode": "Kode promo",
  "store/coupon.PromoCodeLabel": "Kode promo",
  "store/coupon.couponNotFound": "Kode promo tidak valid.",
  "store/coupon.couponExpired": "Kode promo ini tidak berlaku."
}
```


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

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

[Assistant]
Here's the implementation:

```json
{
  "store/coupon.Apply": "Aplicar",
  "store/coupon.ApplyPromoCode": "Aplicar cupón de descuento",
  "store/coupon.PromoCode": "Cupón de Descuento",
  "store/coupon.PromoCodeLabel": "Código de cupón",
  "store/coupon.couponNotFound": "Este cupón no es válido.",
  "store/coupon.couponExpired": "Este cupón ha expirado."
}

```


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

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

[Assistant]
Here's the implementation:

```markdown
# VTEX IO Base Component
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->

This demo component shows you how to make a simple yet complete VTEX IO component.

It shows a simple demonstration of the following features:

- Declaring a component interface in `store/interfaces.json`.
- Declaring a schema to receive props via Storefront.
- Using the `messages` feature to have localized strings.
- Using an NPM package like `react-intl`
- Using another VTEX IO App like `vtex.styleguide`.
- Using CSS Modules to make your component customizable via CSS on a store theme.
- Using tachyons tokens to quickly style your components.

## Contributors ✨

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

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

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

```


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

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

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test",
    "lint": "tsc --noEmit && eslint --ext ts,tsx ."
  },
  "dependencies": {
    "react": "^16.8.3",
    "react-dom": "^16.8.6",
    "react-intl": "^3.12.1"
  },
  "devDependencies": {
    "@apollo/react-testing": "^3.1.4",
    "@testing-library/dom": "^7.21.5",
    "@testing-library/jest-dom": "^5.11.1",
    "@types/graphql": "^14.2.0",
    "@types/jest": "^24.0.11",
    "@types/node": "^11.13.0",
    "@types/react": "^16.8.10",
    "@vtex/styleguide": "^9.125.0",
    "@vtex/test-tools": "^3.1.0",
    "vtex.order-coupon": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-coupon@0.7.1/public/@types/vtex.order-coupon",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.111.1/public/@types/vtex.render-runtime",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.125.0/public/@types/vtex.styleguide"
  },
  "version": "0.11.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 checkout-coupon/react/Coupon.css from the checkout-coupon VTEX app.

[Assistant]
Here's the implementation:

```css
.inputForm :global(.vtex-input) input {
  min-width: 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 checkout-coupon/react/Coupon.tsx from the checkout-coupon VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { Fragment, useState } from 'react'
import { defineMessages, FormattedMessage, useIntl } from 'react-intl'
import { ButtonPlain, InputButton, Tag } from 'vtex.styleguide'
import { OrderCoupon } from 'vtex.order-coupon'

import styles from './Coupon.css'

const { useOrderCoupon } = OrderCoupon

const NO_ERROR = ''

const messages = defineMessages({
  Apply: {
    id: 'store/coupon.Apply',
    defaultMessage: 'Apply',
  },
  ApplyPromoCode: {
    id: 'store/coupon.ApplyPromoCode',
    defaultMessage: 'Apply promo code',
  },
  couponNotFound: {
    id: 'store/coupon.couponNotFound',
    defaultMessage: `Invalid promo code.`,
  },
  couponExpired: {
    id: 'store/coupon.couponExpired',
    defaultMessage: `This promo code has expired.`,
  },
  PromoCode: {
    id: 'store/coupon.PromoCode',
    defaultMessage: 'Promo Code',
  },
  PromoCodeLabel: {
    id: 'store/coupon.PromoCode',
    defaultMessage: 'Promo code',
  },
})

const Coupon: React.FC = () => {
  const { coupon, insertCoupon } = useOrderCoupon()
  const [showPromoButton, setShowPromoButton] = useState(true)
  const [errorKey, setErrorKey] = useState(NO_ERROR)
  const [currentCoupon, setCurrentCoupon] = useState('')
  const [loadingCoupon, setLoadingCoupon] = useState(false)
  const toggle = () => setShowPromoButton(!showPromoButton)
  const intl = useIntl()

  const handleBlur = (evt: React.FocusEvent<HTMLInputElement>) => {
    evt.preventDefault()
    const newCoupon = evt.target.value.trim()

    if (!newCoupon) {
      setErrorKey(NO_ERROR)
      toggle()
    }
  }

  const handleCouponChange = (evt: React.ChangeEvent<HTMLInputElement>) => {
    evt.preventDefault()
    const newCoupon = evt.target.value.trim()

    setCurrentCoupon(newCoupon)
  }

  const resetCouponInput = () => {
    insertCoupon('')
    setCurrentCoupon('')
    setShowPromoButton(false)
  }

  const submitCoupon = (evt: React.FormEvent<HTMLFormElement>) => {
    evt.preventDefault()
    setErrorKey(NO_ERROR)
    insertCoupon(currentCoupon).then(result => {
      setLoadingCoupon(false)
      if (result.success) {
        setErrorKey(NO_ERROR)
        setShowPromoButton(true)
      } else {
        setErrorKey(result.errorKey)
      }
    })
    setLoadingCoupon(true)
  }

  return (
    <Fragment>
      {showPromoButton ? (
        <Fragment>
          {!coupon && (
            <div>
              <ButtonPlain id="add-coupon" onClick={toggle}>
                <FormattedMessage id="store/coupon.ApplyPromoCode" />
              </ButtonPlain>
            </div>
          )}

          {coupon && (
            <div>
              <div className="c-on-base t-small mb3">
                <FormattedMessage id="store/coupon.PromoCode" />
              </div>
              <Tag id="coupon-code" onClick={resetCouponInput}>
                {coupon}
              </Tag>
            </div>
          )}
        </Fragment>
      ) : (
        <form className={styles.inputForm} onSubmit={submitCoupon}>
          <InputButton
            id="coupon-input"
            button={intl.formatMessage({ id: 'store/coupon.Apply' })}
            isLoading={loadingCoupon}
            // eslint-disable-next-line jsx-a11y/no-autofocus
            autoFocus
            onChange={handleCouponChange}
            onBlur={handleBlur}
            placeholder=""
            errorMessage={
              errorKey
                ? intl.formatMessage(
                    messages[errorKey as keyof typeof messages]
                  )
                : NO_ERROR
            }
            label={<FormattedMessage id="store/coupon.PromoCodeLabel" />}
            value={currentCoupon}
          />
        </form>
      )}
    </Fragment>
  )
}

export default Coupon

```


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

[User] Show me the implementation of checkout-coupon/react/typings/css.d.ts from the checkout-coupon VTEX app.

[Assistant]
Here's the implementation:

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

```


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

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

[Assistant]
Here's the implementation:

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

declare module 'vtex.styleguide' {
  export const Input: ComponentType<InputProps>

  interface InputProps {
    [key: string]: any
  }

  export const Tag: ComponentType<any>

  export const InputButton: ComponentType<any>
}

```