id
stringlengths
12
53
messages
listlengths
3
3
code_adyen-platforms_d9be578f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/node/clients/masterdata/account.ts from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { MasterData } from '@vtex/api'\n\nconst DATA_ENTITY = 'account'\nconst ACCOUNT_SCHEMA_VERSION = 'account-dev@0.1'\nconst ACCOUNT_SCHEMA = {\n properties: {\n sellerId: {\n type: 'string',\n },\n accountHolderCode: {\n type: 'string',\n },\n accountCode: {\n type: 'string',\n unique: true,\n },\n status: {\n type: 'string',\n },\n },\n 'v-default-fields': [\n 'id',\n 'sellerId',\n 'accountHolderCode',\n 'accountCode',\n 'status',\n ],\n required: ['sellerId', 'accountHolderCode', 'accountCode', 'status'],\n 'v-indexed': ['sellerId', 'accountHolderCode'],\n 'v-cache': false,\n 'v-security': {\n allowGetAll: true,\n publicRead: ['sellerId', 'accountHolderCode', 'accountCode', 'status'],\n },\n}\n\ninterface IAdyenAccount {\n id: string\n sellerId: string\n accountHolderCode: string\n accountCode: string\n status: string\n}\n\nexport class Account extends MasterData {\n private checkSchema = async () => {\n return this.createOrUpdateSchema({\n dataEntity: DATA_ENTITY,\n schemaName: ACCOUNT_SCHEMA_VERSION,\n schemaBody: ACCOUNT_SCHEMA,\n }).catch(() => null)\n }\n\n public async save({\n data,\n }: {\n data: {\n sellerId: string\n accountHolderCode: string\n accountCode: string\n status: string\n }\n }) {\n await this.checkSchema()\n\n return this.createDocument({\n dataEntity: DATA_ENTITY,\n fields: data,\n schema: ACCOUNT_SCHEMA_VERSION,\n })\n }\n\n public async update(\n id: string,\n data: { [key: string]: string | boolean | number | null }\n ) {\n await this.checkSchema()\n\n return this.updatePartialDocument({\n id,\n dataEntity: DATA_ENTITY,\n fields: data,\n schema: ACCOUNT_SCHEMA_VERSION,\n })\n }\n\n public async find(data: { [key: string]: string }) {\n const [key] = Object.keys(data)\n\n return this.searchDocuments<IAdyenAccount>({\n dataEntity: DATA_ENTITY,\n fields: ['id', 'sellerId', 'accountHolderCode', 'accountCode', 'status'],\n pagination: { page: 1, pageSize: 100 },\n where: `${key}=${data[key]}`,\n schema: ACCOUNT_SCHEMA_VERSION,\n })\n }\n\n public async findBySellerId(data: string[]) {\n const where = `sellerId=${data.join(' OR sellerId=')}`\n\n return this.searchDocuments<IAdyenAccount>({\n dataEntity: DATA_ENTITY,\n fields: ['sellerId', 'accountHolderCode', 'accountCode', 'status'],\n pagination: { page: 1, pageSize: 100 },\n where,\n schema: ACCOUNT_SCHEMA_VERSION,\n })\n }\n\n public async all() {\n return this.searchDocumentsWithPaginationInfo<IAdyenAccount>({\n dataEntity: DATA_ENTITY,\n fields: ['sellerId', 'accountHolderCode', 'accountCode', 'status'],\n pagination: { page: 1, pageSize: 100 },\n schema: ACCOUNT_SCHEMA_VERSION,\n })\n }\n}\n\n```" } ]
code_adyen-platforms_e0f209e6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/node/clients/masterdata/onboarding.ts from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { MasterData } from '@vtex/api'\n\nconst DATA_ENTITY = 'onboarding'\nconst ONBOARDING_SCHEMA_VERSION = 'onboarding-dev@0.1'\nconst ONBOARDING_SCHEMA = {\n properties: {\n accountHolderCode: {\n type: 'string',\n unique: true,\n },\n urlToken: {\n type: ['null', 'string'],\n unique: true,\n },\n expirationTimestamp: {\n type: ['null', 'number'],\n },\n },\n 'v-default-fields': [\n 'id',\n 'accountHolderCode',\n 'urlToken',\n 'expirationTimestamp',\n ],\n required: ['accountHolderCode', 'urlToken', 'expirationTimestamp'],\n 'v-indexed': ['accountHolderCode', 'urlToken'],\n 'v-cache': false,\n 'v-security': {\n allowGetAll: true,\n publicRead: ['accountHolderCode', 'urlToken', 'expirationTimestamp'],\n },\n}\n\ninterface Ionboarding {\n id: string\n accountHolderCode: string\n urlToken: string\n expirationTimestamp: number\n}\n\nexport class Onboarding extends MasterData {\n private checkSchema = async () => {\n return this.createOrUpdateSchema({\n dataEntity: DATA_ENTITY,\n schemaName: ONBOARDING_SCHEMA_VERSION,\n schemaBody: ONBOARDING_SCHEMA,\n }).catch(() => null)\n }\n\n public async update(\n id: string,\n data: { [key: string]: string | boolean | number | null }\n ) {\n await this.checkSchema()\n\n return this.updatePartialDocument({\n id,\n dataEntity: DATA_ENTITY,\n fields: data,\n schema: ONBOARDING_SCHEMA_VERSION,\n })\n }\n\n public async create({\n data,\n }: {\n data: {\n accountHolderCode: string\n urlToken: string\n expirationTimestamp: number\n }\n }) {\n await this.checkSchema()\n\n return this.createDocument({\n dataEntity: DATA_ENTITY,\n fields: data,\n })\n }\n\n public async find(data: { [key: string]: string }) {\n const [key] = Object.keys(data)\n\n return this.searchDocuments<Ionboarding>({\n dataEntity: DATA_ENTITY,\n fields: ['id', 'accountHolderCode', 'urlToken', 'expirationTimestamp'],\n pagination: { page: 1, pageSize: 100 },\n schema: ONBOARDING_SCHEMA_VERSION,\n where: `${key}=${data[key]}`,\n })\n }\n}\n\n```" } ]
code_adyen-platforms_4f0db4b4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/node/api/resolvers/seller.ts from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { service } from '../../services'\n\nexport const sellerQueries = {\n sellers: async (_: any, __: any, ctx: Context) => {\n return service.seller.all({ ctx })\n },\n\n seller: async (_: any, data: any, ctx: Context) => {\n return service.seller.findOne(data.sellerId, ctx)\n },\n}\n\n```" } ]
code_adyen-platforms_a272e943
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/node/api/resolvers/adyen.ts from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { service } from '../../services'\n\nexport interface CreateAccountHolderDTO {\n accountHolderCode: string\n sellerId: string\n country: string\n legalBusinessName: string\n email: string\n legalEntity: string\n processingTier: number\n}\n\nexport interface AccountUpdateDTO {\n accountCode: string\n schedule: string\n}\n\nexport const adyenMutations = {\n createAccountHolder: async (\n _: unknown,\n data: CreateAccountHolderDTO,\n ctx: Context\n ) => {\n return service.adyen.createAccountHolder({ ctx, data })\n },\n closeAccountHolder: async (\n _: unknown,\n data: { accountHolderCode: string },\n ctx: Context\n ) => {\n return service.adyen.closeAccountHolder({ ctx, data })\n },\n updateAccount: async (_: unknown, data: AccountUpdateDTO, ctx: Context) => {\n return service.adyen.updateAccount({ ctx, data })\n },\n}\n\nexport const adyenQueries = {\n adyenAccountHolder: async (\n _: unknown,\n data: { sellerId: string },\n ctx: Context\n ) => {\n return service.adyen.getAccountHolder({ ctx, data })\n },\n}\n\n```" } ]
code_adyen-platforms_90472544
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/node/api/resolvers/onboarding.ts from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { service } from '../../services'\n\nexport const onboardingMutations = {\n onboardingComplete: async (\n _: unknown,\n data: { accountHolderCode: string },\n ctx: Context\n ) => {\n const {\n clients: { onboarding: onboardingClient },\n vtex: { logger },\n } = ctx\n\n try {\n const [onboarding] = (await onboardingClient.find(data)) ?? []\n\n if (!onboarding) return\n\n const { id, ...update } = onboarding\n\n await onboardingClient.update(id, {\n ...update,\n urlToken: null,\n expirationTimestamp: null,\n })\n } catch (error) {\n logger.error({\n error,\n message: 'adyenPlatform-completeOnboardingError',\n })\n }\n },\n refreshOnboarding: async (\n _: unknown,\n data: { accountHolderCode: string },\n ctx: Context\n ) => {\n return service.onboarding.refreshOnboarding(ctx, data)\n },\n}\n\nexport const onboardingQueries = {\n onboarding: async (\n _: unknown,\n { accountHolderCode }: { accountHolderCode: string },\n ctx: Context\n ) => {\n return service.onboarding.getOnboarding(ctx, accountHolderCode)\n },\n}\n\n```" } ]
code_adyen-platforms_26bee64f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/node/api/resolvers/index.ts from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { adyenMutations, adyenQueries } from './adyen'\nimport { onboardingMutations, onboardingQueries } from './onboarding'\nimport { sellerQueries } from './seller'\n\nexport const resolvers = {\n Mutation: {\n ...onboardingMutations,\n ...adyenMutations,\n },\n Query: { ...sellerQueries, ...onboardingQueries, ...adyenQueries },\n}\n\n```" } ]
code_adyen-platforms_233a64c5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/node/api/routes/account.ts from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport accountService from '../../services/accountService'\n\nconst account = async (ctx: Context) => {\n const { seller } = ctx.request.query\n\n if (!seller.length) {\n return\n }\n\n const sellerIds = typeof seller === 'string' ? [seller] : seller\n\n ctx.body = await accountService.findBySellerId({ ctx, sellerIds })\n}\n\nexport default account\n\n```" } ]
code_adyen-platforms_4d1d8c56
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/node/api/routes/onboarding.ts from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { service } from '../../services'\n\nconst startOnboarding = async (ctx: Context) => {\n const {\n request: {\n query: { token: urlToken },\n },\n vtex: { logger },\n } = ctx\n\n if (!urlToken || typeof urlToken !== 'string') return\n\n try {\n const onboardingUrl = await service.onboarding.getOnboardingUrl(\n ctx,\n urlToken\n )\n\n if (!onboardingUrl) return\n\n return ctx.redirect(onboardingUrl)\n } catch (error) {\n logger.error({\n error,\n message: 'adyenPlatforms-startOnboardingError',\n })\n\n // displays specific message (e.g \"Link has expired\") instead of generic \"Not Found\" when accessing expired/invalid onboarding page\n ctx.response.message = error.response?.data?.message ?? error.message\n }\n}\n\nexport default startOnboarding\n\n```" } ]
code_adyen-platforms_575dc755
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/node/api/routes/index.ts from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport account from './account'\nimport startOnboarding from './onboarding'\n\nexport const routes = {\n account: [account],\n onboarding: [startOnboarding],\n}\n\n```" } ]
code_adyen-platforms_67e67527
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/context/StateContext.tsx from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst initialState = {\n onboarding: null,\n seller: null,\n adyenAccountHolder: null,\n setContextState: () => {},\n}\n\nexport const StateContext = React.createContext(initialState as any)\n\n```" } ]
code_adyen-platforms_f2848166
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/typings/graphql.d.ts from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_adyen-platforms_f95f642f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/components/Settings.tsx from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useEffect, useState } from 'react'\nimport { Box, Text, Card, Input, Button, toast } from '@vtex/admin-ui'\nimport { useMutation, useQuery } from 'react-apollo'\n\nimport SaveAppSettings from '../graphql/SaveAppSettings.graphql'\nimport AppSettings from '../graphql/AppSettings.graphql'\n\nconst Settings: FC<any> = () => {\n const [settingsState, setSettingsState] = useState({\n apiKey: '',\n productionAPI: '',\n onboardingRedirectUrl: '',\n })\n\n const { data: settings } = useQuery(AppSettings, {\n variables: {\n version: process.env.VTEX_APP_VERSION,\n },\n ssr: false,\n })\n\n useEffect(() => {\n if (!settings?.appSettings?.message) return\n\n const parsedSettings = JSON.parse(settings.appSettings.message)\n\n setSettingsState(parsedSettings)\n }, [settings])\n\n const [saveSettings] = useMutation(SaveAppSettings)\n\n const [settingsLoading, setSettingsLoading] = useState(false)\n const handleSaveSettings = async () => {\n setSettingsLoading(true)\n\n try {\n await saveSettings({\n variables: {\n version: process.env.VTEX_APP_VERSION,\n settings: JSON.stringify(settingsState),\n },\n })\n } catch (err) {\n console.error(err)\n toast.dispatch({\n type: 'error',\n message: 'Error saving app settings',\n })\n\n setSettingsLoading(false)\n\n return\n }\n\n toast.dispatch({\n type: 'success',\n message: 'App settings saved',\n })\n setSettingsLoading(false)\n }\n\n return (\n <Card csx={{ marginTop: 2 }}>\n <Text variant=\"subtitle\">Adyen for Platforms configuration settings</Text>\n <Box csx={{ marginTop: 9, width: '50%' }}>\n <Input\n id=\"apiKey\"\n label=\"API Key\"\n helperText=\"Enter your Adyen for Platforms API Key\"\n value={settingsState.apiKey}\n onChange={(e: React.FormEvent<HTMLInputElement>) =>\n setSettingsState({\n ...settingsState,\n apiKey: e.currentTarget.value,\n })\n }\n />\n <Input\n id=\"liveEndpoint\"\n label=\"Production API Endpoint\"\n helperText=\"Enter your Adyen for Platforms production API endpoint\"\n value={settingsState.productionAPI}\n onChange={(e: React.FormEvent<HTMLInputElement>) =>\n setSettingsState({\n ...settingsState,\n productionAPI: e.currentTarget.value,\n })\n }\n />\n <Input\n id=\"redirectUrl\"\n label=\"Completed Onboarding Redirect URL\"\n helperText=\"After a seller has completed the Adyen onboarding process, you can choose to redirect them to a custom URL. Complete URL must be entered, for example: https://www.my-store.com/onboard-complete\"\n value={settingsState.onboardingRedirectUrl}\n onChange={(e: React.FormEvent<HTMLInputElement>) =>\n setSettingsState({\n ...settingsState,\n onboardingRedirectUrl: e.currentTarget.value,\n })\n }\n />\n </Box>\n <Box csx={{ marginTop: '20px' }}>\n <Button\n onClick={() => handleSaveSettings()}\n loading={settingsLoading}\n disabled={!settingsState.apiKey}\n >\n Save\n </Button>\n </Box>\n </Card>\n )\n}\n\nexport default Settings\n\n```" } ]
code_adyen-platforms_b3bc2bb0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/components/sellerDetailTitle.tsx from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useContext } from 'react'\nimport { PageHeader } from '@vtex/admin-ui'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport { StateContext } from '../context/StateContext'\n\nconst SellerDetailTitle: FC<any> = () => {\n const { navigate } = useRuntime()\n const { seller } = useContext(StateContext)\n\n if (!seller) return null\n\n return (\n <PageHeader\n csx={{ marginBottom: '20px' }}\n onPopNavigation={() =>\n navigate({\n page: `admin.app.adyen-menu`,\n })\n }\n >\n <PageHeader.Title>{seller.name}</PageHeader.Title>\n </PageHeader>\n )\n}\n\nexport default SellerDetailTitle\n\n```" } ]
code_adyen-platforms_db289cfe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/components/sellerCloseAccountModal.tsx from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable import/order */\nimport React, { useState } from 'react'\nimport type { FC } from 'react'\n\nimport {\n Set,\n Text,\n ModalDisclosure,\n Button,\n StatelessModal,\n ModalButton,\n toast,\n useModalState,\n Alert,\n IconWarningColorful,\n} from '@vtex/admin-ui'\nimport { useMutation } from 'react-apollo'\n\nimport CLOSE_ACCOUNT_HOLDER from '../graphql/CloseAccountHolder.graphql'\nimport { StateContext } from '../context/StateContext'\n\nconst SellerCloseAccountModal: FC<any> = ({ adyenAccountHolder }) => {\n const [isLoading, setIsLoading] = useState(false)\n const [deleteAccountHolder] = useMutation(CLOSE_ACCOUNT_HOLDER)\n const publishModal = useModalState()\n\n const handleClose = async (setContextState: any) => {\n setIsLoading(true)\n try {\n await deleteAccountHolder({\n variables: {\n accountHolderCode: adyenAccountHolder.accountHolderCode,\n },\n })\n } catch (error) {\n console.error(error)\n }\n\n setIsLoading(false)\n\n toast.dispatch({\n type: 'success',\n message: 'Adyen account deleted',\n })\n\n adyenAccountHolder.accountHolderStatus.status = 'Closed'\n setContextState({ adyenAccountHolder })\n\n publishModal.hide()\n }\n\n return (\n <StateContext.Consumer>\n {({ setContextState }) => (\n <Set spacing={3}>\n <ModalDisclosure state={publishModal}>\n <Button\n disabled={\n adyenAccountHolder.accountHolderStatus?.status === 'Closed'\n }\n variant=\"danger\"\n >\n Close Account\n </Button>\n </ModalDisclosure>\n <StatelessModal\n aria-label=\"Close Adyen account modal\"\n state={publishModal}\n size=\"regular\"\n hideOnClickOutside={false}\n >\n <StatelessModal.Header title=\"Close Adyen Account\" />\n <StatelessModal.Content>\n <Text>Close the Adyen account associated with this seller.</Text>\n <Alert\n csx={{ marginTop: 6 }}\n type=\"warning\"\n icon={<IconWarningColorful />}\n visible\n >\n This action cannot be undone. This account will no longer be\n able to process payments or receive payouts.\n </Alert>\n </StatelessModal.Content>\n <StatelessModal.Footer>\n <ModalButton closeModalOnClick variant=\"secondary\">\n Cancel\n </ModalButton>\n <ModalButton\n loading={isLoading}\n disabled={isLoading}\n variant=\"danger\"\n onClick={async () => handleClose(setContextState)}\n >\n Close\n </ModalButton>\n </StatelessModal.Footer>\n </StatelessModal>\n </Set>\n )}\n </StateContext.Consumer>\n )\n}\n\nexport default SellerCloseAccountModal\n\n```" } ]
code_adyen-platforms_d35f7944
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/components/sellerOnboarding.tsx from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable import/order */\nimport React, { useContext, useEffect, useState } from 'react'\nimport type { FC } from 'react'\n\nimport {\n Box,\n Set,\n Heading,\n Columns,\n Paragraph,\n Button,\n Tooltip,\n IconDuplicate,\n Input,\n toast,\n} from '@vtex/admin-ui'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport SellerOnboardingModal from './sellerOnboardingModal'\nimport { useMutation } from 'react-apollo'\nimport REFRESH_ONBOARDING from '../graphql/RefreshOnboarding.graphql'\nimport { StateContext } from '../context/StateContext'\n\nconst SellerOnboarding: FC<any> = () => {\n const { seller, adyenAccountHolder, onboarding } = useContext(StateContext)\n\n const [onboardUrl, setOnboardUrl] = useState('')\n const [isLoading, setIsLoading] = useState(false)\n const { workspace, binding, production } = useRuntime()\n const [refreshOnboarding] = useMutation(REFRESH_ONBOARDING)\n const { urlToken } = onboarding || {}\n\n useEffect(() => {\n if (urlToken) {\n setOnboardUrl(\n `https://${production ? '' : `${workspace}--`}${\n binding?.canonicalBaseAddress.split('/')[0]\n }/_v/api/adyen-platforms/v0/onboarding?token=${urlToken}`\n )\n }\n }, [\n binding?.canonicalBaseAddress,\n urlToken,\n onboardUrl,\n production,\n workspace,\n ])\n\n const handleRefresh = async (setContextState: any) => {\n setIsLoading(true)\n\n try {\n const response = await refreshOnboarding({\n variables: {\n accountHolderCode: adyenAccountHolder.accountHolderCode,\n },\n })\n\n setContextState({ onboarding: response.data.refreshOnboarding })\n } catch (error) {\n console.error(error)\n setIsLoading(false)\n\n return\n }\n\n toast.dispatch({\n type: 'success',\n message: 'Onboarding link created',\n })\n\n setIsLoading(false)\n }\n\n const copyText = () => {\n navigator.clipboard.writeText(onboardUrl)\n\n toast.dispatch({\n type: 'success',\n message: 'Copied to clipboard',\n })\n }\n\n const isActive =\n adyenAccountHolder &&\n adyenAccountHolder.accountHolderStatus?.status !== 'Closed'\n\n return (\n <Columns spacing={1}>\n <Columns.Item>\n <Box>\n <Set orientation=\"vertical\" spacing={3} fluid>\n <Heading>Onboarding</Heading>\n <Paragraph csx={{ width: '60%' }}>\n Create a new account and provide the generated link to the account\n holder.\n </Paragraph>\n <Set>\n <SellerOnboardingModal seller={seller} disabled={isActive} />\n {isActive && (\n <StateContext.Consumer>\n {({ setContextState }) => (\n <Button\n variant=\"primary\"\n loading={isLoading}\n disabled={\n adyenAccountHolder.accountHolderStatus?.status !==\n 'Active'\n }\n onClick={() => handleRefresh(setContextState)}\n >\n Create New Link\n </Button>\n )}\n </StateContext.Consumer>\n )}\n </Set>\n {onboardUrl && (\n <Box csx={{ maxWidth: '70%' }}>\n <Input\n id=\"1\"\n label=\"Onboarding Link\"\n value={onboardUrl}\n disabled\n buttonElements={\n <Tooltip label=\"Copy link\" placement=\"bottom\">\n <Button\n csx={{ height: '100%' }}\n onClick={() => copyText()}\n icon={<IconDuplicate />}\n disabled={!onboardUrl}\n variant=\"tertiary\"\n />\n </Tooltip>\n }\n />\n </Box>\n )}\n </Set>\n </Box>\n </Columns.Item>\n </Columns>\n )\n}\n\nexport default SellerOnboarding\n\n```" } ]
code_adyen-platforms_d2336fff
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/components/sellerAccountDetails.tsx from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useContext } from 'react'\nimport { Set, Columns, Heading, Text, Box } from '@vtex/admin-ui'\n\nimport SellerCloseAccountModal from './sellerCloseAccountModal'\nimport { StateContext } from '../context/StateContext'\n\nconst SellerAccountDetails: FC<any> = () => {\n const { adyenAccountHolder } = useContext(StateContext)\n\n if (!adyenAccountHolder?.accountHolderCode) return null\n\n return (\n <Columns spacing={1}>\n <Columns.Item>\n <Box>\n <Set orientation=\"vertical\" spacing={3}>\n <Heading>Account Details</Heading>\n <Set spacing={8}>\n <Box>\n <Set orientation=\"vertical\">\n <Text variant=\"subtitle\">Account Holder Code</Text>\n <Text>{`${adyenAccountHolder.accountHolderCode}`}</Text>\n </Set>\n </Box>\n <Box>\n <Set orientation=\"vertical\">\n <Text variant=\"subtitle\">Account Status</Text>\n <Text>\n {`${adyenAccountHolder.accountHolderStatus?.status || '-'}`}\n </Text>\n </Set>\n </Box>\n <Box>\n <Set orientation=\"vertical\">\n <Text variant=\"subtitle\">Account Email</Text>\n <Text>\n {`${adyenAccountHolder.accountHolderDetails?.email}`}\n </Text>\n </Set>\n </Box>\n </Set>\n </Set>\n <Box csx={{ marginTop: 6 }}>\n <SellerCloseAccountModal adyenAccountHolder={adyenAccountHolder} />\n </Box>\n </Box>\n </Columns.Item>\n </Columns>\n )\n}\n\nexport default SellerAccountDetails\n\n```" } ]
code_adyen-platforms_732733db
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/components/sellerPayouts.tsx from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useContext, useState, useEffect } from 'react'\nimport { useMutation } from 'react-apollo'\nimport {\n Box,\n Set,\n Heading,\n useSelectState,\n Columns,\n Paragraph,\n Select,\n Button,\n toast,\n} from '@vtex/admin-ui'\n\nimport UPDATE_ACCOUNT from '../graphql/UpdateAccount.graphql'\nimport { StateContext } from '../context/StateContext'\n\nconst SCHEDULE_OPTIONS = [\n {\n label: 'Daily',\n value: 'DAILY',\n description: 'Every day at midnight (00:00:00 CET).',\n },\n {\n label: 'Monthly',\n value: 'MONTHLY',\n description: 'Monthly at midnight (00:00:00 CET).',\n },\n {\n label: 'Weekly',\n value: 'WEEKLY',\n description: 'Weekly at midnight (00:00:00 CET).',\n },\n {\n label: 'Twice Weekly',\n value: 'WEEKLY_ON_TUE_FRI_MIDNIGHT',\n description: 'Weekly every Tuesday and Friday at midnight (00:00:00 CET).',\n },\n {\n label: 'Bimonthly',\n value: 'BIWEEKLY_ON_1ST_AND_15TH_AT_MIDNIGHT',\n description: 'Monthly on the 1st and 15th at midnight (00:00:00 CET).',\n },\n]\n\nconst SellerPayouts: FC<any> = () => {\n const { adyenAccountHolder } = useContext(StateContext)\n const [isLoading, setIsLoading] = useState(false)\n\n const [updateAccount] = useMutation(UPDATE_ACCOUNT)\n const [account] = adyenAccountHolder?.accounts || []\n\n const state = useSelectState({\n items: SCHEDULE_OPTIONS,\n itemToString: (item: any) => item.label,\n initialSelectedItem: SCHEDULE_OPTIONS[0],\n })\n\n useEffect(() => {\n if (!account?.payoutSchedule.schedule) {\n return\n }\n\n const selectedItem: any =\n SCHEDULE_OPTIONS.find(\n i => i.value === account?.payoutSchedule.schedule\n ) ?? SCHEDULE_OPTIONS[0]\n\n state.selectItem(selectedItem)\n }, [account?.payoutSchedule.schedule])\n\n const handleUpdate = async (setContextState: any) => {\n setIsLoading(true)\n\n try {\n const response = await updateAccount({\n variables: {\n accountCode: account.accountCode,\n schedule: state.selectedItem?.value,\n },\n })\n\n account.payoutSchedule.schedule = response.data.updateAccount.schedule\n setContextState({ adyenAccountHolder })\n } catch (err) {\n setIsLoading(false)\n\n toast.dispatch({\n type: 'error',\n message: 'Unable to update payout schedule',\n })\n\n return\n }\n\n setIsLoading(false)\n toast.dispatch({\n type: 'success',\n message: 'Payout schedule updated',\n })\n }\n\n return (\n <StateContext.Consumer>\n {({ setContextState }) => (\n <Columns spacing={1}>\n <Columns.Item>\n <Box>\n <Set orientation=\"vertical\" spacing={3} fluid>\n <Heading>Payouts</Heading>\n <Paragraph csx={{ width: '60%' }}>\n Set seller payout schedule.\n </Paragraph>\n <Set spacing={3}>\n <Select\n items={SCHEDULE_OPTIONS}\n state={state}\n label=\"Schedule\"\n renderItem={(item: any) => item.label}\n />\n <Paragraph csx={{ width: '60%' }}>\n {state.selectedItem?.description}\n </Paragraph>\n </Set>\n </Set>\n </Box>\n <Button\n loading={isLoading}\n disabled={!adyenAccountHolder}\n variant=\"primary\"\n csx={{ marginTop: '20px' }}\n onClick={() => handleUpdate(setContextState)}\n >\n Save\n </Button>\n </Columns.Item>\n </Columns>\n )}\n </StateContext.Consumer>\n )\n}\n\nexport default SellerPayouts\n\n```" } ]
code_adyen-platforms_f3c2cac1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/components/sellerOnboardingModal.tsx from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable import/order */\nimport React, { useState } from 'react'\nimport type { FC } from 'react'\n\nimport {\n Box,\n Set,\n Text,\n Select,\n ModalDisclosure,\n Button,\n StatelessModal,\n ModalButton,\n Input,\n toast,\n useModalState,\n useSelectState,\n Alert,\n IconErrorColorful,\n} from '@vtex/admin-ui'\nimport { useMutation } from 'react-apollo'\nimport { StateContext } from '../context/StateContext'\n\nimport CREATE_ACCOUNT_HOLDER from '../graphql/CreateAccountHolder.graphql'\n\nconst SellerOnboardingModal: FC<any> = ({ seller, disabled }) => {\n const [legalBusinessName, setLegalBusinessName] = useState('')\n const [email, setEmail] = useState('')\n const [accountHolderCode, setAccountHolderCode] = useState(seller?.id)\n const [isLoading, setIsLoading] = useState(false)\n const [errors, setErrors] = useState<any[]>([])\n const [createAccountHolder] = useMutation(CREATE_ACCOUNT_HOLDER)\n const publishModal = useModalState()\n\n const countries = [{ id: 'US', label: 'United States' }]\n const legalEntities = [{ id: 'Business', label: 'Business' }]\n const processingTiers = [\n { id: 0, label: 'Tier 0' },\n { id: 1, label: 'Tier 1' },\n { id: 2, label: 'Tier 2' },\n { id: 3, label: 'Tier 3' },\n ]\n\n const countryState = useSelectState({\n items: countries,\n itemToString: (item: any) => item.label,\n initialSelectedItem: countries[0],\n })\n\n const legalEntityState = useSelectState({\n items: legalEntities,\n itemToString: (item: any) => item.label,\n initialSelectedItem: legalEntities[0],\n })\n\n const processingTierState = useSelectState({\n items: processingTiers,\n itemToString: (item: any) => item.label,\n initialSelectedItem: processingTiers[0],\n })\n\n const createAccount = async (setContextState: any) => {\n setErrors([])\n setIsLoading(true)\n let response = null\n\n try {\n response = await createAccountHolder({\n variables: {\n accountHolderCode,\n sellerId: seller.id,\n country: countryState.selectedItem?.id,\n legalBusinessName,\n email,\n legalEntity: legalEntityState.selectedItem?.id,\n processingTier: processingTierState.selectedItem?.id,\n },\n })\n } catch (error) {\n console.error(error)\n }\n\n setIsLoading(false)\n\n if (!response?.data) {\n return setErrors([{ errorDescription: 'Adyen account creation failed' }])\n }\n\n const { invalidFields, onboarding, adyenAccountHolder } =\n response.data.createAccountHolder\n\n if (invalidFields) {\n return setErrors(invalidFields)\n }\n\n setContextState({ onboarding, adyenAccountHolder })\n\n toast.dispatch({\n type: 'success',\n message: 'Adyen account created',\n })\n\n publishModal.hide()\n }\n\n return (\n <StateContext.Consumer>\n {({ setContextState }) => (\n <Set spacing={3}>\n <ModalDisclosure state={publishModal}>\n <Button disabled={disabled} variant=\"primary\">\n Create Adyen Account\n </Button>\n </ModalDisclosure>\n <StatelessModal\n aria-label=\"Create Adyen account modal\"\n state={publishModal}\n size=\"regular\"\n hideOnClickOutside={false}\n >\n <StatelessModal.Header title=\"Create Adyen Account\" />\n <StatelessModal.Content>\n <Text>\n Enter the required information to create an Adyen account for\n the seller.\n </Text>\n <Box csx={{ marginTop: '15px', marginBottom: '15px' }}>\n <Input\n id=\"accountHolderCode\"\n label=\"Adyen Account Holder Code\"\n helperText=\"A unique identifier used in the Adyen dashboard\"\n value={accountHolderCode}\n onChange={e => setAccountHolderCode(e.target.value)}\n />\n </Box>\n <Set orientation=\"vertical\" spacing={1}>\n <Select\n block\n items={countries}\n state={countryState}\n label=\"Country\"\n renderItem={(item: any) => item.label}\n />\n <Select\n block\n items={legalEntities}\n state={legalEntityState}\n label=\"Legal Entity Type\"\n renderItem={(item: any) => item.label}\n />\n <Select\n block\n items={processingTiers}\n state={processingTierState}\n label=\"Processing Tier\"\n renderItem={(item: any) => item.label}\n />\n </Set>\n <Input\n id=\"legalBusinessName\"\n label=\"Legal Business Name\"\n value={legalBusinessName}\n onChange={e => setLegalBusinessName(e.target.value)}\n />\n <Input\n id=\"email\"\n type=\"email\"\n label=\"Business Email\"\n value={email}\n onChange={e => setEmail(e.target.value)}\n />\n {errors.length > 0 && (\n <Alert\n csx={{ marginTop: '15px' }}\n type=\"error\"\n icon={<IconErrorColorful />}\n visible={errors.length > 0}\n >\n {errors.map((error, i) => (\n <div key={i}>{error.errorDescription}</div>\n ))}\n </Alert>\n )}\n </StatelessModal.Content>\n <StatelessModal.Footer>\n <ModalButton\n onClick={() => setErrors([])}\n closeModalOnClick\n variant=\"secondary\"\n >\n Cancel\n </ModalButton>\n <ModalButton\n loading={isLoading}\n disabled={isLoading}\n onClick={async () => createAccount(setContextState)}\n >\n Create\n </ModalButton>\n </StatelessModal.Footer>\n </StatelessModal>\n </Set>\n )}\n </StateContext.Consumer>\n )\n}\n\nexport default SellerOnboardingModal\n\n```" } ]
code_adyen-platforms_e4342267
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/UpdateAccount.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation updateAccount($accountCode: String!, $schedule: String!) {\n updateAccount(accountCode: $accountCode, schedule: $schedule)\n @context(provider: \"vtex.adyen-platforms\") {\n schedule\n }\n}\n\n```" } ]
code_adyen-platforms_11ff19e4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/Seller.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery Seller($sellerId: String) {\n seller(sellerId: $sellerId) {\n id\n name\n logo\n isActive\n fulfillmentEndpoint\n allowHybridPayments\n taxCode\n email\n description\n sellerCommissionConfiguration\n catalogSystemEndpoint\n isBetterScope\n sellerType\n availableSalesChannels {\n isSelected\n id\n name\n }\n CSCIdentification\n account\n channel\n salesChannel\n isVtex\n score\n exchangeReturnPolicy\n deliveryPolicy\n securityPrivacyPolicy\n fulfillmentSellerId\n trustPolicy\n }\n}\n\n```" } ]
code_adyen-platforms_5331eac2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/CloseAccountHolder.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation closeAccountHolder($accountHolderCode: String!) {\n closeAccountHolder(accountHolderCode: $accountHolderCode)\n @context(provider: \"vtex.adyen-platforms\") {\n urlToken\n }\n}\n\n```" } ]
code_adyen-platforms_461e0fce
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/OnboardingComplete.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation OnboardingComplete($accountHolderCode: String!) {\n onboardingComplete(accountHolderCode: $accountHolderCode) {\n accountHolderCode\n }\n}\n\n```" } ]
code_adyen-platforms_f91334ff
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/CreateAccountHolder.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation createAccountHolder(\n $accountHolderCode: String!\n $sellerId: String!\n $country: String!\n $legalBusinessName: String!\n $email: String!\n $legalEntity: String!\n $processingTier: Int!\n) {\n createAccountHolder(\n accountHolderCode: $accountHolderCode\n sellerId: $sellerId\n country: $country\n legalBusinessName: $legalBusinessName\n email: $email\n legalEntity: $legalEntity\n processingTier: $processingTier\n ) @context(provider: \"vtex.adyen-platforms\") {\n adyenAccountHolder {\n accountHolderCode\n accountHolderStatus {\n status\n processingState {\n disabled\n }\n payoutState {\n disabled\n }\n }\n accountHolderDetails {\n email\n }\n accounts {\n accountCode\n payoutSchedule {\n schedule\n }\n status\n }\n }\n onboarding {\n accountHolderCode\n urlToken\n }\n invalidFields {\n errorDescription\n }\n }\n}\n\n```" } ]
code_adyen-platforms_e79730d5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/RefreshOnboarding.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation RefreshOnboarding($accountHolderCode: String!) {\n refreshOnboarding(accountHolderCode: $accountHolderCode) {\n accountHolderCode\n urlToken\n }\n}\n\n```" } ]
code_adyen-platforms_5f4761fe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/Onboarding.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery Onboarding($accountHolderCode: String) {\n onboarding(accountHolderCode: $accountHolderCode) {\n accountHolderCode\n urlToken\n invalidFields {\n errorDescription\n }\n }\n}\n\n```" } ]
code_adyen-platforms_6559e1ec
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/AdyenAccountHolder.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery AdyenAccountHolder($sellerId: String) {\n adyenAccountHolder(sellerId: $sellerId) {\n accountHolderCode\n accountHolderStatus {\n status\n processingState {\n disabled\n }\n payoutState {\n disabled\n }\n }\n accountHolderDetails {\n email\n }\n accounts {\n accountCode\n payoutSchedule {\n schedule\n }\n status\n }\n }\n}\n\n```" } ]
code_adyen-platforms_cae2a215
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/SaveAppSettings.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation SaveAppSettings($version: String, $settings: String) {\n saveAppSettings(\n app: \"vtex.adyen-platforms\"\n version: $version\n settings: $settings\n ) @context(provider: \"vtex.apps-graphql\") {\n message\n }\n}\n\n```" } ]
code_adyen-platforms_d6caae36
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/Sellers.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery Sellers {\n sellers {\n id\n name\n logo\n isActive\n fulfillmentEndpoint\n allowHybridPayments\n taxCode\n email\n description\n sellerCommissionConfiguration\n catalogSystemEndpoint\n isBetterScope\n sellerType\n availableSalesChannels {\n isSelected\n id\n name\n }\n CSCIdentification\n account\n channel\n salesChannel\n isVtex\n score\n exchangeReturnPolicy\n deliveryPolicy\n securityPrivacyPolicy\n fulfillmentSellerId\n trustPolicy\n adyenAccount {\n sellerId\n accountCode\n status\n }\n }\n}\n\n```" } ]
code_adyen-platforms_d5e86d73
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of adyen-platforms/react/graphql/AppSettings.graphql from the adyen-platforms VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery AppSettings($version: String) {\n appSettings(app: \"vtex.adyen-platforms\", version: $version)\n @context(provider: \"vtex.apps-graphql\") {\n message\n }\n}\n\n```" } ]
code_twitter-meta-tags_f81ea135
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of twitter-meta-tags/docs/README.md from the twitter-meta-tags VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Twitter Meta Tags\n\nImplements **Twitter** meta tags to a store's product page.\n\n```" } ]
code_twitter-meta-tags_5885d8e6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of twitter-meta-tags/react/TwitterMetaTags.tsx from the twitter-meta-tags VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment, useContext } from 'react'\nimport { ProductContext } from 'vtex.product-context'\n// eslint-disable-next-line prettier/prettier\nimport type { RenderContext } from 'vtex.render-runtime'\nimport { canUseDOM, Helmet, useRuntime } from 'vtex.render-runtime'\n\ninterface MetaTag {\n property: string\n content: string\n}\n\nconst VTEX_STORE_APP = 'vtex.store'\n\nfunction TwitterMetaTags() {\n const productContext: ProductContext = useContext(ProductContext)\n const runtime: RenderContext = useRuntime()\n const { getSettings } = runtime\n const { includeTwitterMetaTags, twitterCard, twitterUsername } = getSettings(\n VTEX_STORE_APP\n )\n\n if (!productContext.product || !includeTwitterMetaTags) {\n return null\n }\n\n const {\n product: { productName, description },\n selectedItem: {\n images: [firstImage],\n },\n } = productContext\n\n\n const protocol = canUseDOM && window.location.protocol\n const hostname = canUseDOM && window.location.hostname\n const pathname = canUseDOM && window.location.pathname\n const url = `${protocol}://${hostname}${pathname}`\n\n const metaTags: MetaTag[] = [\n { property: 'twitter:card', content: twitterCard },\n { property: 'twitter:site', content: twitterUsername.startsWith('@') ? twitterUsername : `@${twitterUsername}` },\n { property: 'twitter:title', content: productName },\n { property: 'twitter:description', content: description },\n { property: 'twitter:image', content: firstImage.imageUrl },\n { property: 'twitter:url', content: url },\n ]\n\n return (\n <Fragment>\n <Helmet meta={metaTags} />\n </Fragment>\n )\n}\n\nexport default TwitterMetaTags\n\n```" } ]
code_twitter-meta-tags_ae0b75cb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of twitter-meta-tags/react/package.json from the twitter-meta-tags VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\",\n \"lint\": \"eslint --ext ts,tsx .\"\n },\n \"dependencies\": {\n \"react\": \"^16.8.3\",\n \"react-dom\": \"^16.8.3\",\n \"react-intl\": \"^2.7.2\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.4\",\n \"@types/classnames\": \"^2.2.7\",\n \"@types/graphql\": \"^14.2.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/prop-types\": \"^15.7.0\",\n \"@types/react\": \"^16.8.10\",\n \"@types/react-helmet\": \"^5.0.8\",\n \"@types/react-intl\": \"^2.3.17\",\n \"@vtex/test-tools\": \"^3.0.0\",\n \"apollo-client\": \"^2.5.1\",\n \"typescript\": \"3.9.7\"\n },\n \"version\": \"1.2.1\"\n}\n\n```" } ]
code_twitter-meta-tags_3755942f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of twitter-meta-tags/react/typings/vtex.product-context.d.ts from the twitter-meta-tags VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.product-context' {\n interface ProductContext {\n product: Product\n selectedItem: SKU\n }\n\n interface Product {\n productName: string\n description: string\n }\n\n interface SKU {\n images: Array<{\n imageUrl: string\n }>\n }\n\n export const ProductContext: Context<ProductContext>\n}\n\n```" } ]
code_twitter-meta-tags_7239e017
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of twitter-meta-tags/react/typings/vtex.render-runtime.d.ts from the twitter-meta-tags VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime' {\n export { Helmet } from 'react-helmet'\n\n export const canUseDOM: boolean\n\n export interface RenderContext {\n getSettings: (app: string) => AppSettings\n }\n\n export function useRuntime(): RenderContext\n}\n\ninterface AppSettings {\n includeTwitterMetaTags: boolean\n twitterCard: string\n twitterUsername: string\n}\n\n```" } ]
code_connector-adyen_702659c6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/messages/en.json from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/adyen.title\": \"Adyen\",\n \"admin/adyen.admin-menu-button\": \"Adyen\",\n \"admin/adyen.settings.adyenMerchantAccount.label\": \"Adyen Merchant Account\",\n \"admin/adyen.settings.adyenMerchantAccount.helpText\": \"Enter your Adyen Merchant Account\",\n \"admin/adyen.settings.adyenApiKey.label\": \"Adyen API Key\",\n \"admin/adyen.settings.adyenApiKey.helpText\": \"Enter your Adyen API key\",\n \"admin/adyen.settings.adyenWebhookUsername.label\": \"Adyen Webhook Username\",\n \"admin/adyen.settings.adyenWebhookUsername.helpText\": \"Enter your Adyen webhook user name\",\n \"admin/adyen.settings.adyenWebhookPassword.label\": \"Adyen Webhook Password\",\n \"admin/adyen.settings.adyenWebhookPassword.helpText\": \"Enter your Adyen webhook password\",\n \"admin/adyen.settings.vtexAppKey.label\": \"VTEX App Key\",\n \"admin/adyen.settings.vtexAppToken.label\": \"VTEX App Token\",\n \"admin/adyen.settings.vtexAppToken.helpText\": \"Enter a VTEX app key and token pair for this account. If you are configuring a marketplace-seller relationship, use a key and token that have permissions for all related accounts.\",\n \"admin/adyen.settings.productionAPI.label\": \"Adyen API Production Endpoint\",\n \"admin/adyen.settings.productionAPI.helpText\": \"Enter your Adyen API production endpoint\",\n \"admin/adyen.settings.adyenPlatforms.active\": \"Using Adyen for Platforms\",\n \"admin/adyen.settings.adyenPlatforms.inactive\": \"Not using Adyen for Platforms\",\n \"admin/adyen.settings.adyenPlatforms.helpText\": \"Activate to use Adyen for Platforms to processs split payouts. The Adyen for Platforms app must be installed\",\n \"admin/adyen.saveSettings.buttonText\": \"Save settings\",\n \"admin/adyen.saveSettings.success\": \"Settings have been saved\",\n \"admin/adyen.saveSettings.failure\": \"Error saving settings (see console for details)\",\n \"admin/adyen.settings.adyenProductionAPI.label\": \"Adyen Production API URI\",\n \"admin/adyen.settings.adyenProductionAPI.helpText\": \"Enter the Adyen production API URI. Ensure that it is in the form of http://{productionURI}.com\"\n}\n\n```" } ]
code_connector-adyen_16954383
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/messages/context.json from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/adyen.title\": \"admin/adyen.title\",\n \"admin/adyen.admin-menu-button\": \"admin/adyen.admin-menu-button\",\n \"admin/adyen.settings.adyenMerchantAccount.label\": \"admin/adyen.settings.adyenMerchantAccount.label\",\n \"admin/adyen.settings.adyenMerchantAccount.helpText\": \"admin/adyen.settings.adyenMerchantAccount.helpText\",\n \"admin/adyen.settings.adyenApiKey.label\": \"admin/adyen.settings.adyenApiKey.label\",\n \"admin/adyen.settings.adyenApiKey.helpText\": \"admin/adyen.settings.adyenApiKey.helpText\",\n \"admin/adyen.settings.adyenWebhookUsername.label\": \"admin/adyen.settings.adyenWebhookUsername.label\",\n \"admin/adyen.settings.adyenWebhookUsername.helpText\": \"admin/adyen.settings.adyenWebhookUsername.helpText\",\n \"admin/adyen.settings.adyenWebhookPassword.label\": \"admin/adyen.settings.adyenWebhookPassword.label\",\n \"admin/adyen.settings.adyenWebhookPassword.helpText\": \"admin/adyen.settings.adyenWebhookPassword.helpText\",\n \"admin/adyen.settings.vtexAppKey.label\": \"admin/adyen.settings.vtexAppKey.label\",\n \"admin/adyen.settings.vtexAppToken.label\": \"admin/adyen.settings.vtexAppToken.label\",\n \"admin/adyen.settings.vtexAppToken.helpText\": \"admin/adyen.settings.vtexAppToken.helpText\",\n \"admin/adyen.settings.productionAPI.label\": \"admin/adyen.settings.enableTaxCalculation.label\",\n \"admin/adyen.settings.productionAPI.helpText\": \"admin/adyen.settings.enableTaxCalculation.helpText\",\n \"admin/adyen.settings.adyenPlatforms.active\": \"admin/adyen.settings.adyenPlatforms.helpText\",\n \"admin/adyen.settings.adyenPlatforms.inactive\": \"admin/adyen.settings.adyenPlatforms.helpText\",\n \"admin/adyen.settings.adyenPlatforms.helpText\": \"admin/adyen.settings.adyenPlatforms.helpText\",\n \"admin/adyen.saveSettings.buttonText\": \"admin/adyen.saveSettings.buttonText\",\n \"admin/adyen.saveSettings.success\": \"admin/adyen.saveSettings.success\",\n \"admin/adyen.saveSettings.failure\": \"admin/adyen.saveSettings.failure\",\n \"admin/adyen.settings.adyenProductionAPI.label\": \"admin/adyen.settings.adyenProductionAPI.label\",\n \"admin/adyen.settings.adyenProductionAPI.helpText\": \"admin/adyen.settings.adyenProductionAPI.helpText\"\n}\n\n```" } ]
code_connector-adyen_2a17276d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/admin/navigation.json from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n[\n {\n \"section\": \"transactions\",\n \"subSection\": \"payments\",\n \"LMProductId\": \"6\",\n \"subSectionItems\": [\n {\n \"labelId\": \"admin/adyen.admin-menu-button\",\n \"path\": \"/admin/adyen\"\n }\n ],\n \"icon\": \"extensions-ic\"\n },\n {\n \"adminVersion\": 4,\n \"section\": \"storeSettings\",\n \"subSection\": \"payment\",\n \"LMProductId\": \"6\",\n \"subSectionItems\": [\n {\n \"labelId\": \"admin/adyen.admin-menu-button\",\n \"path\": \"/admin/adyen\"\n }\n ]\n }\n]\n\n```" } ]
code_connector-adyen_616bfaf0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/admin/routes.json from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin.app.adyen\": {\n \"around\": [\"layout\"],\n \"path\": \"/admin/app/adyen/\"\n },\n \"layout\": {\n \"component\": \"Admin\"\n }\n}\n\n```" } ]
code_connector-adyen_ac9e98f0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/docs/README.md from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/connector-adyen) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Adyen\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nThis app integrates Adyen with VTEX checkout.\n\n## Configuration\n\n### Adyen Setup\n\nBefore you can configure the VTEX Adyen connector, you will need to do the following setup in your Adyen merchant account:\n\n1. Generate Web Service API credentials.\n - Under the Developers tab, select `API credentials`\n - Select `Webservice`\n - Keep `Username` and `Password` somewhere safe\n - Generate a new API Key and store it somewhere safe. This can be regenerated if lost\n2. (Do Only Once) Send an email to Adyen support (suporte@adyen.com), requesting the permissions listed in the model below:\n - Subject: Setting VTEX web-service user permissions for {accountName}\n - Email Body: Adyen Support, I send this email to ask you to grant the necessary permissions to the user username@Company.companyname so that it can be used on the VTEX platform. Thank you in advance!\n3. In Merchant Settings, update the Capture Delay option to `manual`. This allows VTEX to handle payment capture timing.\n4. Create a Standard Notification Webhook\n - Use `https://{accountName}.myvtex.com/_v/api/connector-adyen/v0/hook` for the URL\n - Example: `https://mysampleshop.myvtex.com/_v/api/connector-adyen/v0/hook`\n - Make sure `Service Version` is `1`\n - Make sure the webhook is marked as `active`\n - Make sure `Method` is set to `JSON`\n - Create a `username` and `password` of your choice for the webhook events\n\n### Installing the App\n\n1. Install this app in the desired account using the CLI command `vtex install vtex.connector-adyen`.\n2. In your admin sidebar, search for `Payments` and select `Settings` under the `Payments` tab.\n3. Click the `Gateway Affiliations` tab and click the green plus sign to add a new affiliation.\n4. Select `Adyen Payments` from the **Others** list.\n5. Modify the `Affiliation name` if desired, choose an `Auto Settlement` behavior from the dropdown and then click `Save`. Leave `Application Key` and `Application Token` blank.\n6. Click the `Payment Conditions` tab and click the green plus sign to add a new payment condition.\n7. From the **Credit Card** list, click the card type you want to process using Adyen.\n8. In the `Process with affiliation` dropdown, choose `Adyen Payments` or the name of the affiliation that you created in step 6. Set the status to `Active` and click `Save`. Note that this will activate the payment method in checkout!\n9. Repeat steps 8 and 9 for each credit type to be processed with Adyen.\n10. In your admin sidebar, search for `Adyen`. This will bring you to the `Adyen` admin panel to configure the app settings.\n11. Complete the settings with the values from your Adyen setup, following the guide below.\n\n### App Configurations\n\n> ⚠️ _Only users with access to the **Payments** section in the VTEX admin (or assigned the **PCI Gateway** role in License Manager) will be able to configure the app._\n\n1. `Adyen Merchant Account` is the merchant account name.\n - Note: This is not the company name.\n2. `Adyen API Key` is the API key that is generated in Step 1 of `Adyen Setup`\n3. `Adyen Production API URI` is the Checkout API's URI.\n - This can be found in the Developer > API URLs tab in Adyen.\n - Example: `http://checkout-test.adyen.com`\n - Note: Please use http instead of https\n4. `Adyen Webhook Username` and `Adyen Webhook Password` is the Username/Password created in Step 4 of `Adyen Setup`\n5. `VTEX App Key/App Token` should be a VTEX application key that has the `Super Admin` role in your account and its associated token. Reference [this documentation](https://help.vtex.com/en/tutorial/application-keys--2iffYzlvvz4BDMr6WGUtet) for app key generation and configuration.\n\n- If you are running Adyen in a marketplace, make sure to grant this application key the same `Super Admin` role on all seller accounts as well. In other words, create the application key on the marketplace account, then go to the `Application Keys` admin panel on each seller account and click `+ Add` to grant the key permissions for that account.\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```" } ]
code_connector-adyen_c4cc9268
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/paymentProvider/configuration.json from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Adyen Payments\",\n \"implementsSplit\": true,\n \"usesAutoSettleOptions\": true,\n \"acceptSplitPartialRefund\": true,\n \"paymentMethods\": [\n {\n \"name\": \"Visa\",\n \"allowsSplit\": \"onAuthorize\"\n },\n {\n \"name\": \"American Express\",\n \"allowsSplit\": \"onAuthorize\"\n },\n {\n \"name\": \"Discover\",\n \"allowsSplit\": \"onAuthorize\"\n },\n {\n \"name\": \"Mastercard\",\n \"allowsSplit\": \"onAuthorize\"\n },\n {\n \"name\": \"JCB\",\n \"allowsSplit\": \"onAuthorize\"\n },\n {\n \"name\": \"Diners\",\n \"allowsSplit\": \"onAuthorize\"\n },\n {\n \"name\": \"Visa Electron\",\n \"allowsSplit\": \"onAuthorize\"\n },\n {\n \"name\": \"Maestro\",\n \"allowsSplit\": \"onAuthorize\"\n },\n {\n \"name\": \"Mastercard Debit\",\n \"allowsSplit\": \"onAuthorize\"\n }\n ]\n}\n\n```" } ]
code_connector-adyen_56fc0fb7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/routes.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/consistent-type-imports */\n\nimport { json } from 'co-body'\nimport {\n ApprovedAuthorization,\n AuthorizationRequest,\n FailedAuthorization,\n} from '@vtex/payment-provider'\n\nconst APP_ID = process.env.VTEX_APP_ID as string\n\nconst handleAdyenWebhook = async (ctx: Context) => {\n const {\n clients: { vbase, apps, provider },\n vtex: { logger },\n headers,\n req,\n } = ctx\n\n const settings = await apps.getAppSettings(APP_ID)\n\n const { webhookUsername, webhookPassword, vtexAppKey, vtexAppToken } =\n settings\n\n const b64auth = (headers.authorization ?? '').split(' ')[1] || ''\n const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':')\n\n if (login !== webhookUsername || password !== webhookPassword) {\n ctx.status = 401\n\n logger.error({\n message: 'Webhook-missingCredentials',\n })\n\n return\n }\n\n const eventData: AdyenHookNotification = await json(req)\n\n const {\n notificationItems: [\n {\n NotificationRequestItem: {\n merchantReference,\n eventCode,\n pspReference,\n success,\n reason,\n },\n },\n ],\n } = eventData\n\n logger.info({\n message: 'Webhook-received',\n data: { merchantReference, eventCode, pspReference, success, reason },\n })\n\n let authRequest: AuthorizationRequest | null = null\n const [paymentId] = merchantReference.split('-')\n\n try {\n authRequest = await vbase.getJSON<AuthorizationRequest | null>(\n 'adyenRequest',\n paymentId,\n true\n )\n } catch (error) {\n logger.error({\n message: 'Webhook-transactionFetchError',\n error,\n data: { merchantReference },\n })\n }\n\n if (!authRequest) {\n logger.error({\n message: 'Webhook-originalAuthorizationNotFound',\n data: { paymentId: merchantReference, pspReference, eventCode, success },\n })\n\n ctx.body = '[accepted]'\n\n return\n }\n\n if (eventCode === 'AUTHORISATION') {\n try {\n await vbase.saveJSON<AdyenHookNotification>(\n 'adyenAuth',\n merchantReference,\n eventData\n )\n } catch (error) {\n logger.error({\n message: 'Webhook-transactionSaveError',\n error,\n data: { merchantReference, pspReference },\n })\n }\n\n const authResponse = {\n ...authRequest,\n authorizationId: pspReference,\n tid: pspReference,\n nsu: pspReference,\n status: success === 'true' ? 'approved' : 'denied',\n message: reason ?? null,\n code: null,\n acquirer: null,\n } as ApprovedAuthorization | FailedAuthorization\n\n try {\n provider.callback(\n authRequest.callbackUrl,\n { vtexAppKey, vtexAppToken },\n authResponse\n )\n } catch (error) {\n logger.error({\n message: 'Webhook-providerInboundError',\n error,\n data: authResponse,\n })\n }\n }\n\n let vbaseSavePromise: Promise<unknown> | null = null\n\n if (eventCode === 'CAPTURE') {\n vbaseSavePromise = vbase.saveJSON<TransactionEvent>(\n 'adyenCapture',\n merchantReference,\n { notification: eventData }\n )\n }\n\n if (eventCode === 'REFUND') {\n vbaseSavePromise = vbase.saveJSON<TransactionEvent>(\n 'adyenRefund',\n merchantReference,\n { notification: eventData }\n )\n }\n\n if (eventCode === 'CANCELLATION') {\n vbaseSavePromise = vbase.saveJSON<AdyenHookNotification>(\n 'adyenCancellation',\n merchantReference,\n eventData\n )\n }\n\n try {\n await vbaseSavePromise\n } catch (error) {\n logger.error({\n message: 'Webhook-transactionSaveError',\n error,\n data: { merchantReference, pspReference, eventCode, success },\n })\n }\n\n ctx.body = '[accepted]'\n}\n\nconst routes = {\n adyenWebhook: [handleAdyenWebhook],\n}\n\nexport default routes\n\n```" } ]
code_connector-adyen_6a58c902
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/connector.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable @typescript-eslint/consistent-type-imports */\n\nimport {\n AuthorizationRequest,\n AuthorizationResponse,\n CancellationRequest,\n CancellationResponse,\n Cancellations,\n PaymentProvider,\n RefundRequest,\n RefundResponse,\n Refunds,\n SettlementRequest,\n SettlementResponse,\n Settlements,\n isCardAuthorization,\n Authorizations,\n CardAuthorization,\n PendingAuthorization,\n RedirectResponse,\n} from '@vtex/payment-provider'\n\nimport { Clients } from './clients'\nimport { adyenService } from './services/adyen'\n\nconst APP_ID = process.env.VTEX_APP_ID as string\n\nexport default class Adyen extends PaymentProvider<Clients> {\n public async authorize(\n authorization: AuthorizationRequest\n ): Promise<AuthorizationResponse> {\n const {\n clients: { adyenSecure: adyen, vbase, apps },\n vtex: { logger },\n } = this.context\n\n const settings: AppSettings = await apps.getAppSettings(APP_ID)\n const existingAuthorization =\n await vbase.getJSON<AdyenHookNotification | null>(\n 'adyenAuth',\n authorization.paymentId,\n true\n )\n\n logger.info({\n message: 'connectorAdyen-paymentRequest',\n data: { authorization, existingAuthorization },\n })\n\n if (existingAuthorization) {\n const [\n {\n NotificationRequestItem: { pspReference, reason, success },\n },\n ] = existingAuthorization.notificationItems\n\n if (success === 'true') {\n return Authorizations.approveCard(authorization as CardAuthorization, {\n tid: pspReference,\n authorizationId: pspReference,\n })\n }\n\n if (success === 'false') {\n return Authorizations.deny(authorization, {\n message: reason,\n })\n }\n }\n\n if (!isCardAuthorization(authorization)) {\n return Authorizations.deny(authorization, {\n message: 'Payment method not supported',\n })\n }\n\n await vbase.saveJSON<AuthorizationRequest | null>(\n 'adyenRequest',\n authorization.paymentId,\n authorization\n )\n\n const adyenPaymentRequest = await adyenService.buildPaymentRequest({\n ctx: this.context,\n authorization,\n settings,\n })\n\n let adyenResponse = null\n\n try {\n adyenResponse = await adyen.payment(adyenPaymentRequest)\n } catch (error) {\n logger.error({\n error,\n message: 'connectorAdyen-adyenPaymentRequestError',\n data: adyenPaymentRequest.data,\n })\n }\n\n if (!adyenResponse) {\n return Authorizations.deny(authorization as CardAuthorization, {\n message: 'No Adyen Payment response',\n })\n }\n\n const { resultCode, pspReference, refusalReason } = adyenResponse\n\n if (adyenResponse.action?.url) {\n return {\n paymentId: authorization.paymentId,\n status: 'undefined',\n redirectUrl: adyenResponse.action.url,\n } as RedirectResponse\n }\n\n if (['Error', 'Refused', 'Cancelled'].includes(resultCode)) {\n return Authorizations.deny(authorization as CardAuthorization, {\n tid: pspReference,\n message: refusalReason,\n })\n }\n\n return {\n paymentId: authorization.paymentId,\n status: 'undefined',\n tid: pspReference,\n } as PendingAuthorization\n }\n\n public async cancel(\n cancellation: CancellationRequest\n ): Promise<CancellationResponse> {\n const {\n clients: { adyen, vbase, apps },\n vtex: { logger },\n } = this.context\n\n const existingCancellation = await vbase.getJSON<TransactionEvent | null>(\n 'adyenCancellation',\n cancellation.paymentId,\n true\n )\n\n logger.info({\n message: 'connectorAdyen-cancelRequest',\n data: { cancellation, existingCancellation },\n })\n\n if (existingCancellation) {\n if (existingCancellation.notification) {\n const [\n {\n NotificationRequestItem: {\n pspReference,\n eventCode,\n reason,\n success,\n },\n },\n ] = existingCancellation.notification.notificationItems\n\n if (success === 'true') {\n return Cancellations.approve(cancellation, {\n cancellationId: pspReference,\n })\n }\n\n return Cancellations.deny(cancellation, {\n code: eventCode,\n message: reason,\n })\n }\n\n return {\n ...cancellation,\n cancellationId: null,\n code: null,\n message: null,\n }\n }\n\n vbase.saveJSON<TransactionEvent>(\n 'adyenCancellation',\n cancellation.paymentId,\n {\n notification: null,\n }\n )\n\n if (!cancellation.authorizationId) {\n logger.error({\n message: 'connectorAdyen-authorizationIdMissing',\n data: { cancellation },\n })\n\n throw new Error('Transaction not found')\n }\n\n const settings: AppSettings = await apps.getAppSettings(APP_ID)\n\n try {\n await adyen.cancel(\n cancellation.authorizationId,\n {\n merchantAccount: settings.merchantAccount,\n reference: cancellation.paymentId,\n },\n settings\n )\n } catch (error) {\n logger.error({\n error,\n message: 'connectorAdyen-adyenCancelRequestError',\n data: {\n pspReference: cancellation.authorizationId,\n request: {\n merchantAccount: settings.merchantAccount,\n reference: cancellation.paymentId,\n },\n },\n })\n }\n\n return {\n ...cancellation,\n cancellationId: null,\n code: null,\n message: null,\n }\n }\n\n public async refund(refund: RefundRequest): Promise<RefundResponse> {\n const {\n clients: { adyen, vbase },\n vtex: { logger },\n } = this.context\n\n const existingRefund = await vbase.getJSON<TransactionEvent | null>(\n 'adyenRefund',\n `${refund.paymentId}-${refund.value}`,\n true\n )\n\n logger.info({\n message: 'connectorAdyen-refundRequest',\n data: { refund, existingRefund },\n })\n\n if (existingRefund) {\n if (existingRefund.notification) {\n const [\n {\n NotificationRequestItem: {\n pspReference,\n eventCode,\n reason,\n success,\n },\n },\n ] = existingRefund.notification.notificationItems\n\n if (success === 'true') {\n return Refunds.approve(refund, {\n refundId: pspReference,\n })\n }\n\n return Refunds.deny(refund, {\n cancellationId: pspReference,\n code: eventCode,\n message: reason,\n })\n }\n\n return {\n ...refund,\n refundId: null,\n code: null,\n message: null,\n }\n }\n\n vbase.saveJSON<TransactionEvent>(\n 'adyenRefund',\n `${refund.paymentId}-${refund.value}`,\n { notification: null }\n )\n\n const adyenAuth = await vbase.getJSON<AdyenHookNotification | null>(\n 'adyenAuth',\n refund.paymentId,\n true\n )\n\n if (!adyenAuth) {\n logger.error({\n message: 'connectorAdyen-refundError-AdyenAuthNotFound',\n data: { refund },\n })\n\n throw new Error('Missing transaction data')\n }\n\n const refundRequest = await adyenService.buildRefundRequest({\n ctx: this.context,\n refund,\n authorization: adyenAuth,\n })\n\n try {\n await adyen.refund(refundRequest)\n } catch (error) {\n logger.error({\n error,\n message: 'connectorAdyen-adyenRefundRequestError',\n data: {\n pspReference: refundRequest.pspReference,\n request: refundRequest.data,\n },\n })\n }\n\n return {\n ...refund,\n refundId: null,\n code: null,\n message: null,\n }\n }\n\n public async settle(\n settlement: SettlementRequest\n ): Promise<SettlementResponse> {\n const {\n clients: { adyen, vbase },\n vtex: { logger },\n } = this.context\n\n const existingSettlement = await vbase.getJSON<TransactionEvent | null>(\n 'adyenCapture',\n `${settlement.paymentId}-${settlement.value}`,\n true\n )\n\n logger.info({\n message: 'connectorAdyen-settleRequest',\n data: { settlement, existingSettlement },\n })\n\n if (existingSettlement) {\n if (existingSettlement.notification) {\n const [\n {\n NotificationRequestItem: {\n pspReference,\n eventCode,\n reason,\n success,\n },\n },\n ] = existingSettlement.notification.notificationItems\n\n if (success === 'true') {\n return Settlements.approve(settlement, {\n settleId: pspReference,\n })\n }\n\n return Settlements.deny(settlement, {\n code: eventCode,\n message: reason,\n })\n }\n\n return {\n ...settlement,\n code: null,\n message: null,\n settleId: null,\n }\n }\n\n vbase.saveJSON<TransactionEvent>(\n 'adyenCapture',\n `${settlement.paymentId}-${settlement.value}`,\n { notification: null }\n )\n\n const adyenAuth = await vbase.getJSON<AdyenHookNotification | null>(\n 'adyenAuth',\n settlement.paymentId,\n true\n )\n\n if (!adyenAuth) {\n logger.error({\n message: 'connectorAdyen-settleError-adyenAuthNotFound',\n data: { settlement, adyenAuth },\n })\n\n throw new Error('Missing transaction data')\n }\n\n const adyenCaptureRequest = await adyenService.buildCaptureRequest({\n ctx: this.context,\n settlement,\n authorization: adyenAuth,\n })\n\n try {\n await adyen.capture(adyenCaptureRequest)\n } catch (error) {\n logger.error({\n error,\n message: 'connectorAdyen-adyenSettleRequestError',\n data: {\n pspReference: adyenCaptureRequest.pspReference,\n request: adyenCaptureRequest.data,\n },\n })\n }\n\n return {\n ...settlement,\n code: null,\n message: null,\n settleId: null,\n }\n }\n\n public inbound: undefined\n}\n\n```" } ]
code_connector-adyen_20988ee5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/service.json from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 512,\n \"ttl\": 43200,\n \"timeout\": 40,\n \"minReplicas\": 2,\n \"maxReplicas\": 12,\n \"workers\": 1,\n \"routes\": {\n \"adyenWebhook\": {\n \"path\": \"/_v/api/connector-adyen/v0/hook\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_connector-adyen_fc3ebe3a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/utils.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const randomString = () => {\n return Math.random().toString(36).substring(7)\n}\n\nexport const randomUrl = () => {\n return `https://${randomString()}.com`\n}\n\nexport const priceInCents = (value: number) => {\n return Math.round(value * 100)\n}\n\n```" } ]
code_connector-adyen_1845e698
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/flow.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n isBankInvoiceAuthorization,\n isCardAuthorization,\n isTokenizedCard,\n Authorizations,\n} from '@vtex/payment-provider'\n\nimport { randomString, randomUrl } from './utils'\n\nimport type {\n AuthorizationRequest,\n AuthorizationResponse,\n} from '@vtex/payment-provider'\n\ntype Flow =\n | 'Authorize'\n | 'Denied'\n | 'Cancel'\n | 'AsyncApproved'\n | 'AsyncDenied'\n | 'BankInvoice'\n | 'Redirect'\n\nexport const flows: Record<\n Flow,\n (\n authorization: AuthorizationRequest,\n callback: (response: AuthorizationResponse) => void\n ) => AuthorizationResponse\n> = {\n Authorize: (request) =>\n Authorizations.approve(request, {\n authorizationId: randomString(),\n nsu: randomString(),\n tid: randomString(),\n }),\n\n Denied: (request) => Authorizations.deny(request, { tid: randomString() }),\n\n Cancel: (request, callback) => flows.Authorize(request, callback),\n\n AsyncApproved: (request, callback) => {\n callback(\n Authorizations.approve(request, {\n authorizationId: randomString(),\n nsu: randomString(),\n tid: randomString(),\n })\n )\n\n return Authorizations.pending(request, {\n delayToCancel: 1000,\n tid: randomString(),\n })\n },\n\n AsyncDenied: (request, callback) => {\n callback(Authorizations.deny(request, { tid: randomString() }))\n\n return Authorizations.pending(request, {\n delayToCancel: 1000,\n tid: randomString(),\n })\n },\n\n BankInvoice: (request, callback) => {\n callback(\n Authorizations.approve(request, {\n authorizationId: randomString(),\n nsu: randomString(),\n tid: randomString(),\n })\n )\n\n return Authorizations.pendingBankInvoice(request, {\n delayToCancel: 1000,\n paymentUrl: randomUrl(),\n tid: randomString(),\n })\n },\n\n Redirect: (request, callback) => {\n callback(\n Authorizations.approve(request, {\n authorizationId: randomString(),\n nsu: randomString(),\n tid: randomString(),\n })\n )\n\n return Authorizations.redirect(request, {\n delayToCancel: 1000,\n redirectUrl: randomUrl(),\n tid: randomString(),\n })\n },\n}\n\nexport type CardNumber =\n | '4444333322221111'\n | '4444333322221112'\n | '4222222222222224'\n | '4222222222222225'\n | 'null'\n\nconst cardResponses: Record<CardNumber, Flow> = {\n '4444333322221111': 'Authorize',\n '4444333322221112': 'Denied',\n '4222222222222224': 'AsyncApproved',\n '4222222222222225': 'AsyncDenied',\n null: 'Redirect',\n}\n\nconst findFlow = (request: AuthorizationRequest): Flow => {\n if (isBankInvoiceAuthorization(request)) return 'BankInvoice'\n\n if (isCardAuthorization(request)) {\n const { card } = request\n const cardNumber = isTokenizedCard(card) ? null : card.number\n\n return cardResponses[cardNumber as CardNumber]\n }\n\n return 'Authorize'\n}\n\nexport const executeAuthorization = (\n request: AuthorizationRequest,\n callback: (response: AuthorizationResponse) => void\n): AuthorizationResponse => {\n const flow = findFlow(request)\n\n return flows[flow](request, callback)\n}\n\n```" } ]
code_connector-adyen_367023c1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/package.json from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"@vtex/payment-provider\": \"^1.2.4-beta\",\n \"axios\": \"^0.21.1\",\n \"co-body\": \"^6.0.0\",\n \"country-iso-3-to-2\": \"^1.1.0\",\n \"ramda\": \"^0.25.0\",\n \"typescript-string-enums\": \"^1.0.0\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.44.0\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"@vtex/tsconfig\": \"^0.5.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.apps-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.apps-graphql@2.8.0/public/@types/vtex.apps-graphql\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.141.1/public/@types/vtex.styleguide\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\"\n },\n \"version\": \"0.2.0\"\n}\n\n```" } ]
code_connector-adyen_e82d5d3e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/index.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { PaymentProviderService } from '@vtex/payment-provider'\n\nimport { clients } from './clients'\nimport connector from './connector'\nimport routes from './routes'\n\nexport default new PaymentProviderService({\n connector,\n clients,\n routes,\n})\n\n```" } ]
code_connector-adyen_461910aa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/react/package.json from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"connector-adyen\",\n \"version\": \"0.2.0\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"devDependencies\": {\n \"@types/jest\": \"^26.0.4\",\n \"@types/node\": \"^14.0.14\",\n \"@types/react\": \"^16.9.41\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"vtex.apps-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.apps-graphql@2.8.0/public/@types/vtex.apps-graphql\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.128.4/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.141.1/public/@types/vtex.styleguide\"\n },\n \"dependencies\": {\n \"graphql\": \"^15.3.0\",\n \"react-apollo\": \"^3.1.5\",\n \"react-intl\": \"^5.0.2\"\n }\n}\n\n```" } ]
code_connector-adyen_1738a9ce
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/react/Admin.tsx from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/consistent-type-imports */\nimport React, { FC, useState, useEffect } from 'react'\nimport { useIntl } from 'react-intl'\nimport { useQuery, useMutation } from 'react-apollo'\nimport {\n Layout,\n PageHeader,\n PageBlock,\n Input,\n Button,\n ToastProvider,\n ToastConsumer,\n Toggle,\n} from 'vtex.styleguide'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport AppSettings from './graphql/appSettings.graphql'\nimport SaveAppSettings from './graphql/saveAppSettings.graphql'\n\nconst Admin: FC = () => {\n const { formatMessage } = useIntl()\n const { account } = useRuntime()\n\n const [settingsState, setSettingsState] = useState({\n merchantAccount: '',\n apiKey: '',\n productionAPI: '',\n webhookUsername: '',\n webhookPassword: '',\n vtexAppKey: '',\n vtexAppToken: '',\n useAdyenPlatforms: false,\n })\n\n const [settingsLoading, setSettingsLoading] = useState(false)\n\n const { data } = useQuery(AppSettings, {\n variables: {\n version: process.env.VTEX_APP_VERSION,\n },\n ssr: false,\n })\n\n const [saveSettings] = useMutation(SaveAppSettings)\n\n useEffect(() => {\n if (!data?.appSettings?.message) return\n\n const parsedSettings = JSON.parse(data.appSettings.message)\n\n setSettingsState(parsedSettings)\n }, [data, account, formatMessage])\n\n const handleSaveSettings = async (showToast: any) => {\n setSettingsLoading(true)\n\n await saveSettings({\n variables: {\n version: process.env.VTEX_APP_VERSION,\n settings: JSON.stringify(settingsState),\n },\n })\n .catch((err) => {\n console.error(err)\n showToast({\n message: formatMessage({\n id: 'admin/adyen.saveSettings.failure',\n }),\n duration: 5000,\n })\n setSettingsLoading(false)\n })\n .then(() => {\n showToast({\n message: formatMessage({\n id: 'admin/adyen.saveSettings.success',\n }),\n duration: 5000,\n })\n\n setSettingsLoading(false)\n })\n }\n\n return (\n <ToastProvider positioning=\"window\">\n <ToastConsumer>\n {({ showToast }: { showToast: any }) => (\n <Layout\n pageHeader={\n <PageHeader\n title={formatMessage({\n id: 'admin/adyen.title',\n })}\n />\n }\n >\n <PageBlock>\n <section className=\"pb4\">\n <Input\n label={formatMessage({\n id: 'admin/adyen.settings.adyenMerchantAccount.label',\n })}\n value={settingsState.merchantAccount}\n onChange={(e: React.FormEvent<HTMLInputElement>) =>\n setSettingsState({\n ...settingsState,\n merchantAccount: e.currentTarget.value,\n })\n }\n helpText={formatMessage({\n id: 'admin/adyen.settings.adyenMerchantAccount.helpText',\n })}\n token\n />\n </section>\n <section className=\"pb4\">\n <Input\n label={formatMessage({\n id: 'admin/adyen.settings.adyenApiKey.label',\n })}\n value={settingsState.apiKey}\n onChange={(e: React.FormEvent<HTMLInputElement>) =>\n setSettingsState({\n ...settingsState,\n apiKey: e.currentTarget.value,\n })\n }\n helpText={formatMessage({\n id: 'admin/adyen.settings.adyenApiKey.helpText',\n })}\n token\n />\n </section>\n <section className=\"pb4\">\n <Input\n label={formatMessage({\n id: 'admin/adyen.settings.adyenProductionAPI.label',\n })}\n value={settingsState.productionAPI}\n onChange={(e: React.FormEvent<HTMLInputElement>) =>\n setSettingsState({\n ...settingsState,\n productionAPI: e.currentTarget.value,\n })\n }\n helpText={formatMessage({\n id: 'admin/adyen.settings.adyenProductionAPI.helpText',\n })}\n token\n />\n </section>\n <section className=\"pb4\">\n <Input\n label={formatMessage({\n id: 'admin/adyen.settings.adyenWebhookUsername.label',\n })}\n value={settingsState.webhookUsername}\n onChange={(e: React.FormEvent<HTMLInputElement>) =>\n setSettingsState({\n ...settingsState,\n webhookUsername: e.currentTarget.value,\n })\n }\n helpText={formatMessage({\n id: 'admin/adyen.settings.adyenMerchantAccount.helpText',\n })}\n token\n />\n </section>\n <section className=\"pb4\">\n <Input\n label={formatMessage({\n id: 'admin/adyen.settings.adyenWebhookPassword.label',\n })}\n value={settingsState.webhookPassword}\n onChange={(e: React.FormEvent<HTMLInputElement>) =>\n setSettingsState({\n ...settingsState,\n webhookPassword: e.currentTarget.value,\n })\n }\n helpText={formatMessage({\n id: 'admin/adyen.settings.adyenMerchantAccount.helpText',\n })}\n token\n />\n </section>\n <section className=\"pb4\">\n <Input\n label={formatMessage({\n id: 'admin/adyen.settings.vtexAppKey.label',\n })}\n value={settingsState.vtexAppKey}\n onChange={(e: React.FormEvent<HTMLInputElement>) =>\n setSettingsState({\n ...settingsState,\n vtexAppKey: e.currentTarget.value,\n })\n }\n token\n />\n </section>\n <section className=\"pb6\">\n <Input\n label={formatMessage({\n id: 'admin/adyen.settings.vtexAppToken.label',\n })}\n value={settingsState.vtexAppToken}\n onChange={(e: React.FormEvent<HTMLInputElement>) =>\n setSettingsState({\n ...settingsState,\n vtexAppToken: e.currentTarget.value,\n })\n }\n helpText={formatMessage({\n id: 'admin/adyen.settings.vtexAppToken.helpText',\n })}\n token\n />\n </section>\n <section className=\"pb4\">\n <Toggle\n label={\n settingsState.useAdyenPlatforms\n ? formatMessage({\n id: 'admin/adyen.settings.adyenPlatforms.active',\n })\n : formatMessage({\n id: 'admin/adyen.settings.adyenPlatforms.inactive',\n })\n }\n size=\"large\"\n checked={settingsState.useAdyenPlatforms}\n onChange={() =>\n setSettingsState({\n ...settingsState,\n useAdyenPlatforms: !settingsState.useAdyenPlatforms,\n })\n }\n helpText={formatMessage({\n id: 'admin/adyen.settings.adyenPlatforms.helpText',\n })}\n />\n </section>\n\n <section className=\"pt4\">\n <Button\n variation=\"primary\"\n onClick={() => handleSaveSettings(showToast)}\n isLoading={settingsLoading}\n disabled={\n !settingsState.merchantAccount ||\n !settingsState.apiKey ||\n !settingsState.vtexAppKey ||\n !settingsState.vtexAppToken\n }\n >\n {formatMessage({\n id: 'admin/adyen.saveSettings.buttonText',\n })}\n </Button>\n </section>\n </PageBlock>\n </Layout>\n )}\n </ToastConsumer>\n </ToastProvider>\n )\n}\n\nexport default Admin\n\n```" } ]
code_connector-adyen_adb6de46
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/clients/adyenSecure.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/consistent-type-imports */\nimport { SecureExternalClient } from '@vtex/payment-provider'\nimport {\n // ExternalClient,\n InstanceOptions,\n IOContext,\n RequestConfig,\n} from '@vtex/api'\n\nexport default class AdyenSecure extends SecureExternalClient {\n constructor(protected context: IOContext, options?: InstanceOptions) {\n super('http://checkout-test.adyen.com', context, options)\n }\n\n public async payment({\n data,\n settings,\n secureProxyUrl,\n }: AdyenPaymentRequest): Promise<AdyenPaymentResponse | null> {\n return this.http.post<AdyenPaymentResponse>(\n `/checkout/v67/payments`,\n data,\n {\n headers: {\n 'X-API-Key': settings.apiKey,\n 'X-Vtex-Use-Https': 'true',\n },\n secureProxy: secureProxyUrl,\n metric: 'connectorAdyen-payment',\n } as RequestConfig\n )\n }\n}\n\n```" } ]
code_connector-adyen_095d5a75
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/clients/adyen.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/consistent-type-imports */\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\n\nconst TEST_URL = 'http://checkout-test.adyen.com' as const\n\nexport default class Adyen extends ExternalClient {\n constructor(protected context: IOContext, options?: InstanceOptions) {\n super('', context, options)\n }\n\n private getEndpoint(settings: any) {\n return this.context.production ? settings.productionAPI : TEST_URL\n }\n\n public async capture({\n pspReference,\n data,\n settings,\n }: any): Promise<AdyenCaptureResponse | null> {\n return this.http.post(\n `${this.getEndpoint(settings)}/v67/payments/${pspReference}/captures\n `,\n data,\n {\n headers: {\n 'X-API-Key': settings.apiKey,\n 'X-Vtex-Use-Https': 'true',\n 'Content-Type': 'application/json',\n },\n metric: 'connectorAdyen-capture',\n }\n )\n }\n\n public async cancel(\n pspReference: string,\n data: AdyenCancelRequest,\n appSettings: AppSettings\n ): Promise<AdyenCancelResponse | null> {\n return this.http.post(\n `${this.getEndpoint(appSettings)}/v67/payments/${pspReference}/cancels`,\n data,\n {\n headers: {\n 'X-API-Key': appSettings.apiKey,\n 'X-Vtex-Use-Https': 'true',\n 'Content-Type': 'application/json',\n },\n metric: 'connectorAdyen-cancel',\n }\n )\n }\n\n public async refund({\n pspReference,\n data,\n settings,\n }: AdyenRefundRequest): Promise<AdyenRefundResponse | null> {\n return this.http.post(\n `${this.getEndpoint(settings)}/v67/payments/${pspReference}/refunds\n `,\n data,\n {\n headers: {\n 'X-API-Key': settings.apiKey,\n 'X-Vtex-Use-Https': 'true',\n 'Content-Type': 'application/json',\n },\n metric: 'connectorAdyen-refund',\n }\n )\n }\n}\n\n```" } ]
code_connector-adyen_e24e17ec
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/clients/index.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/consistent-type-imports */\nimport { ClientsConfig, IOClients, ServiceContext } from '@vtex/api'\n\nimport Adyen from './adyen'\nimport Platforms from './adyenPlatforms'\nimport AdyenSecure from './adyenSecure'\nimport Provider from './provider'\n\nexport class Clients extends IOClients {\n public get adyen() {\n return this.getOrSet('adyen', Adyen)\n }\n\n public get adyenSecure() {\n return this.getOrSet('adyenSecure', AdyenSecure)\n }\n\n public get provider() {\n return this.getOrSet('provider', Provider)\n }\n\n public get platforms() {\n return this.getOrSet('platforms', Platforms)\n }\n}\n\ndeclare global {\n type Context = ServiceContext<Clients>\n}\n\nconst EIGHT_SECONDS = 8000\n\nexport const clients: ClientsConfig<Clients> = {\n implementation: Clients,\n options: {\n default: {\n retries: 2,\n timeout: EIGHT_SECONDS,\n },\n },\n}\n\n```" } ]
code_connector-adyen_e123669e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/clients/provider.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/consistent-type-imports */\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\nimport {\n ApprovedAuthorization,\n FailedAuthorization,\n} from '@vtex/payment-provider'\n\nexport default class Provider extends ExternalClient {\n constructor(protected context: IOContext, options?: InstanceOptions) {\n super(`http://heimdall.vtexpayments.com.br/api`, context, options)\n }\n\n public async callback(\n url: string,\n { vtexAppKey, vtexAppToken }: { vtexAppKey: string; vtexAppToken: string },\n response: ApprovedAuthorization | FailedAuthorization\n ): Promise<void> {\n return this.http.post(url, response, {\n headers: {\n 'X-Vtex-Use-Https': 'true',\n 'Content-Type': 'application/json',\n 'X-VTEX-API-AppKey': vtexAppKey,\n 'X-VTEX-API-AppToken': vtexAppToken,\n },\n })\n }\n}\n\n```" } ]
code_connector-adyen_5bf3a1ec
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/clients/adyenPlatforms.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n// eslint-disable-next-line @typescript-eslint/consistent-type-imports\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\n\nexport default class Platforms extends ExternalClient {\n constructor(ctx: IOContext, opts?: InstanceOptions) {\n super(\n `http://${ctx.workspace}--${ctx.account}.myvtex.com/_v/api/adyen-platforms`,\n ctx,\n opts\n )\n }\n\n public async getAccounts(ctx: Context, sellers: string[]): Promise<any> {\n return this.http.get(`/v0/account?seller=${sellers.join('&seller=')}`, {\n headers: {\n VtexIdclientAutCookie: ctx.vtex.authToken,\n },\n metric: 'connectorAdyen-getAccounts',\n })\n }\n}\n\n```" } ]
code_connector-adyen_00a34da5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/typings/adyen.d.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface AdyenHookNotification {\n live: 'true' | 'false'\n notificationItems: [\n {\n NotificationRequestItem: {\n amount: {\n currency: string\n value: number\n }\n eventCode: EventCode\n eventDate: string\n merchantAccountCode: string\n merchantReference: string\n originalReference: string\n paymentMethod: string\n pspReference: string\n reason: string\n success: 'true' | 'false'\n }\n }\n ]\n}\n\ninterface TransactionEvent {\n notification: AdyenHookNotification | null\n}\n\ntype EventCode =\n | 'CAPTURE'\n | 'CAPTURE_FAILED'\n | 'REFUND'\n | 'CANCELLATION'\n | 'AUTHORISATION'\n\ninterface AdyenPaymentResponse {\n action?: Action\n additionalData?: any\n amount: Amount\n donationToken?: string\n fraudResult?: any\n merchantReference: string\n order?: any\n pspReference: string\n refusalReason?: string\n refusalReasonCode?: string\n resultCode: ResultCode\n threeDS2Result?: any\n}\n\ntype ResultCode =\n | 'AuthenticationFinished'\n | 'AuthenticationNotRequired'\n | 'Authorised'\n | 'Cancelled'\n | 'ChallengeShopper'\n | 'Error'\n | 'IdentifyShopper'\n | 'Pending'\n | 'PresentToShopper'\n | 'Received'\n | 'RedirectShopper'\n | 'Refused'\ntype Action = CheckoutAwaitAction\n\ninterface CheckoutAwaitAction {\n paymentData: string\n paymentMethodType: string\n type: 'await'\n url: string\n}\n\ninterface AdyenPayment {\n merchantAccount: string\n amount: Amount\n reference: string\n paymentMethod: PaymentMethod\n returnUrl: string\n}\n\ninterface Amount {\n currency: string\n value: number\n}\n\ninterface PaymentType {\n type: string\n}\n\ninterface AdyenCard extends PaymentType {\n encryptedCardNumber: string\n encryptedExpiryMonth: string\n encryptedExpiryYear: string\n encryptedSecurityCode: string\n holderName?: string\n}\n\ntype PaymentMethod = AdyenCard | PaymentType\n\ninterface AdyenModificationRequest {\n merchantAccount: string\n originalReference: string\n additionalData?: any\n mpiData?: any\n originalMerchantReference?: string\n reference?: string\n splits?: Split[]\n tenderReference?: string\n uniqueTerminalId?: string\n}\n\ninterface AdyenCaptureRequest {\n amount: Amount\n merchantAccount: string\n reference?: string\n splits?: Split[]\n}\n\ninterface AdyenCancelRequest {\n merchantAccount: string\n reference?: string\n}\n\ninterface AdyenPaymentRequest {\n data: AdyenPayment\n settings: AppSettings\n secureProxyUrl: string | undefined\n}\n\ninterface AdyenRefundRequest {\n pspReference: string\n data: AdyenRefund\n settings: AppSettings\n}\n\ninterface AdyenRefund {\n amount: Amount\n merchantAccount: string\n reference?: string\n splits?: Split[]\n}\n\ninterface AdyenSplit {\n account?: string\n amount: Amount\n description?: string\n reference?: string\n type: string\n}\n\ninterface AdyenCaptureResponse {\n amount: Amount\n merchantAccount: string\n paymentPspReference: string\n pspReference: string\n reference?: string\n splits?: Split[]\n status: 'received'\n}\n\ninterface AdyenRefundResponse {\n amount: Amount\n merchantAccount: string\n paymentPspReference: string\n pspReference: string\n reference?: string\n status: 'received'\n}\n\ninterface AdyenCancelResponse {\n merchantAccount: string\n paymentPspReference: string\n pspReference: string\n reference?: string\n status: 'received'\n}\n\n```" } ]
code_connector-adyen_5e88b683
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/typings/global.d.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface AppSettings {\n merchantAccount: string\n apiKey: string\n vtexAppToken: string\n vtexAppKey: string\n webhookUsername: string\n webhookPassword: string\n useAdyenPlatforms: boolean\n}\n\n```" } ]
code_connector-adyen_d1f9a12e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/node/services/adyen.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/consistent-type-imports */\nimport getCountryISO2 from 'country-iso-3-to-2'\nimport {\n AuthorizationRequest,\n CardAuthorization,\n RefundRequest,\n SettlementRequest,\n TokenizedCard,\n} from '@vtex/payment-provider'\nimport { ServiceContext } from '@vtex/api'\n\nimport { priceInCents } from '../utils'\nimport { Clients } from '../clients'\n\nconst APP_ID = process.env.VTEX_APP_ID as string\n\nconst handleSplit = async (\n ctx: ServiceContext<Clients>,\n settings: AppSettings,\n authorization: AuthorizationRequest | RefundRequest | SettlementRequest\n) => {\n if (!settings.useAdyenPlatforms || !authorization.recipients) return undefined\n\n const { recipients } = authorization\n const sellers = recipients.filter((s) => s.role === 'seller')\n\n if (!sellers.length) return undefined\n\n const {\n clients: { platforms },\n vtex: { logger },\n } = ctx\n\n const sellerIds = sellers.map((seller) => seller.id)\n let accounts: any = null\n\n try {\n accounts = await platforms.getAccounts(ctx, sellerIds)\n } catch (error) {\n logger.error({\n error,\n message: 'connectorAdyen-getAccountsRequestError',\n data: { sellerIds },\n })\n }\n\n if (!accounts) {\n logger.warn({\n message: 'connectorAdyen-NoSplitAccountsReturned',\n data: { recipients },\n })\n\n return undefined\n }\n\n const splits = recipients.reduce((prev, cur) => {\n const detail = {\n amount: {\n value: priceInCents(cur.amount),\n },\n type: 'Default',\n reference: cur.name,\n }\n\n if (cur.role === 'seller') {\n prev.push({\n ...detail,\n type: 'MarketPlace',\n account: accounts.find((i: any) => i.sellerId === cur.id).accountCode,\n })\n }\n\n if (cur.role === 'marketplace') {\n prev.push(detail)\n }\n\n return prev\n }, [] as any[])\n\n return splits\n}\n\nexport const adyenService = {\n buildPaymentRequest: async ({\n ctx,\n authorization,\n settings,\n }: {\n ctx: ServiceContext<Clients>\n authorization: AuthorizationRequest\n settings: AppSettings\n }): Promise<AdyenPaymentRequest> => {\n const {\n value,\n currency,\n paymentId,\n returnUrl,\n ipAddress,\n secureProxyUrl,\n card,\n miniCart: { buyer, billingAddress, shippingAddress },\n } = authorization as CardAuthorization\n\n const {\n numberToken: number,\n holderToken: holderName,\n cscToken: cvc,\n expiration: { month: expiryMonth, year: expiryYear },\n } = card as TokenizedCard\n\n const paymentMethod = {\n type: 'scheme',\n number,\n expiryMonth,\n expiryYear,\n cvc,\n holderName,\n }\n\n const splits = await handleSplit(ctx, settings, authorization)\n\n const data = {\n paymentMethod,\n merchantAccount: settings.merchantAccount,\n amount: { value: priceInCents(value), currency },\n reference: paymentId,\n returnUrl: returnUrl ?? '',\n splits,\n shopperEmail: buyer.email,\n shopperIP: ipAddress,\n billingAddress: {\n city: billingAddress?.city,\n country: shippingAddress?.country\n ? getCountryISO2(shippingAddress.country)\n : 'ZZ',\n houseNumberOrName: billingAddress?.number ?? '',\n postalCode: billingAddress?.postalCode ?? '',\n stateOrProvince: billingAddress?.state ?? '',\n street: billingAddress?.street ?? '',\n },\n deliveryAddress: {\n city: shippingAddress?.city,\n country: shippingAddress?.country\n ? getCountryISO2(shippingAddress.country)\n : 'ZZ',\n houseNumberOrName: shippingAddress?.number ?? '',\n postalCode: shippingAddress?.postalCode ?? '',\n stateOrProvince: shippingAddress?.state ?? '',\n street: shippingAddress?.street ?? '',\n },\n browserInfo: {\n language: 'en-EN',\n },\n redirectToIssuerMethod: 'GET',\n }\n\n return {\n data,\n settings,\n secureProxyUrl,\n }\n },\n buildRefundRequest: async ({\n ctx,\n refund,\n authorization,\n }: {\n ctx: ServiceContext<Clients>\n refund: RefundRequest\n authorization: AdyenHookNotification\n }): Promise<AdyenRefundRequest> => {\n const {\n pspReference,\n amount: { currency },\n } = authorization.notificationItems[0].NotificationRequestItem\n\n const settings: AppSettings = await ctx.clients.apps.getAppSettings(APP_ID)\n const splits = await handleSplit(ctx, settings, refund)\n\n const data = {\n merchantAccount: settings.merchantAccount,\n amount: { value: priceInCents(refund.value), currency },\n reference: `${refund.paymentId}-${refund.value}`,\n splits,\n }\n\n return {\n pspReference, // refund.tid\n data,\n settings,\n }\n },\n buildCaptureRequest: async ({\n ctx,\n settlement,\n authorization,\n }: {\n ctx: ServiceContext<Clients>\n settlement: SettlementRequest\n authorization: AdyenHookNotification\n }): Promise<AdyenRefundRequest> => {\n const {\n pspReference,\n amount: { currency },\n } = authorization.notificationItems[0].NotificationRequestItem\n\n const settings: AppSettings = await ctx.clients.apps.getAppSettings(APP_ID)\n const splits = await handleSplit(ctx, settings, settlement)\n\n const data = {\n merchantAccount: settings.merchantAccount,\n amount: { value: priceInCents(settlement.value), currency },\n reference: `${settlement.paymentId}-${settlement.value}`,\n splits,\n }\n\n return {\n pspReference, // refund.tid\n data,\n settings,\n }\n },\n}\n\n```" } ]
code_connector-adyen_c1be4a99
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/react/typings/graphql.d.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_connector-adyen_5ed02480
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/react/typings/vtex.styleguide.d.ts from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n export const PageHeader\n export const Alert\n export const Modal\n export const Box\n export const Card\n export const Dropdown\n export const Spinner\n export const Table\n export const Button\n export const ButtonPlain\n export const IconWarning\n export const IconCheck\n export const Input\n export const InputSearch\n export const IconCaretDown\n export const IconCaretUp\n export const IconArrowDown\n export const IconArrowBack\n export const IconArrowUp\n export const IconClose\n export const IconExternalLink\n export const IconSearch\n export const IconSuccess\n export const IconCopy\n export const IconCog\n export const Toggle\n export const Tooltip\n export const ToastConsumer\n export const ToastProvider\n export const withToast\n export const ButtonWithIcon\n export const Pagination\n export const Collapsible\n export const Textarea\n export const NumericStepper\n export const EmptyState\n export const Tab\n export const Tag\n export const Layout\n export const Tabs\n export const Divider\n export const PageBlock\n}\n\n```" } ]
code_connector-adyen_e895c03c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/react/graphql/saveAppSettings.graphql from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation SaveAppSettings($version: String, $settings: String) {\n saveAppSettings(\n app: \"vtex.connector-adyen\"\n version: $version\n settings: $settings\n ) @context(provider: \"vtex.apps-graphql\") {\n message\n }\n}\n\n```" } ]
code_connector-adyen_3dba9614
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of connector-adyen/react/graphql/appSettings.graphql from the connector-adyen VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery AppSettings($version: String) {\n appSettings(app: \"vtex.connector-adyen\", version: $version)\n @context(provider: \"vtex.apps-graphql\") {\n message\n }\n}\n\n```" } ]
code_components-financial-commission_3bdcca1e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/messages/en.json from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/navigation.title\": \"Commission Report Dashboard\",\n \"admin/navigation.setting\": \"Setting: {name}\",\n \"admin/navigation.settings\": \"Settings\",\n \"admin/table.title-seller-label\": \"Choose seller name\",\n \"admin/table.title-status-label\": \"Choose status order\",\n \"admin/table.title-datepicker-start\": \"Start\",\n \"admin/table.title-datepicker-final\": \"Final\",\n \"admin/table.title-filter\": \"Filter\",\n \"admin/table.title-tab-commission\": \"Orders\",\n \"admin/table.pagination-show\": \"Show rows\",\n \"admin/table.pagination-textOf\": \"of\",\n \"admin/table.title-tab-invoices\": \"Invoices\",\n \"admin/form-settings.button-invoice\": \"Create Invoice\",\n \"admin/form-settings.invalid-invoice\": \"Filter orders by invoiced status and within a proper range to enable CREATE INVOICE button\",\n \"admin/modal-settings.email-empty\": \"Specify an email address\",\n \"admin/modal-settings.email-invalid\": \"Invalid email address\",\n \"admin/modal-setting.warning\": \"The invoice you are about to create may contain orders previously invoiced.\",\n \"admin/modal-setting.confirmation\": \"Are you sure to continue?\",\n \"admin/form-settings.button-email\": \"Send Email\",\n \"admin/email-success\": \"Email sent\",\n \"admin/invoice-success\": \"Invoice Created\",\n \"admin/invoice-error\": \"Error creating invoice\",\n \"admin/billing-cycle\": \"Settings Detail Sellers\",\n \"admin/save-settings\": \"SAVE\",\n \"admin/table-settings-name\": \"name\",\n \"admin/table-settings-actions\": \"Actions\",\n \"admin/table-settings-detail\": \"Detail\",\n \"admin/table-seller-name\": \"Seller name\",\n \"admin/table-total-order\": \"Total Order\",\n \"admin/table-total-amount\": \"Total Amount Orders\",\n \"admin/table-total-commission\": \"Total commission\",\n \"admin/table-actions\": \"Actions\",\n \"admin/table.empty-state\": \"Use the filters to search and display data\",\n \"admin/table.empty-state-title\": \"There's nothing here\",\n \"admin/table-seller-order\": \"Order ID\",\n \"admin/table-creation-order\": \"Creation Date\",\n \"admin/table-commission-order\": \"Total Commission\",\n \"admin/table-rate-order\": \"Rate\",\n \"admin/table-seller-status\": \"Status\",\n \"admin/table-seller-invoice\": \"ID invoice\",\n \"admin/table-seller-created\": \"Invoice Created Date\",\n \"admin/modal-settings.billingCycle\": \"Global Billing cycle\",\n \"admin/modal-settings.billingCycle-helpText\": \"Each cycle will trigger the creation of an Invoice; keep in mind that if this is changed, all sellers that follow the default settings will automatically generate an Invoice and start a new cycle following the new rule.\",\n \"admin/modal-settings.alert-warning\": \"Proceed with caution. All sellers that currently don't have individual settings will be affected\",\n \"admin/form-settings.button-new\": \"Generate a new one\",\n \"admin/navigation.detail-title\": \"Seller Invoice Detail\"\n}\n\n```" } ]
code_components-financial-commission_b9ed2cc7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/messages/context.json from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/navigation.title\": \"Dashboard Main Title \",\n \"admin/navigation.setting\": \"Setting: {name}\",\n \"admin/navigation.settings\": \"Settings\",\n \"admin/table.title-seller-label\": \"Title of table filter to identify Choose seller name\",\n \"admin/table.title-status-label\": \"Title of table filter to Choose order status\",\n \"admin/table.title-datepicker-start\": \"Title of table filter to identify Start Date\",\n \"admin/table.title-datepicker-final\": \"Title of table filter to identify Final Date\",\n \"admin/table.title-filter\": \"Title of table filter to identify Filter\",\n \"admin/table.title-tab-commission\": \"Title tab to identify Commissions\",\n \"admin/table.pagination-show\": \"show rows\",\n \"admin/table.pagination-textOf\": \"of\",\n \"admin/table.title-tab-invoices\": \"Title tab to Invoices\",\n \"admin/form-settings.button-invoice\": \"Create Invoice\",\n \"admin/form-settings.invalid-invoice\": \"Filter orders by invoiced status and within a proper range to enable CREATE INVOICE button\",\n \"admin/modal-settings.email-empty\": \"Specify an email address\",\n \"admin/modal-settings.email-invalid\": \"Invalid email address\",\n \"admin/modal-setting.warning\": \"The invoice you are about to create may contain orders previously invoiced\",\n \"admin/modal-setting.confirmation\": \"Are you sure to continue?\",\n \"admin/form-settings.button-email\": \"Send Email\",\n \"admin/email-success\": \"Email sent\",\n \"admin/invoice-success\": \"Invoice Created\",\n \"admin/invoice-error\": \"Error creating invoice\",\n \"admin/billing-cycle\": \"Billing Cycle Detail\",\n \"admin/save-settings\": \"SAVE\",\n \"admin/table-settings-name\": \"name\",\n \"admin/table-settings-actions\": \"Actions\",\n \"admin/table-settings-detail\": \"Detail\",\n \"admin/table-seller-name\": \"Seller name\",\n \"admin/table-total-amount\": \"Total Amount Orders\",\n \"admin/table-total-commission\": \"Total commission\",\n \"admin/table-actions\": \"Actions\",\n \"admin/table.empty-state\": \"Describe empty table\",\n \"admin/table.empty-state-title\": \"Title to empty table\",\n \"admin/table-seller-order\": \"Order ID\",\n \"admin/table-creation-order\": \"Creation Date\",\n \"admin/table-total-order\": \"Total Order\",\n \"admin/table-commission-order\": \"Total Commission\",\n \"admin/table-rate-order\": \"Rate\",\n \"admin/table-seller-status\": \"Status\",\n \"admin/table-seller-invoice\": \"ID invoice\",\n \"admin/table-seller-created\": \"Invoice Created Date\",\n \"admin/modal-settings.billingCycle\": \"Section title for billing cycle\",\n \"admin/modal-settings.billingCycle-helpText\": \"Repercution explanation about modifying billing cycle\",\n \"admin/modal-settings.alert-warning\": \"Warning about modifying settings\",\n \"admin/form-settings.button-new\": \"Generate a new one\",\n \"admin/navigation.detail-title\": \"Seller Invoice Detail\"\n}\n\n```" } ]
code_components-financial-commission_ab8bfdf3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/docs/README.md from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n**📢 Don't fork this project. Use, contribute, or open issues through Store Discussion.**\n\n\n\n# COMPONENTS FINANCIAL COMMISSION \n\n**Components Financial Commission** is an app that can be used to create the interfaces in other apps in charge of generating and showing the sales commissions \n\n</br>\n </br>\n\n > :warning:\n > **This app was designed to be used in the Financial Commission App**. Please, validate if you want to use this app in another implementation.\n \n </br>\n\n## How to import this app\n\nAdd in the section `dependencies` of the manifest file of the app to use, the next instruction that show you below.\n\n```powershell\n\"dependencies\":{\n \"vtex.components-financial-commission\": \"0.x\"\n}\n```\n</br>\n\n**Important:** Remember to validate the version. For this, go to the repository [Here](https://github.com/vtex-apps/components-financial-commission)\n\n</br>\n\n## Project Structure\n\nHere you find the structure of the project folder. The changes made in this app will be reflected in the apps using the **Components Financial Commission** app in the dependencies\n\n![image](https://user-images.githubusercontent.com/8409481/186645144-3aeb1c81-245b-4948-b80c-8bf653499b3f.png)\n\n</br>\n\n\n**Components folder**\n\nHere you find all elements shared or common between screens. \n\nA large part of components receives the data from `props`.\n\n</br>\n\n**Utils Folder**\n\nIn this folder you find the common operations, for example: \n\n- Get the date in string format to the using it in the services request\n- Get the first day of the month\n- Functions of filters to use in the components related with filters\n</br>\n\n\n**Typings Folder**\n\nAdd the interfaces or commons types to you'll use in the app.\n\n</br>\n\n**Root Folder**\n\nHere you can find the folder `message`. Here add the files `en.json` with all the dynamic text. Also, you should add the file `context.json` with the explanation of the use of each dynamic text.\n\n</br>\n\n## How to use this app\n\nImport the components that you need in your project, for example:\n\n```jsx\nimport { detail as Detail } from 'vtex.components-financial-commission'\n\nreturn (\n <Detail\n dataSellers={dataSellers}\n ordersQuery={SEARCH_ORDERS}\n invoiceMutation={CREATE_INVOICE}\n invoicesQuery={SELLER_INVOICES}\n settingsQuery={GET_SETTINGS}\n />\n )\n\n/** Types */\ninterface DetailProps {\n account?: string\n dataSellers?: {\n getSellers: {\n pagination: Pagination\n sellers: [DataSellerSelect]\n }\n }\n ordersQuery: DocumentNode\n invoiceMutation: DocumentNode\n invoicesQuery: DocumentNode\n settingsQuery?: DocumentNode\n}\n```\n</br>\n\nThe components available with the assigned types:\n\n```jsx\nimport { settings as Settings } from 'vtex.components-financial-commission'\n\nreturn (\n <Settings\n getSellersQuery={GET_SELLERS}\n createSettingsMutation={CREATE_SETTINGS}\n getSettingsQuery={GET_SETTINGS}\n editToken={EDIT_TOKEN}\n createTokenMutation={CREATE_TOKEN}\n getTokenQuery={GET_TOKEN}\n />\n )\n\n/** Types */\ninterface DetailProps {\n account?: string\n dataSellers?: {\n getSellers: {\n pagination: Pagination\n sellers: [DataSellerSelect]\n }\n }\n ordersQuery: DocumentNode\n invoiceMutation: DocumentNode\n invoicesQuery: DocumentNode\n settingsQuery?: DocumentNode\n}\n```\n\n```tsx\nimport { commissionReport as Report } from 'vtex.components-financial-commission'\n\nreturn (\n <Report\n getSellersQuery={GET_SELLERS}\n searchStatsQuery={SEARCH_STATS}\n searchSellersQuery={SEARCH_SELLERS}\n />\n )\n\n/** Types */\ninterface ReportProps {\n getSellersQuery: DocumentNode\n searchStatsQuery: DocumentNode\n searchSellersQuery: DocumentNode\n}\n```\n\n```tsx\nimport { settingsDetail as SettingsDetail } from 'vtex.components-financial-commission'\n\nreturn (\n <SettingsDetail\n createTokenMutation={CREATE_TOKEN}\n editToken={EDIT_TOKEN}\n getTokenQuery={GET_TOKEN}\n createSettingsMutation={CREATE_SETTINGS}\n getSettingsQuery={GET_SETTINGS}\n />\n )\n\n/** Types */\n\ninterface SettingsDetailProps {\n createTokenMutation: DocumentNode\n editToken: DocumentNode\n getTokenQuery: DocumentNode\n createSettingsMutation: DocumentNode\n getSettingsQuery: DocumentNode\n}\n```\n\n```jsx\nimport { invoiceDetail as InvoiceDetail } from 'vtex.components-financial-commission'\n\nreturn (\n <InvoiceDetail\n invoiceQuery={GET_INVOICE}\n getTemplate={GET_TEMPLATE}\n sendEmail={SEND_EMAIL}\n />\n )\n\n/** Types */\n\ninterface InvoiceDetailProps {\n invoiceQuery: DocumentNode\n getTemplate: DocumentNode\n sendEmail: DocumentNode\n}\n```\n\nUse the types to identify the data to pass between props of the components.\n\n\n---\n\n**Other things about the project:**\n\n`🚫` Please, don't upload the file `yarn.lock`. Remove this file of the `commit`.\n\n`✅` When you clone the project, create your work branch from `develop`.\n\n`✅` Upload your changes by making a `pull request`.\n\n`⚠️` Not forget to update the version and documentation. This last only if this is necessary.\n\n```" } ]
code_components-financial-commission_c8b99552
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/settings.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useEffect, useState } from 'react'\nimport {\n Layout,\n PageBlock,\n PageHeader,\n ActionMenu,\n IconOptionsDots,\n Alert,\n EXPERIMENTAL_Select as Select,\n Box,\n Button,\n Toggle,\n EXPERIMENTAL_Table as Table,\n Spinner,\n} from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\nimport { useQuery, useMutation } from 'react-apollo'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { DocumentNode } from 'graphql'\n\nimport TableComponent from './components/Table'\nimport PaginationComponent from './components/Table/pagination'\nimport { Filter, TokenAuth } from './components'\n\ninterface SettingsProps {\n getSellersQuery: DocumentNode\n createSettingsMutation: DocumentNode\n getSettingsQuery: DocumentNode\n createTokenMutation: DocumentNode\n editToken: DocumentNode\n getTokenQuery: DocumentNode\n}\n\nconst Settings: FC<SettingsProps> = (props) => {\n const { getSellersQuery, createSettingsMutation, getSettingsQuery, createTokenMutation, editToken, getTokenQuery, } = props\n const { navigate, account } = useRuntime()\n const [sellersId, setSellersId] = useState('')\n const [optionsSelect, setOptionsSelect] = useState<SellerSelect[]>([])\n const [sellersResult, setSellersResult] = useState<SettingsSellers[] | []>([])\n const [selectedValue, setSelectValue] = useState<SelectObj | null>()\n const [infoSettings, setInfoSettings] = useState<SettingInfoType[]>([])\n const [createSettings, { data: dataSettings }] = useMutation(\n createSettingsMutation\n )\n const [tokenSeller, setTokenSeller] = useState<any>({})\n const [page, setPage] = useState(1)\n const [pageSize, setPageSize] = useState(20)\n const [itemFrom, setItemFrom] = useState(1)\n const [itemTo, setItemTo] = useState(20)\n const [totalItems, setTotalItems] = useState(0)\n const [openAlert, setOpenAlert] = useState(false)\n const [integration, setIntegration] = useState(true)\n const { data: dataSellers } = useQuery(getSellersQuery, {\n ssr: false,\n pollInterval: 0,\n })\n\n const { data: dataSellersTable } = useQuery(getSellersQuery, {\n ssr: false,\n pollInterval: 0,\n variables: {\n listSellersParams: {\n page,\n pageSize,\n sellersId,\n },\n },\n })\n\n const [editTokenMutation] = useMutation(editToken)\n\n const { data: getToken } = useQuery(getTokenQuery, {\n ssr: false,\n pollInterval: 0,\n variables: {\n accountId: account,\n },\n })\n\n const { data: settings, loading } = useQuery(getSettingsQuery, {\n ssr: false,\n pollInterval: 0,\n fetchPolicy: 'no-cache',\n })\n\n const DATE_CUT_OPTIONS = [\n /*\n {\n value: 7,\n label: 'Weekly',\n },\n {\n value: 15,\n label: 'Bi-weekly',\n }, */\n {\n value: 1,\n label: 'Daily',\n },\n {\n value: 30,\n label: 'Monthly',\n },\n ]\n\n useEffect(() => {\n if (getToken) setTokenSeller(getToken)\n }, [getToken])\n\n useEffect(() => {\n if (settings) {\n setInfoSettings([\n {\n idbilling: settings.getSettings.billingCycle,\n start: settings.getSettings.startDate,\n end: settings.getSettings.endDate,\n },\n ])\n\n setSelectValue({\n value: 30,\n label: settings.getSettings.billingCycle,\n })\n\n if (settings.getSettings.integration === 'external') setIntegration(false)\n }\n }, [settings])\n\n useEffect(() => {\n if (dataSellersTable) {\n const dataTableDashboard: SettingsSellers[] = []\n\n dataSellersTable.getSellers.sellers.forEach((seller: DataSeller) => {\n dataTableDashboard.push({\n id: seller.id,\n name: seller.name,\n })\n })\n setSellersResult(dataTableDashboard)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dataSellersTable])\n\n useEffect(() => {\n if (dataSellers) {\n const builtSelectSeller: SellerSelect[] = []\n\n dataSellers.getSellers.sellers.forEach((seller: DataSeller) => {\n builtSelectSeller.push({\n value: { id: seller.id, name: seller.name },\n label: seller.name,\n })\n })\n setOptionsSelect(builtSelectSeller)\n setTotalItems(dataSellers.getSellers.sellers.length)\n }\n }, [dataSellers])\n\n const Actions = ({ data }: any) => {\n return (\n <ActionMenu\n buttonProps={{\n variation: 'tertiary',\n icon: <IconOptionsDots />,\n }}\n options={[\n {\n label: <FormattedMessage id=\"admin/table-settings-detail\" />,\n onClick: () => {\n navigate({\n to: `/admin/app/commission-report/settings/detail/${data.id}`,\n replace: true,\n query: `name=${data.name}&integration=${integration}`,\n })\n },\n },\n ]}\n />\n )\n }\n\n const schemaTable = [\n {\n id: 'name',\n title: <FormattedMessage id=\"admin/table-settings-name\" />,\n width: '90em',\n // eslint-disable-next-line react/display-name\n cellRenderer: (cellProps: CellRendererProps) => {\n return <span>{cellProps.data}</span>\n },\n },\n {\n id: 'id',\n title: <FormattedMessage id=\"admin/table-settings-actions\" />,\n width: '10em',\n // eslint-disable-next-line react/display-name\n cellRenderer: (cellProps: CellRendererProps) => (\n <Actions {...cellProps} />\n ),\n extended: true,\n },\n ]\n\n const handleCreateSettings = (integrationType = integration) => {\n if (selectedValue) {\n const nowDate = new Date()\n let date = ''\n let lastDateString = ''\n\n const month =\n nowDate.getMonth() + 1 <= 9\n ? `0${nowDate.getMonth() + 1}`\n : nowDate.getMonth() + 1\n\n if (selectedValue.label === 'Monthly') {\n const day =\n nowDate.getDate() < 10 ? `0${nowDate.getDate()}` : nowDate.getDate()\n\n date = `${nowDate.getFullYear()}-${month}-${day}`\n\n const lastDate = new Date(\n nowDate.getFullYear(),\n nowDate.getMonth() + 1,\n 0\n )\n\n const lastMonth =\n lastDate.getMonth() + 1\n ? `0${lastDate.getMonth() + 1}`\n : lastDate.getMonth() + 1\n\n const lastDay =\n lastDate.getDate() < 10\n ? `0${lastDate.getDate()}`\n : lastDate.getDate()\n\n lastDateString = `${lastDate.getFullYear()}-${lastMonth}-${lastDay}`\n } else {\n const day =\n nowDate.getDate() < 10 ? `0${nowDate.getDate()}` : nowDate.getDate()\n\n /* const finalDay =\n nowDate.getDate() + 1 < 10? `0${nowDate.getDate() + 1}` : nowDate.getDate() + 1 */\n\n date = `${nowDate.getFullYear()}-${month}-${day}`\n lastDateString = `${nowDate.getFullYear()}-${month}-${day}`\n }\n\n createSettings({\n variables: {\n settingsData: {\n startDate: date,\n endDate: lastDateString,\n billingCycle: selectedValue.label,\n integration: integrationType ? 1 : 0,\n },\n },\n })\n\n editTokenMutation({\n variables: {\n accountId: account,\n isEnable: !integrationType,\n },\n })\n }\n }\n\n useEffect(() => {\n if (dataSettings) {\n setInfoSettings([\n {\n idbilling: dataSettings.createSettings.billingCycle,\n start: dataSettings.createSettings.startDate,\n end: dataSettings.createSettings.endDate,\n },\n ])\n\n setOpenAlert(true)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dataSettings])\n\n const changeRows = (row: number) => {\n setPageSize(row)\n setItemTo(row)\n setItemFrom(1)\n setPage(1)\n }\n\n const onNextClick = () => {\n const nextPage = page + 1\n\n const currentTo = pageSize * nextPage\n const currentFrom = itemTo + 1\n\n setItemTo(currentTo)\n setItemFrom(currentFrom)\n setPage(nextPage)\n }\n\n const onPrevClick = () => {\n const previousPage = page - 1\n\n const currentTo = itemTo - pageSize\n const currentFrom = itemFrom - pageSize\n\n setItemTo(currentTo)\n setItemFrom(currentFrom)\n setPage(previousPage)\n }\n\n return (\n <Layout\n pageHeader={\n <PageHeader\n title={<FormattedMessage id=\"admin/navigation.settings\" />}\n />\n }\n >\n {loading ? <div className='flex justify-center'> <Spinner /> </div> : (<div className=\"mb2\">\n <Box>\n {integration && (\n <div className=\"mb7\">\n <h2>\n <FormattedMessage id=\"admin/modal-settings.billingCycle\" />\n </h2>\n <div className=\"mb4\">\n <Alert type=\"warning\">\n <FormattedMessage id=\"admin/modal-settings.alert-warning\" />\n </Alert>\n <div className=\"mb5 flex w-100 mt6\">\n <div className=\"w-90\">\n <Select\n menuPosition=\"fixed\"\n options={DATE_CUT_OPTIONS}\n multi={false}\n value={selectedValue}\n onChange={(values: SelectObj) => {\n setSelectValue(values)\n }}\n />\n </div>\n <div className=\"w-10 pl2\">\n <Button\n variation=\"primary\"\n onClick={() => {\n handleCreateSettings()\n }}\n >\n <FormattedMessage id=\"admin/save-settings\" />\n </Button>\n </div>\n </div>\n <div className=\"w-100\">\n <p className=\"t-small mw9 c-muted-1\">\n <FormattedMessage id=\"admin/modal-settings.billingCycle-helpText\" />\n </p>\n </div>\n </div>\n {openAlert ? (\n <div className=\"mt7\">\n <Alert type=\"success\" onClose={() => setOpenAlert(false)}>\n Data was updated successfully\n </Alert>\n </div>\n ) : (\n <div />\n )}\n <div className=\"mt7\">\n <Table\n stickyHeader\n measures={[]}\n items={infoSettings}\n columns={[\n {\n id: 'idbilling',\n title: 'Billing Cycle',\n },\n {\n id: 'start',\n title: 'Start Date',\n },\n {\n id: 'end',\n title: 'End Date',\n },\n ]}\n />\n </div>\n </div>\n )}\n <div>\n <h3 className=\"ma0\">Type Integration</h3>\n <div className=\"flex items-center\">\n <div className=\"w-20\">\n <Toggle\n label={integration ? 'Internal' : 'External'}\n semantic\n checked={integration}\n onChange={() => {\n setIntegration(!integration)\n handleCreateSettings(!integration)\n }}\n />\n </div>\n <div className=\"w-80\">\n <p>\n If you choose the <b>External</b> option, you will be in\n charge to do the commission calculations and invoices.\n </p>\n </div>\n </div>\n </div>\n </Box>\n </div>)}\n {!integration && (<TokenAuth activateToogle={false} editToken={editToken} createTokenMutation={createTokenMutation} sellerId={account} tokenSeller={tokenSeller} />)}\n <p className=\"c-action-primary hover-c-action-primary fw5 ml2 mt6\">\n <FormattedMessage id=\"admin/billing-cycle\" />\n </p>\n <div className=\"mt6\">\n <PageBlock>\n <div>\n <Filter\n optionsSelect={optionsSelect}\n setSellerId={setSellersId}\n setTotalItems={setTotalItems}\n multiValue\n />\n </div>\n </PageBlock>\n </div>\n <div className=\"mt2\">\n <PageBlock>\n <div className=\"mt4 mb7\">\n <TableComponent\n schemaTable={schemaTable}\n items={sellersResult}\n loading={false}\n />\n <PaginationComponent\n setPageSize={setPageSize}\n currentPage={itemFrom}\n pageSize={itemTo}\n setPage={setPage}\n totalItems={totalItems}\n onNextClick={onNextClick}\n changeRows={changeRows}\n onPrevClick={onPrevClick}\n />\n </div>\n </PageBlock>\n </div>\n </Layout>\n )\n}\n\nexport default Settings\n\n```" } ]
code_components-financial-commission_78cf8fa7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/pagination.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport PaginationComponent from './components/Table/pagination'\n\nexport default PaginationComponent\n\n```" } ]
code_components-financial-commission_16a1e5dc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/styles.css from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.btn_external button {\n width: 120px;\n}\n\n.btn_filter button {\n width: 95%;\n font-size: 15px;\n}\n\n.buttonGroup button {\n z-index: 0 !important;\n}\n\n.large {\n width: 80%;\n}\n\n@media (max-width: 800px) {\n .filter {\n flex-direction: column;\n }\n\n .filter_container {\n width: 100%;\n margin-top: 10px;\n }\n .btn_filter {\n width: 100%;\n }\n}\n\n```" } ]
code_components-financial-commission_74b5864d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/commissionReport.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport type { DocumentNode } from 'graphql'\nimport React, { useEffect, useState } from 'react'\nimport {\n Layout,\n PageBlock,\n IconShoppingCart,\n IconUser,\n IconArrowUp,\n IconInfo,\n PageHeader,\n ActionMenu,\n IconOptionsDots,\n IconCog,\n ButtonWithIcon,\n Modal,\n Divider,\n Toggle,\n} from 'vtex.styleguide'\nimport { useQuery, useLazyQuery } from 'react-apollo'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { FormattedMessage, defineMessages, useIntl } from 'react-intl'\nimport { Filter, Totalizer } from './components'\nimport TableComponent from './components/Table'\nimport PaginationComponent from './components/Table/pagination'\nimport { defaultStartString, defaultFinalString } from './constants'\n\nconst dateDefaultPicker = {\n startDatePicker: new Date(`${defaultStartString}T00:00:00`),\n finalDatePicker: new Date(`${defaultFinalString}T00:00:00`),\n defaultStartDate: defaultStartString,\n defaultFinalDate: defaultFinalString,\n today: false\n}\n\ninterface ReportProps {\n getSellersQuery: DocumentNode\n searchStatsQuery: DocumentNode\n searchSellersQuery: DocumentNode\n}\n\nconst idMessage: MessageType = defineMessages({\n actions: { id: \"admin/table-actions\" },\n totalComission: { id: \"admin/table-total-commission\" },\n totalOrderValue: { id: \"admin/table-total-amount\" },\n ordersCount: { id: \"admin/table-total-order\" },\n name: { id: \"admin/table-seller-name\" }\n})\n\nconst CommissionReport: FC<ReportProps> = (props) => {\n const { getSellersQuery, searchStatsQuery, searchSellersQuery } = props\n const intl = useIntl()\n\n const { navigate } = useRuntime()\n const [optionsSelect, setOptionsSelect] = useState<SellerSelect[]>([])\n const [startDate, setStartDate] = useState('')\n const [finalDate, setFinalDate] = useState('')\n const [sellersId, setSellersId] = useState('')\n const [page, setPage] = useState(1)\n const [pageSize, setPageSize] = useState(20)\n const [itemFrom, setItemFrom] = useState(1)\n const [itemTo, setItemTo] = useState(20)\n const [totalItems, setTotalItems] = useState(0)\n const [totalAmount, setTotalAmout] = useState(0)\n const [totalCommission, setTotalCommission] = useState(0)\n const [totalOrder, setTotalOrder] = useState(0)\n const [orderSort, setOrderSort] = useState('totalComission DSC')\n const [totalItemsFilter, setTotalItemsFilter] = useState(0)\n const [statsTotalizer, setStatsTotalizer] = useState<StatsTotalizer[]>([\n {\n label: '',\n value: '',\n iconBackgroundColor: '',\n },\n ])\n\n const columnModal: JSX.Element[] = []\n const [hideColumns, setHideColumn] = useState<string[]>([])\n const [modalColumns, setModalColumns] = useState(false)\n\n const [sellersDashboard, setSellersDashboard] = useState<DataSeller[]>([])\n\n const { data: dataSellers } = useQuery(getSellersQuery, {\n ssr: false,\n pollInterval: 0,\n })\n\n const [stats, { data: dataStats, loading: loadingStats }] = useLazyQuery(\n searchStatsQuery,\n {\n ssr: false,\n pollInterval: 0,\n variables: {\n params: {\n dateStart: startDate,\n dateEnd: finalDate,\n },\n },\n }\n )\n\n const [\n dashboard,\n { data: dataDashboard, loading: loadingDataDashboard },\n ] = useLazyQuery(searchSellersQuery, {\n ssr: false,\n pollInterval: 0,\n variables: {\n param: {\n dateStart: startDate,\n dateEnd: finalDate,\n page,\n pageSize,\n sellersId,\n sort: orderSort,\n },\n },\n })\n\n // id name ordersCount totalComission totalOrderValue\n\n const hideShowColumns = (e: string) => {\n const temp = [...hideColumns]\n\n if (temp.find((id) => id === e)) {\n temp.splice(temp.indexOf(e), 1)\n } else {\n temp.push(e)\n }\n\n setHideColumn(temp)\n }\n\n const schemaTable = [\n {\n id: 'name',\n title: <FormattedMessage id=\"admin/table-seller-name\" />,\n // eslint-disable-next-line react/display-name\n cellRenderer: (cellProps: CellRendererProps) => {\n return <span>{cellProps.data}</span>\n },\n sortable: true,\n },\n {\n id: 'ordersCount',\n title: <FormattedMessage id=\"admin/table-total-order\" />,\n sortable: true,\n },\n {\n id: 'totalOrderValue',\n title: <FormattedMessage id=\"admin/table-total-amount\" />,\n sortable: true,\n },\n {\n id: 'totalComission',\n title: <FormattedMessage id=\"admin/table-total-commission\" />,\n sortable: true,\n },\n {\n id: 'name',\n title: <FormattedMessage id=\"admin/table-actions\" />,\n // eslint-disable-next-line react/display-name\n cellRenderer: (cellProps: CellRendererProps) => {\n return (\n <ActionMenu\n buttonProps={{\n variation: 'tertiary',\n icon: <IconOptionsDots />,\n }}\n options={[\n {\n label: 'Detail',\n onClick: () => {\n navigate({\n to: `/admin/app/commission-report/detail?sellerName=${cellProps.data}&status=invoiced`,\n })\n },\n },\n ]}\n />\n )\n },\n },\n ]\n\n useEffect(() => {\n dashboard()\n // eslint-disable-next-line vtex/prefer-early-return\n if (dataDashboard) {\n if (sellersId) {\n setTotalCommission(\n dataDashboard.searchSellersDashboard.statistics.totalComission\n )\n setTotalAmout(\n dataDashboard.searchSellersDashboard.statistics.totalOrderValue\n )\n setTotalOrder(\n dataDashboard.searchSellersDashboard.statistics.ordersCount\n )\n } else {\n setTotalCommission(0)\n setTotalAmout(0)\n setTotalOrder(0)\n }\n\n if (!dataDashboard.searchSellersDashboard.sellers.length) setTotalItems(0)\n else {\n const total = dataSellers ? dataSellers.getSellers.sellers.length : 0\n\n setTotalItems(total)\n }\n\n const dataTableDashboard: DataSeller[] = []\n\n setPage(dataDashboard.searchSellersDashboard.pagination.currentPage)\n dataDashboard.searchSellersDashboard.sellers.forEach(\n (item: DataDashboardSeller) => {\n dataTableDashboard.push({\n id: item.id,\n name: item.name,\n ordersCount: item.statistics.ordersCount.toString(),\n totalComission: item.statistics.totalComission.toFixed(2),\n totalOrderValue: item.statistics.totalOrderValue.toFixed(2),\n })\n }\n )\n setSellersDashboard(dataTableDashboard)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dashboard, dataDashboard])\n\n useEffect(() => {\n stats()\n // eslint-disable-next-line vtex/prefer-early-return\n if (dataStats) {\n let valueSellersStats = 0\n const getStatistics = dataStats.searchStatisticsDashboard.statistics\n let totalStats = 0\n\n if (dataDashboard) {\n valueSellersStats = dataDashboard.searchSellersDashboard.sellers.length\n totalStats =\n valueSellersStats <= 0\n ? 0\n : totalItemsFilter > 0\n ? totalItemsFilter\n : totalItems\n\n if (\n getStatistics.ordersCount === 0 &&\n getStatistics.totalComission === 0 &&\n getStatistics.totalOrderValue === 0\n ) {\n setSellersDashboard([])\n setTotalItems(0)\n setOptionsSelect([])\n }\n }\n\n // TODO: Change labels to FormattedText components\n setStatsTotalizer([\n {\n label: 'Number of Sellers',\n value: totalStats,\n iconBackgroundColor: '#EAFCE3',\n icon: <IconUser color=\"#79B03A\" size={18} />,\n },\n {\n label: 'Total Orders',\n value: sellersId\n ? totalOrder\n : dataStats.searchStatisticsDashboard.statistics.ordersCount,\n iconBackgroundColor: '#CCE8FF',\n icon: <IconShoppingCart color=\"#368DF7\" size={18} />,\n },\n {\n label: 'Total Amount Orders',\n value: sellersId\n ? `$${totalAmount}`\n : `$${dataStats.searchStatisticsDashboard.statistics.totalOrderValue\n .toFixed(2)\n .toString()}`,\n iconBackgroundColor: '#FFDCF8',\n icon: <IconArrowUp color=\"#F67CC7\" size={14} />,\n },\n {\n label: 'Total Commission',\n value: sellersId\n ? `$${totalCommission}`\n : `$${dataStats.searchStatisticsDashboard.statistics.totalComission\n .toFixed(2)\n .toString()}`,\n iconBackgroundColor: '#FFF0EC',\n icon: <IconInfo color=\"#F7634A\" size={14} />,\n },\n ])\n }\n }, [\n dataDashboard,\n dataStats,\n sellersId,\n stats,\n totalAmount,\n totalCommission,\n totalItems,\n totalItemsFilter,\n totalOrder,\n ])\n\n const formatDate = (valueDate: number) => {\n const validateDate = valueDate <= 9 ? `0${valueDate}` : valueDate\n\n return validateDate\n }\n\n useEffect(() => {\n const defaultDate = new Date()\n let defaultStart: Date = new Date()\n const defaultfinal = new Date(\n defaultDate.getFullYear(),\n defaultDate.getMonth(),\n defaultDate.getDate() - 1\n )\n\n const defaultFinalString = `${defaultfinal.getFullYear()}-${formatDate(\n defaultfinal.getMonth() + 1\n )}-${formatDate(defaultfinal.getDate())}`\n\n if (defaultDate.getDate() <= 1) {\n defaultStart = new Date(\n defaultDate.getFullYear(),\n defaultDate.getMonth() - 1,\n 1\n )\n } else {\n defaultStart = new Date(\n defaultDate.getFullYear(),\n defaultDate.getMonth(),\n 1\n )\n }\n\n const defaultStartString = `${defaultStart.getFullYear()}-${formatDate(\n defaultStart.getMonth() + 1\n )}-${formatDate(defaultStart.getDate())}`\n\n setStartDate(defaultStartString)\n setFinalDate(defaultFinalString)\n\n // eslint-disable-next-line vtex/prefer-early-return\n if (dataSellers) {\n const builtSelectSeller: SellerSelect[] = []\n\n dataSellers.getSellers?.sellers.forEach((seller: DataSellerSelect) => {\n builtSelectSeller.push({\n value: { id: seller.id, name: seller.name },\n label: seller.name,\n })\n })\n setOptionsSelect(builtSelectSeller)\n setTotalItems(dataSellers.getSellers.sellers.length)\n }\n }, [dataSellers])\n\n const onNextClick = () => {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n const nextPage = page + 1\n\n const currentTo = pageSize * nextPage\n const currentFrom = itemTo + 1\n\n setItemTo(currentTo)\n setItemFrom(currentFrom)\n setPage(nextPage)\n }\n\n const changeRows = (row: number) => {\n setPageSize(row)\n setItemTo(row)\n setItemFrom(1)\n setPage(1)\n }\n\n const onPrevClick = () => {\n const previousPage = page - 1\n\n const currentTo = itemTo - pageSize\n const currentFrom = itemFrom - pageSize\n\n setItemTo(currentTo)\n setItemFrom(currentFrom)\n setPage(previousPage)\n }\n\n const sorting = (dataSorting: SortObj) => {\n setOrderSort(`${dataSorting.by} ${dataSorting.order}`)\n }\n\n const filterDates = (start: string, final: string) => {\n setStartDate(start)\n setFinalDate(final)\n }\n\n return (\n <Layout\n pageHeader={\n <PageHeader title={<FormattedMessage id=\"admin/navigation.title\" />} />\n }\n >\n <div className=\"w-100 flex justify-end\">\n <ButtonWithIcon\n icon={<IconCog color=\"#979899\" />}\n variation=\"tertiary\"\n onClick={() => setModalColumns(true)}\n />\n </div>\n {modalColumns && <Modal\n centered\n isOpen={modalColumns}\n onClose={() => setModalColumns(false)}\n >\n <p>Choose the columns to display</p>\n <Divider orientation=\"horizontal\" />\n {schemaTable.forEach((itemColum) => {\n const validateCheck = hideColumns.find(\n (item) => item === itemColum.id\n ) || false\n const key = itemColum.id\n columnModal.push(\n <div className=\"mt3\">\n <Toggle\n id={itemColum.id}\n label={intl.formatMessage(idMessage[key])}\n checked={validateCheck}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) => {\n hideShowColumns(e.target.id)\n }}\n />\n <div className=\"mt3\">\n <Divider orientation=\"horizontal\" />\n </div>\n </div>\n )\n })}\n {columnModal}\n </Modal>}\n {startDate && finalDate && (\n <div className=\"mt2\">\n <PageBlock>\n <div className=\"mt4\">\n <Filter\n defaultDate={dateDefaultPicker}\n optionsSelect={optionsSelect}\n setSellerId={setSellersId}\n multiValue={true}\n filterDates={filterDates}\n setTotalItems={setTotalItemsFilter}\n />\n </div>\n </PageBlock>\n </div>\n )}\n <div className=\"mt2\">\n <PageBlock>\n <div className=\"mt4 mb5\">\n <Totalizer item={statsTotalizer} loading={loadingStats} />\n </div>\n </PageBlock>\n </div>\n <div className=\"mt2\">\n <PageBlock>\n <div>\n <TableComponent\n schemaTable={schemaTable}\n items={sellersDashboard}\n loading={loadingDataDashboard}\n sorting={sorting}\n hiddenColumn={hideColumns}\n />\n <PaginationComponent\n setPageSize={setPageSize}\n currentPage={itemFrom}\n pageSize={itemTo}\n setPage={setPage}\n totalItems={totalItemsFilter > 0 ? totalItemsFilter : totalItems}\n onNextClick={onNextClick}\n changeRows={changeRows}\n onPrevClick={onPrevClick}\n />\n </div>\n </PageBlock>\n </div>\n </Layout>\n )\n}\n\nexport default CommissionReport\n\n```" } ]
code_components-financial-commission_51045177
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/filter.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport FilterComponent from './components/Filter'\n\nexport default FilterComponent\n\n```" } ]
code_components-financial-commission_af688c33
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/package.json from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"components-financial-commission\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"date-fns\": \"^2.28.0\",\n \"handlebars\": \"^4.7.7\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.4/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.1/public/@types/vtex.styleguide\"\n }\n}\n\n```" } ]
code_components-financial-commission_5cf3df19
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/constants.ts from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ntype StatusOptions = {\n [key: string]: {\n bgColor: string\n fontColor: string\n }\n}\n\nexport const status: StatusOptions = {\n 'waiting-for-sellers-confirmation': {\n bgColor: '#134CD8',\n fontColor: '#FFF',\n },\n 'payment-pending': {\n bgColor: '#134CD8',\n fontColor: '#FFF',\n },\n 'payment-approved': {\n bgColor: '#8BC34A',\n fontColor: '#FFF',\n },\n 'ready-for-handling': {\n bgColor: '#134CD8',\n fontColor: '#FFF',\n },\n handling: {\n bgColor: '#134CD8',\n fontColor: '#FFF',\n },\n invoiced: {\n bgColor: '#134CD8',\n fontColor: '#FFF',\n },\n canceled: {\n bgColor: '#FF4C4C',\n fontColor: '#FFF',\n },\n}\n\nconst formatDate = (valueDate: number) => {\n const validateDate = valueDate <= 9 ? `0${valueDate}` : valueDate\n\n return validateDate\n}\n\nconst defaultDate = new Date()\nlet defaultStart: Date = new Date()\nconst defaultfinal = new Date(\n defaultDate.getFullYear(),\n defaultDate.getMonth(),\n defaultDate.getDate()\n)\n\nexport const defaultFinalString = `${defaultfinal.getFullYear()}-${formatDate(\n defaultfinal.getMonth() + 1\n)}-${formatDate(defaultfinal.getDate())}`\n\nif (defaultDate.getDate() <= 1) {\n defaultStart = defaultfinal\n} else {\n defaultStart = new Date(\n defaultDate.getFullYear(),\n defaultDate.getMonth(),\n 1\n )\n}\n\nexport const defaultStartString = `${defaultStart.getFullYear()}-${formatDate(\n defaultStart.getMonth() + 1\n)}-${formatDate(defaultStart.getDate())}`\n\n```" } ]
code_components-financial-commission_27abe159
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/invoiceDetail.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport Handlebars from 'handlebars'\nimport type { FC } from 'react'\nimport React, { useEffect, useState } from 'react'\nimport { useQuery, useMutation } from 'react-apollo'\nimport { FormattedMessage } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { Alert, Button, Layout, PageHeader, Spinner } from 'vtex.styleguide'\nimport type { DocumentNode } from 'graphql'\n\ninterface InvoiceDetailProps {\n invoiceQuery: DocumentNode\n getTemplate: DocumentNode\n sendEmail: DocumentNode\n}\n\nconst InvoiceDetail: FC<InvoiceDetailProps> = (props) => {\n const { invoiceQuery, getTemplate, sendEmail } = props\n\n const { route } = useRuntime()\n const { params } = route\n const { id } = params\n\n const [emailSent, setEmailSent] = useState(false)\n const [template, setTemplate] = useState('')\n const [invoice, setInvoice] = useState<Invoice>({})\n const [sendEmailFunc, { data: emailData }] = useMutation(sendEmail)\n\n const { data } = useQuery(invoiceQuery, {\n ssr: false,\n pollInterval: 0,\n variables: {\n id,\n },\n })\n\n const templateSrc = useQuery(getTemplate, {\n ssr: false,\n pollInterval: 0,\n })\n\n useEffect(() => {\n setTemplate(templateSrc?.data?.getTemplate)\n }, [templateSrc, template])\n\n useEffect(() => {\n if (emailData) {\n setEmailSent(true)\n }\n }, [emailData])\n\n useEffect(() => {\n setInvoice(data?.getInvoice)\n }, [data])\n\n if (!template) {\n return (\n <div style={{ position: 'absolute', top: '50%', left: '50%' }}>\n <Spinner />\n </div>\n )\n }\n\n const hbTemplate = Handlebars.compile(template)\n const htmlString = hbTemplate({ id, ...invoice })\n\n const handleSendEmail = () => {\n sendEmailFunc({\n variables: {\n emailData: {\n email: invoice?.seller.contact.email,\n jsonData: JSON.stringify(invoice),\n },\n },\n })\n }\n\n return (\n <Layout>\n <PageHeader title=\"Invoice Detail\">\n {emailSent ? (\n <Alert type=\"success\">\n {<FormattedMessage id=\"admin/email-success\" />}\n </Alert>\n ) : (\n <Button onClick={handleSendEmail}>\n <FormattedMessage id=\"admin/form-settings.button-email\" />\n </Button>\n )}\n </PageHeader>\n <div\n style={{\n position: 'relative',\n overflow: 'hidden',\n width: '100%',\n paddingTop: '100%',\n }}\n >\n <iframe\n srcDoc={htmlString}\n title=\"invoice detail\"\n style={{\n position: 'absolute',\n top: 0,\n left: 0,\n bottom: 0,\n right: 0,\n width: '100%',\n height: '100%',\n border: 'none',\n }}\n />\n </div>\n </Layout>\n )\n}\n\nexport default InvoiceDetail\n\n```" } ]
code_components-financial-commission_3b1a7d25
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/table.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport TableComponent from './components/Table'\n\nexport default TableComponent\n\n```" } ]
code_components-financial-commission_9173a7cb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/detail.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable jsx-a11y/anchor-is-valid */\n/* eslint-disable react/display-name */\nimport type { FC } from 'react'\nimport React, { useEffect, useState } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport {\n Divider,\n Layout,\n Modal,\n PageBlock,\n PageHeader,\n Tab,\n Tabs,\n} from 'vtex.styleguide'\n\nimport Orders from './components/Orders'\nimport SellerInvoices from './components/SellerInvoices'\nimport SellerOrders from './components/SellerOrders'\nimport { Filter } from './components'\nimport { status, defaultStartString, defaultFinalString } from './constants'\n\nconst dateDefaultPicker = {\n startDatePicker: new Date(`${defaultStartString}T00:00:00`),\n finalDatePicker: new Date(`${defaultFinalString}T00:00:00`),\n defaultStartDate: defaultStartString,\n defaultFinalDate: defaultFinalString,\n today: true,\n}\n\nconst CommissionReportDetail: FC<DetailProps> = (props) => {\n const {\n account,\n ordersQuery,\n invoiceMutation,\n dataSellers,\n invoicesQuery,\n settingsQuery,\n } = props\n\n const [startDate, setStartDate] = useState('')\n const [finalDate, setFinalDate] = useState('')\n const [optionsSelect, setOptionsSelect] = useState<SellerSelect[]>([])\n const [sellerName, setSellerName] = useState(account ?? '')\n const [sellerId, setSellerId] = useState('')\n const [tabs, setTabs] = useState(1)\n const [openModal, setOpenModal] = useState(false)\n const [dateRate, setDataRate] = useState<dateRateType[]>([])\n const [optionsStatus, setOptionsStatus] = useState<SellerSelect[]>([])\n const [statusOrders, setStatusOrders] = useState('')\n const [tableOrders, setTableOrders] = useState<TableOrdersType[]>([])\n const [tableInvoices, setTableInvoices] = useState<Invoice[]>([])\n\n const formatDate = (valueDate: number) => {\n const validateDate = valueDate <= 9 ? `0${valueDate}` : valueDate\n\n return validateDate\n }\n\n useEffect(() => {\n // eslint-disable-next-line vtex/prefer-early-return\n if (dataSellers) {\n const builtSelectSeller: SellerSelect[] = []\n\n dataSellers.getSellers.sellers.forEach((seller: DataSellerSelect) => {\n builtSelectSeller.push({\n value: { id: seller.id, name: seller.name },\n label: seller.name,\n })\n })\n setOptionsSelect(builtSelectSeller)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dataSellers])\n\n useEffect(() => {\n if (!optionsStatus.length) {\n const buildSelectStatus: SellerSelect[] = []\n\n Object.keys(status).forEach((orderStatus) => {\n buildSelectStatus.push({\n value: { id: orderStatus, name: orderStatus },\n label: orderStatus,\n })\n })\n setOptionsStatus(buildSelectStatus)\n }\n }, [optionsStatus])\n\n useEffect(() => {\n const defaultDate = new Date()\n let defaultStart: Date = new Date()\n const defaultfinal = new Date(\n defaultDate.getFullYear(),\n defaultDate.getMonth(),\n defaultDate.getDate()\n )\n\n const defaultFinalString = `${defaultfinal.getFullYear()}-${formatDate(\n defaultfinal.getMonth() + 1\n )}-${formatDate(defaultfinal.getDate())}`\n\n if (defaultDate.getDate() <= 1) {\n defaultStart = defaultfinal\n } else {\n defaultStart = new Date(\n defaultDate.getFullYear(),\n defaultDate.getMonth(),\n 1\n )\n }\n\n const defaultStartString = `${defaultStart.getFullYear()}-${formatDate(\n defaultStart.getMonth() + 1\n )}-${formatDate(defaultStart.getDate())}`\n\n setStartDate(defaultStartString)\n setFinalDate(defaultFinalString)\n }, [])\n\n const filterDates = (start: string, final: string) => {\n setStartDate(start)\n setFinalDate(final)\n }\n\n return (\n <Layout\n pageHeader={\n <PageHeader\n title={<FormattedMessage id=\"admin/navigation.detail-title\" />}\n />\n }\n >\n <Modal\n centered\n isOpen={openModal}\n onClose={() => setOpenModal(!openModal)}\n >\n <div className=\"mb3\">\n {dateRate.map((elmRate: dateRateType) => (\n <div key=\"elmRate\">\n <h2>Item ID: #{elmRate.itemId}</h2>\n <p>\n <b>Name Item: </b> {elmRate.nameItem}\n </p>\n <p>\n <b>Freight Commission Percentage: </b>\n {elmRate.rate.freightCommissionPercentage}%\n </p>\n <p>\n <b>Producto Commission Percentage: </b>\n {elmRate.rate.productCommissionPercentage}%\n </p>\n <Divider />\n </div>\n ))}\n </div>\n </Modal>\n <div className=\"mt4 mb7\">\n {startDate && finalDate && (\n <div className=\"mt2\">\n <PageBlock>\n <Filter\n defaultDate={dateDefaultPicker}\n optionsSelect={optionsSelect}\n filterDates={filterDates}\n setSellerId={setSellerName}\n setId={setSellerId}\n multiValue={false}\n optionsStatus={optionsStatus}\n setStatusOrders={setStatusOrders}\n disableSelect={Boolean(account)}\n />\n </PageBlock>\n </div>\n )}\n </div>\n <div className=\"mt7\">\n <Tabs fullWidth>\n <Tab\n label={<FormattedMessage id=\"admin/table.title-tab-commission\" />}\n active={tabs === 1}\n onClick={() => setTabs(1)}\n >\n <div className=\"mt5\">\n {settingsQuery ? (\n <SellerOrders\n ordersQuery={ordersQuery}\n account={account}\n sellerName={sellerName}\n startDate={startDate}\n finalDate={finalDate}\n statusOrders={statusOrders}\n setDataRate={setDataRate}\n sellerId={sellerId}\n invoiceMutation={invoiceMutation}\n setOpenModal={setOpenModal}\n openModal={openModal}\n settingsQuery={settingsQuery}\n dataTableOrders={tableOrders}\n setDataTableOrders={setTableOrders}\n validRange={defaultFinalString !== finalDate}\n />\n ) : (\n <Orders\n ordersQuery={ordersQuery}\n account={account}\n sellerName={sellerName}\n startDate={startDate}\n finalDate={finalDate}\n statusOrders={statusOrders}\n setDataRate={setDataRate}\n sellerId={sellerId}\n invoiceMutation={invoiceMutation}\n dataTableOrders={tableOrders}\n setDataTableOrders={setTableOrders}\n validRange={defaultFinalString !== finalDate}\n />\n )}\n </div>\n </Tab>\n <Tab\n label={<FormattedMessage id=\"admin/table.title-tab-invoices\" />}\n active={tabs === 2}\n onClick={() => setTabs(2)}\n >\n <div className=\"mt5\">\n <SellerInvoices\n invoicesQuery={invoicesQuery}\n account={account}\n sellerName={sellerName}\n startDate={startDate}\n finalDate={finalDate}\n dataTableInvoice={tableInvoices}\n setDataTableInvoice={setTableInvoices}\n />\n </div>\n </Tab>\n </Tabs>\n </div>\n </Layout>\n )\n}\n\nexport default CommissionReportDetail\n\n```" } ]
code_components-financial-commission_144d341e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/settingsDetail.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useState, useEffect } from 'react'\nimport {\n Layout,\n PageHeader,\n Button,\n EXPERIMENTAL_Select as Select,\n Box,\n EXPERIMENTAL_Table as Table,\n Alert,\n} from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { useMutation, useQuery } from 'react-apollo'\nimport { DocumentNode } from 'graphql'\nimport { TokenAuth } from './components'\n\nconst DATE_CUT_OPTIONS = [\n {\n value: 1,\n label: 'Daily',\n },\n {\n value: 30,\n label: 'Monthly',\n },\n]\n\ninterface SettingsDetailProps {\n createTokenMutation: DocumentNode\n editToken: DocumentNode\n getTokenQuery: DocumentNode\n createSettingsMutation: DocumentNode\n getSettingsQuery: DocumentNode\n}\n\nconst SettingsDetail: FC<SettingsDetailProps> = (props) => {\n const {\n createTokenMutation,\n editToken,\n getTokenQuery,\n createSettingsMutation,\n getSettingsQuery,\n } = props\n\n const { navigate, route, query } = useRuntime()\n\n const [selectedValue, setSelectValue] = useState<SelectObj | null>()\n const [openAlert, setOpenAlert] = useState(false)\n const [infoSettings, setInfoSettings] = useState<SettingInfoType[]>([])\n const [tokenSeller, setTokenSeller] = useState<any>({})\n\n const { data: getToken } = useQuery(getTokenQuery, {\n ssr: false,\n pollInterval: 0,\n fetchPolicy: 'no-cache',\n variables: {\n accountId: route.params.sellerId,\n },\n })\n\n const [createSettings, { data: dataSettings }] = useMutation(\n createSettingsMutation\n )\n\n const { data: settings } = useQuery(getSettingsQuery, {\n ssr: false,\n pollInterval: 0,\n variables: {\n id: tokenSeller.getToken ? tokenSeller.getToken.name : '',\n },\n })\n\n\n const handleSaveBilling = () => {\n if (selectedValue) {\n const nowDate = new Date()\n let date = ''\n let lastDateString = ''\n\n const month =\n nowDate.getMonth() + 1 <= 9\n ? `0${nowDate.getMonth() + 1}`\n : nowDate.getMonth() + 1\n\n if (selectedValue.label === 'Monthly') {\n const day =\n nowDate.getDate() < 10 ? `0${nowDate.getDate()}` : nowDate.getDate()\n\n date = `${nowDate.getFullYear()}-${month}-${day}`\n\n const lastDate = new Date(\n nowDate.getFullYear(),\n nowDate.getMonth() + 1,\n 0\n )\n\n const lastMonth =\n lastDate.getMonth() + 1\n ? `0${lastDate.getMonth() + 1}`\n : lastDate.getMonth() + 1\n\n const lastDay =\n lastDate.getDate() < 10\n ? `0${lastDate.getDate()}`\n : lastDate.getDate()\n\n lastDateString = `${lastDate.getFullYear()}-${lastMonth}-${lastDay}`\n } else {\n const day =\n nowDate.getDate() < 10 ? `0${nowDate.getDate()}` : nowDate.getDate()\n\n const finalDay =\n nowDate.getDate() + 1 < 10\n ? `0${nowDate.getDate() + 1}`\n : nowDate.getDate() + 1\n\n date = `${nowDate.getFullYear()}-${month}-${day}`\n lastDateString = `${nowDate.getFullYear()}-${month}-${finalDay}`\n }\n createSettings({\n variables: {\n settingsData: {\n sellerName: query.name,\n startDate: date,\n endDate: lastDateString,\n billingCycle: selectedValue.label,\n },\n },\n })\n }\n }\n\n useEffect(() => {\n if (dataSettings) {\n setInfoSettings([\n {\n idbilling: dataSettings.createSettings.billingCycle,\n start: dataSettings.createSettings.startDate,\n end: dataSettings.createSettings.endDate,\n },\n ])\n\n setOpenAlert(true)\n }\n }, [dataSettings])\n\n useEffect(() => {\n if (settings) {\n setInfoSettings([\n {\n idbilling: settings.getSettings.billingCycle,\n start: settings.getSettings.startDate,\n end: settings.getSettings.endDate,\n },\n ])\n setSelectValue({\n value: 30,\n label: settings.getSettings.billingCycle,\n })\n }\n }, [settings])\n\n useEffect(() => {\n if (getToken) setTokenSeller(getToken)\n }, [getToken])\n\n return (\n <Layout\n pageHeader={\n <PageHeader\n title={\n <FormattedMessage\n id=\"admin/navigation.setting\"\n values={{ name: query?.name }}\n />\n }\n linkLabel={<FormattedMessage id=\"admin/navigation.settings\" />}\n onLinkClick={() => {\n navigate({\n to: `/admin/app/commission-report/settings/`,\n })\n }}\n />\n }\n >\n {(tokenSeller) && (\n <TokenAuth activateToogle={false} editToken={editToken} createTokenMutation={createTokenMutation} sellerId={route.params.sellerId} tokenSeller={tokenSeller} />\n )}\n {query?.integration === 'true' && (\n <div className=\"mt4\">\n <Box>\n <h2 className=\"mt0 mb6\">Billing cycle</h2>\n <div className=\"mb5 flex w-100\">\n <div className=\"w-90\">\n <Select\n menuPosition=\"fixed\"\n options={DATE_CUT_OPTIONS}\n value={selectedValue}\n multi={false}\n onChange={(values: SelectObj) => {\n setSelectValue(values)\n }}\n />\n </div>\n <div className=\"w-10 pl2\">\n <Button\n variation=\"primary\"\n onClick={handleSaveBilling}\n >\n SAVE\n </Button>\n </div>\n </div>\n <div className=\"w-100\">\n <p className=\"t-small w-100 c-muted-1\">\n <FormattedMessage id=\"admin/modal-settings.billingCycle-helpText\" />\n </p>\n </div>\n {openAlert ? (\n <div className=\"mt7\">\n <Alert type=\"success\" onClose={() => setOpenAlert(false)}>\n Data was updated successfully\n </Alert>\n </div>\n ) : (\n <div />\n )}\n <div className=\"mt7\">\n <Table\n stickyHeader\n measures={[]}\n items={infoSettings}\n columns={[\n {\n id: 'idbilling',\n title: 'Billing Cycle',\n },\n {\n id: 'start',\n title: 'Start Date',\n },\n {\n id: 'end',\n title: 'End Date',\n },\n ]}\n />\n </div>\n </Box>\n </div>\n )}\n </Layout>\n )\n}\n\nexport default SettingsDetail\n\n```" } ]
code_components-financial-commission_669f116b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/typings/gql.d.ts from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n import { DocumentNode } from 'graphql'\n\n const Schema: DocumentNode\n\n export default Schema\n}\n\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const schema: DocumentNode\n\n export default Schema\n}\n\n```" } ]
code_components-financial-commission_6c995017
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/typings/global.d.ts from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime'\ninterface Invoice {\n comment?: string\n invoiceCreateDate?: string\n orders?: [Order]\n seller?: Seller\n status?: string\n totalizers?: Totalizers\n}\ninterface Order {\n orderId: string\n sellerOrderId: string\n totalComission: number\n totalOrderRate: number\n totalOrderValue: number\n}\ninterface DateFilter {\n startDateFilter: Date\n finalDateFilter: Date\n dataFilter: SellerSelect[]\n statusFilter: SellerSelect[]\n}\ninterface CellRendererProps {\n data: string\n density: string\n motion: {\n transaction: string\n willChange: string\n }\n rowHeight: number\n}\ninterface DataSellerSelect {\n account: string\n freightCommissionPercentage: number\n id: string\n isActive: boolean\n name: string\n productCommissionPercentage: number\n}\ninterface ModalConfirmData {\n buttonMessage: any\n messages: MessagesData\n sellerData: SellerData\n invoiceMutation: any\n disabled: boolean\n integration?: string\n}\ninterface MessagesData {\n confirmation: any\n warning: any\n}\ninterface SellerData {\n startDate: string\n finalDate: string\n sellerName: string\n id: string\n}\ninterface TableData {\n items: any\n schemaTable: SchemaTable[]\n loading: boolean\n sorting?: any\n hiddenColumn?: string[]\n}\ninterface SchemaTable {\n id: string\n title: JSX.Element\n cellRenderer?: (props: CellRendererProps) => void\n}\ninterface CellRendererProps {\n data: string\n density: string\n motion: {\n transaction: string\n willChange: string\n }\n rowHeight: number\n}\ninterface FilterProps {\n defaultDate?: {\n startDatePicker: Date\n finalDatePicker: Date\n defaultStartDate: string\n defaultFinalDate: string\n today: boolean\n }\n optionsSelect: SellerSelect[]\n filterDates?: (v: string, x: string) => void\n setTotalItems?: (v: number) => void\n setPages?: (v: number) => void\n setSellerId: (v: string) => void\n setId?: (v: string) => void\n multiValue: boolean\n optionsStatus?: SellerSelect[]\n setStatusOrders?: (v: string) => void\n disableSelect?: boolean\n}\ninterface StatsTotalizer {\n label: any\n value: any\n iconBackgroundColor?: string\n icon?: any\n}\ninterface DataSeller {\n id: string\n name: string\n ordersCount: string\n totalComission: string\n totalOrderValue: string\n}\ninterface DataDashboardSeller {\n account: string\n id: string\n name: string\n statistics: DataStatistics\n}\ninterface SellerSelect {\n label: string\n value: {\n id: string\n name: string\n }\n}\ninterface SelectProps {\n options: SellerSelect[]\n dataFilter: SellerSelect[]\n setDataFilter: (v: SellerSelect[]) => void\n multi: boolean\n customLabel: any\n}\ninterface DatepickerProps {\n startDatePicker: Date\n finalDatePicker: Date\n changeDate: (date: Date, type: string) => void\n today: boolean\n}\ninterface PaginationProps {\n setPageSize: (v: number) => void\n currentPage: number\n pageSize: number\n setPage: (v: number) => void\n totalItems: number\n onNextClick: () => void\n changeRows: (row: number) => void\n onPrevClick: () => void\n}\ninterface SettingsSellers {\n id: string\n name: string\n}\ninterface DataSeller {\n id: string\n name: string\n ordersCount: string\n totalComission: string\n totalOrderValue: string\n}\ninterface Pagination {\n currentPage: number\n pageSize: number\n totalPage: number\n}\ninterface DetailProps {\n account?: string\n dataSellers?: {\n getSellers: {\n pagination: Pagination\n sellers: [DataSellerSelect]\n }\n }\n ordersQuery: DocumentNode\n invoiceMutation: DocumentNode\n invoicesQuery: DocumentNode\n settingsQuery?: DocumentNode\n}\n\ntype SellerSettingsToken = Partial<TokenConfiguration>\ninterface MessageType {\n [key: string]: { id: string }\n}\ninterface rateType {\n freightCommissionPercentage: number\n productCommissionPercentage: number\n}\ninterface dateRateType {\n itemId: string\n nameItem: string\n rate: rateType\n}\ninterface StatusType {\n status: string\n bgColor: string\n fontColor: string\n}\ninterface TableOrdersType {\n creationDate: string\n id: string\n rate: [rateType]\n status: StatusType\n totalCommission: number\n totalOrder: number\n}\n\ninterface TableDataOrder {\n creationDate: string\n marketplaceOrderId: string | null\n orderId: string\n rate: [rateType]\n sellerOrderId: string\n status: string\n statusDescription: string\n totalComission: number\n totalOrderValue: number\n}\ninterface SortObj {\n by: string\n order: string\n}\ninterface SelectObj {\n value: number\n label: string\n}\ninterface SettingInfoType {\n idbilling: string\n start: string\n end: string\n}\ninterface responseToken {\n getToken: {\n autheticationToken: string,\n enabled: boolean\n name: string\n }\n}\ninterface TokenAuthProps {\n activateToogle: Boolean\n sellerId: string\n editToken: DocumentNode\n createTokenMutation: DocumentNode\n tokenSeller: responseToken\n}\ninterface DataActions {\n id: string\n name: string\n}\n\ninterface ResponseFilter {\n stringId: string\n sellerFilter: string\n countTotalItems: number\n sellerId: string\n}\n\n```" } ]
code_components-financial-commission_858b15b1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/typings/css.d.ts from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n type Styles = {\n [selector: string]: string\n }\n\n const styles: Styles\n\n export default styles\n}\n\n```" } ]
code_components-financial-commission_638a87a5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/utils/calculateDate.ts from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst now = new Date()\n\nexport const getDateString = (date: Date) => {\n const month = date.getMonth() + 1\n const monthString = month <= 9 ? `0${month}` : month\n const day = date.getDate()\n const dayString = day <= 9 ? `0${day}` : day\n\n return `${date.getFullYear()}-${monthString}-${dayString}`\n}\n\nexport const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)\nnow.setDate(now.getDate() - 1)\nexport const yesterday = now\nexport const today = new Date()\nif (yesterday.getMonth() < today.getMonth() || yesterday.getMonth() < firstDay.getMonth()) {\n firstDay.setMonth(now.getMonth())\n}\n\nexport const filterEmptyObj = (obj: any) => {\n Object.keys(obj).forEach(key => {\n if (obj[key] === '') {\n delete obj[key];\n }\n })\n return obj\n}\n\nexport const filterSellerValues = (data: SellerSelect[], status: boolean) => {\n let stringId = '', countTotalItems = 0, sellerFilter = '', sellerId = ''\n data.forEach((item: SellerSelect) => {\n stringId += status ? `${item.label},` : `${item.value.id},`\n sellerFilter += `${item.label},`\n countTotalItems += 1\n sellerId += `${item.value.id},`\n })\n\n return { stringId, sellerFilter, countTotalItems, sellerId }\n}\n\n```" } ]
code_components-financial-commission_79f9b8ec
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/index.ts from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport Filter from './Filter'\nimport Totalizer from './Dashboard/Totalizer'\nimport TokenAuth from './TokenAuth'\n\nexport { Filter, Totalizer, TokenAuth }\n\n```" } ]
code_components-financial-commission_bf01e4fc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/TokenAuth/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useState, useEffect } from 'react'\nimport {\n Input,\n Button,\n Toggle,\n Box,\n} from 'vtex.styleguide'\nimport { useMutation } from 'react-apollo'\nimport { FormattedMessage } from 'react-intl'\n\nconst TokenAuth: FC<TokenAuthProps> = (props) => {\n const [\n sellerSettingsToken,\n setSellerSettingsToken,\n ] = useState<SellerSettingsToken>({})\n\n const {\n editToken,\n createTokenMutation,\n } = props\n\n const [editTokenMutation] = useMutation(editToken)\n\n const [\n authenticationToken,\n { data: createToken, loading: loadingCreateToken },\n ] = useMutation(createTokenMutation)\n\n const handleIsEnable = () => {\n setSellerSettingsToken({\n ...sellerSettingsToken,\n enabled: !sellerSettingsToken.enabled,\n })\n /*authenticationToken: !sellerSettingsToken.enabled\n ? sellerSettingsToken.authenticationToken\n : '',*/\n editTokenMutation({\n variables: {\n sellerId: props.sellerId,\n isEnable: !sellerSettingsToken.enabled,\n },\n })\n }\n\n const handleCreateToken = () => {\n authenticationToken({ variables: { accountId: props.sellerId } })\n }\n\n useEffect(() => {\n // eslint-disable-next-line vtex/prefer-early-return\n if (createToken) {\n const newToken = createToken.createToken.autheticationToken\n\n setSellerSettingsToken({\n ...sellerSettingsToken,\n authenticationToken: newToken,\n })\n }\n }, [createToken])\n\n return (\n <div className=\"mt7\">\n <Box>\n <h2 className=\"mt0 mb6\">Autentication Token</h2>\n <div className=\"mt2 mb8\">\n {props.activateToogle && (<Toggle\n label={sellerSettingsToken.enabled ? 'Activated' : 'Deactivated'}\n checked={sellerSettingsToken.enabled}\n semantic\n onChange={() => handleIsEnable()}\n />)}\n </div>\n <div className=\"mb5\">\n <Input\n placeholder=\"Token\"\n readOnly\n label=\"Seller Token\"\n value={sellerSettingsToken.authenticationToken ? sellerSettingsToken.authenticationToken : props.tokenSeller.getToken?.autheticationToken}\n />\n </div>\n <div className=\"mb4 flex justify-end \">\n <Button\n variation=\"primary\"\n loading={loadingCreateToken}\n onClick={() => handleCreateToken()}\n disabled={!sellerSettingsToken.enabled && props.activateToogle}\n >\n {<FormattedMessage id=\"admin/form-settings.button-new\" />}\n </Button>\n </div>\n </Box>\n </div>\n )\n}\n\nexport default TokenAuth\n\n```" } ]
code_components-financial-commission_8d517e41
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/SettingsTable/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useState } from 'react'\nimport {\n ButtonWithIcon,\n IconCog,\n Modal,\n Divider,\n Toggle,\n} from 'vtex.styleguide'\nimport { defineMessages, useIntl } from 'react-intl'\n// import { FormattedMessage } from 'react-intl'\n\ninterface SettingsTableData {\n schemaTable: any\n}\n\nconst idMessage: MessageType = defineMessages({\n actions: { id: \"admin/table-actions\" },\n totalComission: { id: \"admin/table-total-commission\" },\n totalOrderValue: { id: \"admin/table-total-amount\" },\n ordersCount: { id: \"admin/table-total-order\" },\n name: { id: \"admin/table-seller-name\" }\n})\n\nconst SettingsTable: FC<SettingsTableData> = (props) => {\n const intl = useIntl()\n const [hideColumns, setHideColumn] = useState<string[]>([])\n const [modalColumns, setModalColumns] = useState(false)\n let columnModal: JSX.Element[] = []\n\n const hideShowColumns = (e: string) => {\n\n let temp = [...hideColumns]\n if (temp.find(id => id === e)) {\n temp.splice(temp.indexOf(e), 1)\n } else {\n temp.push(e)\n }\n setHideColumn(temp)\n }\n return (\n <div>\n <div className='w-100 flex justify-end'>\n <ButtonWithIcon icon={<IconCog color=\"#979899\" />} variation=\"tertiary\" onClick={() => setModalColumns(true)} />\n </div>\n <Modal centered isOpen={modalColumns} onClose={() => setModalColumns(false)}>\n <p>Choose the columns to display</p>\n <Divider orientation=\"horizontal\" />\n {\n props.schemaTable.forEach((itemColum: any) => {\n const validateCheck = hideColumns.find(item => item === itemColum.id)\n const key = itemColum.id\n columnModal.push(<div className='mt3'>\n <Toggle id={itemColum.id} label={intl.formatMessage(idMessage[key])} onChange={(e: React.ChangeEvent<HTMLInputElement>) => hideShowColumns(e.target.id)} checked={validateCheck ? true : false} />\n <div className='mt3'><Divider orientation=\"horizontal\" /></div>\n </div>)\n\n })}\n {columnModal}\n\n </Modal>\n </div>\n )\n}\n\nexport default SettingsTable\n\n```" } ]
code_components-financial-commission_d00d408d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/SellerOrders/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useEffect, useState } from 'react'\nimport {\n ButtonWithIcon,\n IconVisibilityOff,\n PageBlock,\n Tag,\n} from 'vtex.styleguide'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { FormattedMessage } from 'react-intl'\nimport { useQuery } from 'react-apollo'\nimport type { DocumentNode } from 'graphql'\n\nimport { status } from '../../constants'\nimport ModalConfirm from '../ModalConfirm'\nimport TableComponent from '../Table'\nimport PaginationComponent from '../Table/pagination'\n\ninterface DetailProps {\n account?: string\n ordersQuery: DocumentNode\n invoiceMutation: DocumentNode\n settingsQuery: DocumentNode\n sellerName?: string\n startDate?: string\n finalDate?: string\n statusOrders?: string\n setDataRate: (data: dateRateType[]) => void\n sellerId?: string\n setOpenModal?: (open: boolean) => void\n openModal?: boolean\n dataTableOrders: TableOrdersType[]\n setDataTableOrders: (data: TableOrdersType[]) => void\n validRange: boolean\n}\n\nconst SellerOrders: FC<DetailProps> = ({\n account,\n sellerName,\n ordersQuery,\n settingsQuery,\n startDate,\n finalDate,\n statusOrders,\n setDataRate,\n sellerId,\n invoiceMutation,\n setOpenModal,\n openModal,\n dataTableOrders,\n setDataTableOrders,\n validRange,\n}) => {\n const { query } = useRuntime()\n const [page, setPage] = useState(1)\n const [pageSize, setPageSize] = useState(20)\n const [itemFrom, setItemFrom] = useState(1)\n const [itemTo, setItemTo] = useState(20)\n const [totalItems, setTotalItems] = useState(0)\n const [integration, setIntegration] = useState('')\n\n const { data: settings } = useQuery(settingsQuery, {\n ssr: false,\n pollInterval: 0,\n })\n\n useEffect(() => {\n if (settings) {\n setIntegration(settings.getSettings.integration)\n }\n }, [settings])\n\n const { data: dataOrders, loading: loadingDataOrders } = useQuery(\n ordersQuery,\n {\n ssr: false,\n pollInterval: 0,\n variables: {\n searchOrdersParams: {\n dateStart: startDate,\n dateEnd: finalDate,\n sellerName,\n page,\n perpage: pageSize,\n status: statusOrders,\n },\n },\n }\n )\n\n const IDCell = (props: CellRendererProps) => {\n return (\n // eslint-disable-next-line jsx-a11y/anchor-is-valid\n <a\n href={`admin/checkout/#/orders/${props.data}`}\n style={{ color: '#0C389F' }}\n target=\"_blank\"\n rel=\"noreferrer\"\n >\n {props.data}\n </a>\n )\n }\n\n const TotalOrderCell = (props: CellRendererProps) => {\n return <span>${props.data}</span>\n }\n\n const TotalCommissionCell = (props: CellRendererProps) => {\n return <span>${props.data}</span>\n }\n\n const RateCell = (props: any) => {\n return (\n <div>\n <ButtonWithIcon\n icon={<IconVisibilityOff />}\n variation=\"tertiary\"\n onClick={() => {\n if (setOpenModal) setOpenModal(!openModal)\n setDataRate(props.data)\n }}\n />\n </div>\n )\n }\n\n const StatusCell = (props: any) => {\n return (\n <Tag bgColor={props.data.bgColor} color={props.data.fontColor}>\n {props.data.status}\n </Tag>\n )\n }\n\n const schemaTable = [\n {\n id: 'id',\n title: <FormattedMessage id=\"admin/table-seller-order\" />,\n cellRenderer: IDCell,\n },\n {\n id: 'creationDate',\n title: <FormattedMessage id=\"admin/table-creation-order\" />,\n },\n {\n id: 'totalOrder',\n title: <FormattedMessage id=\"admin/table-total-order\" />,\n cellRenderer: TotalOrderCell,\n },\n {\n id: 'totalCommission',\n title: <FormattedMessage id=\"admin/table-commission-order\" />,\n cellRenderer: TotalCommissionCell,\n },\n {\n id: 'rate',\n title: <FormattedMessage id=\"admin/table-rate-order\" />,\n cellRenderer: RateCell,\n },\n {\n id: 'status',\n title: <FormattedMessage id=\"admin/table-seller-status\" />,\n cellRenderer: StatusCell,\n },\n ]\n\n const changeRows = (row: number) => {\n setPageSize(row)\n setItemTo(row)\n setItemFrom(1)\n setPage(1)\n }\n\n const onNextClick = () => {\n const nextPage = page + 1\n\n const currentTo = pageSize * nextPage\n const currentFrom = itemTo + 1\n\n setItemTo(currentTo)\n setItemFrom(currentFrom)\n setPage(nextPage)\n }\n\n const onPrevClick = () => {\n const previousPage = page - 1\n\n const currentTo = itemTo - pageSize\n const currentFrom = itemFrom - pageSize\n\n setItemTo(currentTo)\n setItemFrom(currentFrom)\n setPage(previousPage)\n }\n\n useEffect(() => {\n if (sellerName === '' && !query?.sellerName) {\n setDataTableOrders([])\n setTotalItems(0)\n }\n }, [query, sellerName, setDataTableOrders])\n\n useEffect(() => {\n if (dataOrders) {\n const dataTable: TableOrdersType[] = []\n\n dataOrders.orders.data.forEach((item: TableDataOrder) => {\n const keyColor = Object.keys(status).find(\n (itemStatus: string) => itemStatus === item.status\n )\n\n dataTable.push({\n id: account ? item.sellerOrderId : item.orderId,\n creationDate: item.creationDate.substring(\n 0,\n item.creationDate.indexOf('T')\n ),\n totalOrder: item.totalOrderValue,\n totalCommission: item.totalComission,\n rate: item.rate,\n status: {\n status: item.status,\n bgColor: keyColor ? status[keyColor].bgColor : '',\n fontColor: keyColor ? status[keyColor].fontColor : '',\n },\n })\n })\n if (sellerName === '') setDataTableOrders([])\n else setDataTableOrders(dataTable)\n setTotalItems(dataOrders.orders.paging.total)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dataOrders, sellerName])\n\n return (\n <PageBlock>\n {account ? null : (\n <ModalConfirm\n integration={integration}\n invoiceMutation={invoiceMutation}\n disabled={\n !(\n statusOrders === 'invoiced' &&\n dataOrders?.orders.data.length &&\n validRange\n )\n }\n buttonMessage={\n <FormattedMessage id=\"admin/form-settings.button-invoice\" />\n }\n messages={{\n warning: <FormattedMessage id=\"admin/modal-setting.warning\" />,\n confirmation: (\n <FormattedMessage id=\"admin/modal-setting.confirmation\" />\n ),\n }}\n sellerData={{\n startDate: startDate ?? '',\n finalDate: finalDate ?? '',\n sellerName: sellerName ?? '',\n id: sellerId ?? '',\n }}\n />\n )}\n <div className=\"mt2\">\n <TableComponent\n schemaTable={schemaTable}\n items={dataTableOrders}\n loading={loadingDataOrders}\n />\n <PaginationComponent\n setPageSize={setPageSize}\n currentPage={itemFrom}\n pageSize={itemTo}\n setPage={setPage}\n totalItems={totalItems}\n onNextClick={onNextClick}\n changeRows={changeRows}\n onPrevClick={onPrevClick}\n />\n </div>\n </PageBlock>\n )\n}\n\nexport default SellerOrders\n\n```" } ]
code_components-financial-commission_fa91cb12
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/ModalConfirm/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useState } from 'react'\nimport { useMutation } from 'react-apollo'\nimport { FormattedMessage } from 'react-intl'\nimport { Alert, Button, Input, ModalDialog, Spinner } from 'vtex.styleguide'\n\nimport styles from '../../styles.css'\n\nconst ModalConfirm: FC<ModalConfirmData> = (props) => {\n const [email, setEmail] = useState('')\n const [isModalOpen, setIsModalOpen] = useState(false)\n const [validEmail, setValidEmail] = useState(true)\n const [empty, setEmpty] = useState(true)\n\n const EMAIL_PATTERN = /^\\w+([.-]?\\w+)*@\\w+([.-]?\\w+)*(\\.\\w{2,3})+$/\n\n const checkEmail = (emailAddress: string) => {\n const valid = EMAIL_PATTERN.test(emailAddress)\n\n if (!emailAddress) {\n setEmpty(true)\n\n return\n }\n\n setEmpty(false)\n if (!valid) {\n setValidEmail(false)\n } else {\n setValidEmail(true)\n }\n }\n\n const [createInvoice, { data, loading, error }] = useMutation(\n props.invoiceMutation\n )\n\n const getErrorMessage = () => {\n if (empty) {\n return <FormattedMessage id=\"admin/modal-settings.email-empty\" />\n }\n\n if (!validEmail) {\n return <FormattedMessage id=\"admin/modal-settings.email-invalid\" />\n }\n\n return null\n }\n\n const handleCreateInvoice = (\n startDate: string,\n finalDate: string,\n name: string,\n id: string,\n emailAddress: string\n // eslint-disable-next-line max-params\n ) => {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n createInvoice({\n variables: {\n invoiceData: {\n name,\n id,\n email: emailAddress,\n startDate,\n endDate: finalDate,\n },\n },\n })\n }\n\n if (loading) {\n return (\n <div className=\"mb5 flex justify-center\">\n <Spinner />\n </div>\n )\n }\n\n if (data) {\n return (\n <Alert type=\"success\">\n {<FormattedMessage id=\"admin/invoice-success\" />}\n </Alert>\n )\n }\n\n if (error) {\n return (\n <Alert type=\"error\">\n {<FormattedMessage id=\"admin/invoice-error\" />}\n </Alert>\n )\n }\n\n return (\n <>\n <ModalDialog\n centered\n confirmation={{\n disabled: true,\n onClick: () => {\n if (empty || !validEmail) {\n return\n }\n\n handleCreateInvoice(\n props.sellerData.startDate,\n props.sellerData.finalDate,\n props.sellerData.sellerName,\n props.sellerData.id,\n email\n )\n setIsModalOpen(!isModalOpen)\n },\n label: 'Confirm',\n }}\n cancelation={{\n onClick: () => setIsModalOpen(!isModalOpen),\n label: 'Cancel',\n }}\n isOpen={isModalOpen}\n onClose={() => setIsModalOpen(!isModalOpen)}\n >\n <div>\n <p>{props.messages.warning}</p>\n <p>{props.messages.confirmation}</p>\n <div>\n <Input\n placeholder=\"e-mail\"\n size=\"large\"\n value={email}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) => {\n setEmail(e.target.value)\n checkEmail(e.target.value)\n }}\n errorMessage={getErrorMessage()}\n />\n </div>\n </div>\n </ModalDialog>\n\n {props.integration !== 'internal' ? null : (\n <div className=\"mb5 justify-end flex items-end items-center\">\n {!props.disabled ? (\n ''\n ) : (\n <div className={`ph5 ${styles.large}`}>\n <Alert type=\"warning\">\n <FormattedMessage id=\"admin/form-settings.invalid-invoice\" />\n </Alert>\n </div>\n )}\n <Button\n onClick={() => {\n setIsModalOpen(!isModalOpen)\n }}\n disabled={props.disabled}\n variation=\"success\"\n >\n {props.buttonMessage}\n </Button>\n </div>\n )}\n\n <div className=\"mb5 flex justify-end items-end\" />\n </>\n )\n}\n\nexport default ModalConfirm\n\n```" } ]
code_components-financial-commission_19d9e02c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/EmptyTable/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React from 'react'\nimport { EmptyState } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\n\nconst EmptyTable: FC = () => {\n return (\n <div className=\"mt5\">\n <EmptyState title={<FormattedMessage id=\"admin/table.empty-state\" />}>\n <p>\n <FormattedMessage id=\"admin/table.empty-state-title\" />\n </p>\n </EmptyState>\n </div>\n )\n}\n\nexport default EmptyTable\n\n```" } ]
code_components-financial-commission_e32343af
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/Table/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React from 'react'\nimport {\n EXPERIMENTAL_Table as Table,\n EXPERIMENTAL_useTableMeasures as useTableMeasures,\n Spinner,\n EXPERIMENTAL_useTableSort as useTableSort,\n} from 'vtex.styleguide'\n\nimport EmptyTable from '../EmptyTable'\n\nconst TableV2: FC<TableData> = (props) => {\n const measures = useTableMeasures({ size: props.items.length })\n const sorting = useTableSort()\n let hiddenColumns = [...props.schemaTable]\n\n if (props.hiddenColumn?.length) {\n hiddenColumns = hiddenColumns.filter(\n (val: SchemaTable) => !props.hiddenColumn?.includes(val.id)\n )\n }\n\n if (sorting.sorted.by && sorting.sorted.order) props.sorting(sorting.sorted)\n\n const ColumnsExample = () => {\n return (\n <div>\n {props.items.length > 0 ? (\n <Table\n measures={measures}\n items={props.items}\n columns={\n props.hiddenColumn?.length ? hiddenColumns : props.schemaTable\n }\n highlightOnHover\n sorting={sorting}\n />\n ) : (\n <EmptyTable />\n )}\n </div>\n )\n }\n\n if (props.loading) {\n return (\n <div className=\"tc\">\n <Spinner />\n </div>\n )\n }\n\n return <ColumnsExample />\n}\n\nexport default TableV2\n\n```" } ]
code_components-financial-commission_978262c7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/Table/pagination.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React from 'react'\nimport { Pagination } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\n\nconst PaginationComponent: FC<PaginationProps> = (props) => {\n return (\n <div>\n {props.totalItems > 0 ? (\n <Pagination\n rowsOptions={[20, 30, 40, 50]}\n currentItemFrom={props.currentPage}\n currentItemTo={props.pageSize}\n textOf={<FormattedMessage id=\"admin/table.pagination-textOf\" />}\n textShowRows={<FormattedMessage id=\"admin/table.pagination-show\" />}\n totalItems={props.totalItems}\n onRowsChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n props.changeRows(parseInt(e.target.value, 10))\n }\n onNextClick={() => props.onNextClick()}\n onPrevClick={() => props.onPrevClick()}\n />\n ) : (\n <div />\n )}\n </div>\n )\n}\n\nexport default PaginationComponent\n\n```" } ]
code_components-financial-commission_355c9e64
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/Orders/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { DocumentNode } from 'graphql'\nimport type { FC } from 'react'\nimport React, { useEffect, useState } from 'react'\nimport { useLazyQuery } from 'react-apollo'\nimport { FormattedMessage } from 'react-intl'\nimport {\n ButtonWithIcon,\n IconVisibilityOff,\n PageBlock,\n Tag,\n} from 'vtex.styleguide'\n\nimport { status } from '../../constants'\nimport ModalConfirm from '../ModalConfirm'\nimport TableComponent from '../Table'\nimport PaginationComponent from '../Table/pagination'\n\ninterface DetailProps {\n account?: string\n ordersQuery: DocumentNode\n invoiceMutation: DocumentNode\n sellerName?: string\n startDate?: string\n finalDate?: string\n statusOrders?: string\n setDataRate: (data: dateRateType[]) => void\n sellerId?: string\n setOpenModal?: (open: boolean) => void\n openModal?: boolean\n dataTableOrders: TableOrdersType[]\n setDataTableOrders: (data: TableOrdersType[]) => void\n validRange: boolean\n}\n\nconst Orders: FC<DetailProps> = ({\n account,\n sellerName,\n ordersQuery,\n startDate,\n finalDate,\n statusOrders,\n setDataRate,\n sellerId,\n invoiceMutation,\n setOpenModal,\n openModal,\n dataTableOrders,\n setDataTableOrders,\n validRange,\n}) => {\n const [page, setPage] = useState(1)\n const [pageSize, setPageSize] = useState(20)\n const [itemFrom, setItemFrom] = useState(1)\n const [itemTo, setItemTo] = useState(20)\n const [totalItems, setTotalItems] = useState(0)\n\n const [\n getDataOrders,\n { data: dataOrders, loading: loadingDataOrders },\n ] = useLazyQuery(ordersQuery, {\n ssr: false,\n pollInterval: 0,\n variables: {\n searchOrdersParams: {\n dateStart: startDate,\n dateEnd: finalDate,\n sellerName,\n page,\n perpage: pageSize,\n status: statusOrders,\n },\n },\n })\n\n const IDCell = (props: CellRendererProps) => {\n return (\n // eslint-disable-next-line jsx-a11y/anchor-is-valid\n <a\n href={`admin/checkout/#/orders/${props.data}`}\n style={{ color: '#0C389F' }}\n target=\"_blank\"\n rel=\"noreferrer\"\n >\n {props.data}\n </a>\n )\n }\n\n const TotalOrderCell = (props: CellRendererProps) => {\n return <span>${props.data}</span>\n }\n\n const TotalCommissionCell = (props: CellRendererProps) => {\n return <span>${props.data}</span>\n }\n\n const RateCell = (props: any) => {\n return (\n <div>\n <ButtonWithIcon\n icon={<IconVisibilityOff />}\n variation=\"tertiary\"\n onClick={() => {\n if (setOpenModal) setOpenModal(!openModal)\n setDataRate(props.data)\n }}\n />\n </div>\n )\n }\n\n const StatusCell = (props: any) => {\n return (\n <Tag bgColor={props.data.bgColor} color={props.data.fontColor}>\n {props.data.status}\n </Tag>\n )\n }\n\n const schemaTable = [\n {\n id: 'id',\n title: <FormattedMessage id=\"admin/table-seller-order\" />,\n cellRenderer: IDCell,\n },\n {\n id: 'creationDate',\n title: <FormattedMessage id=\"admin/table-creation-order\" />,\n },\n {\n id: 'totalOrder',\n title: <FormattedMessage id=\"admin/table-total-order\" />,\n cellRenderer: TotalOrderCell,\n },\n {\n id: 'totalCommission',\n title: <FormattedMessage id=\"admin/table-commission-order\" />,\n cellRenderer: TotalCommissionCell,\n },\n {\n id: 'rate',\n title: <FormattedMessage id=\"admin/table-rate-order\" />,\n cellRenderer: RateCell,\n },\n {\n id: 'status',\n title: <FormattedMessage id=\"admin/table-seller-status\" />,\n cellRenderer: StatusCell,\n },\n ]\n\n const changeRows = (row: number) => {\n setPageSize(row)\n setItemTo(row)\n setItemFrom(1)\n setPage(1)\n }\n\n const onNextClick = () => {\n const nextPage = page + 1\n\n const currentTo = pageSize * nextPage\n const currentFrom = itemTo + 1\n\n setItemTo(currentTo)\n setItemFrom(currentFrom)\n setPage(nextPage)\n }\n\n const onPrevClick = () => {\n const previousPage = page - 1\n\n const currentTo = itemTo - pageSize\n const currentFrom = itemFrom - pageSize\n\n setItemTo(currentTo)\n setItemFrom(currentFrom)\n setPage(previousPage)\n }\n\n useEffect(() => {\n getDataOrders()\n // eslint-disable-next-line vtex/prefer-early-return\n if (dataOrders) {\n const dataTable: TableOrdersType[] = []\n\n dataOrders.orders.data.forEach((item: TableDataOrder) => {\n const keyColor = Object.keys(status).find(\n (itemStatus: string) => itemStatus === item.status\n )\n\n dataTable.push({\n id: account ? item.sellerOrderId : item.orderId,\n creationDate: item.creationDate.substring(\n 0,\n item.creationDate.indexOf('T')\n ),\n totalOrder: item.totalOrderValue,\n totalCommission: item.totalComission,\n rate: item.rate,\n status: {\n status: item.status,\n bgColor: keyColor ? status[keyColor].bgColor : '',\n fontColor: keyColor ? status[keyColor].fontColor : '',\n },\n })\n })\n setDataTableOrders(dataTable)\n setTotalItems(dataOrders.orders.paging.total)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dataOrders, sellerName])\n\n return (\n <PageBlock>\n {account ? null : (\n <ModalConfirm\n invoiceMutation={invoiceMutation}\n disabled={\n !(\n statusOrders === 'invoiced' &&\n dataOrders?.orders.data.length &&\n validRange\n )\n }\n buttonMessage={\n <FormattedMessage id=\"admin/form-settings.button-invoice\" />\n }\n messages={{\n warning: <FormattedMessage id=\"admin/modal-setting.warning\" />,\n confirmation: (\n <FormattedMessage id=\"admin/modal-setting.confirmation\" />\n ),\n }}\n sellerData={{\n startDate: startDate ?? '',\n finalDate: finalDate ?? '',\n sellerName: sellerName ?? '',\n id: sellerId ?? '',\n }}\n />\n )}\n <div className=\"mt2\">\n <TableComponent\n schemaTable={schemaTable}\n items={dataTableOrders}\n loading={loadingDataOrders}\n />\n <PaginationComponent\n setPageSize={setPageSize}\n currentPage={itemFrom}\n pageSize={itemTo}\n setPage={setPage}\n totalItems={totalItems}\n onNextClick={onNextClick}\n changeRows={changeRows}\n onPrevClick={onPrevClick}\n />\n </div>\n </PageBlock>\n )\n}\n\nexport default Orders\n\n```" } ]
code_components-financial-commission_ded2cd9a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/Filter/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { useState, useEffect } from 'react'\nimport {\n ButtonWithIcon,\n IconFilter,\n IconDelete,\n ButtonGroup,\n} from 'vtex.styleguide'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { FormattedMessage } from 'react-intl'\nimport { SelectComponent, DatePickerComponent } from './itemsFilter'\nimport { getDateString, firstDay, yesterday, today, filterEmptyObj, filterSellerValues } from '../../utils/calculateDate'\n\nconst Filter: FC<FilterProps> = (props) => {\n const { query, setQuery } = useRuntime()\n const [dataFilter, setDataFilter] = useState<DateFilter>({\n startDateFilter: firstDay,\n finalDateFilter: props.defaultDate?.today ? today : yesterday,\n dataFilter: [],\n statusFilter: []\n })\n\n useEffect(() => {\n if (props.optionsSelect.length > 0) {\n let filterQuery = []\n let filterQueryStatus = []\n if (query.sellerName) {\n const separateString = query.sellerName.split(\",\")\n filterQuery = separateString.map((seller: any) => props.optionsSelect.find((nameQuery) => nameQuery.label === seller))\n }\n\n if (query.status && props.optionsStatus) {\n const separateString = query.status.split(\",\")\n filterQueryStatus = separateString.map((seller: any) => props.optionsStatus?.find((nameQuery) => nameQuery.label === seller))\n }\n setDataFilter({ ...dataFilter, statusFilter: filterQueryStatus, dataFilter: filterQuery })\n changesValuesTable(filterQuery, filterQueryStatus)\n }\n\n\n }, [props.optionsSelect])\n\n const changesValuesTable = (dataFilterValues?: SellerSelect[], dataFilterStatus?: SellerSelect[]) => {\n let response: ResponseFilter = { stringId: '', sellerFilter: '', countTotalItems: 0, sellerId:'' }, stringStatus = ''\n if (dataFilterValues?.length) response = filterSellerValues(dataFilterValues, props.setStatusOrders ? true : false)\n else response = filterSellerValues(dataFilter.dataFilter, props.setStatusOrders ? true : false)\n\n if (dataFilterStatus?.length) {\n dataFilterStatus.forEach((status) => {\n stringStatus += `${status.label},`\n })\n } else {\n dataFilter.statusFilter.forEach((status) => {\n stringStatus += `${status.label},`\n })\n }\n\n props.filterDates && props.filterDates(getDateString(dataFilter.startDateFilter), getDateString(dataFilter.finalDateFilter))\n props.setSellerId(response.stringId.slice(0, -1))\n props.setId && props.setId(response.sellerId.slice(0, -1))\n props.setStatusOrders && props.setStatusOrders(stringStatus.slice(0, -1))\n props.setTotalItems && props.setTotalItems(response.countTotalItems)\n\n let queryObj = { sellerName: response.sellerFilter.slice(0, -1), status: stringStatus.slice(0, -1), startDate: props.defaultDate ? getDateString(dataFilter.startDateFilter) : '', finalDate: props.defaultDate ? getDateString(dataFilter.finalDateFilter) : '' }\n queryObj = filterEmptyObj(queryObj)\n setQuery(queryObj)\n }\n\n const modifyDataFilterSeller = (values: SellerSelect[]) => {\n setDataFilter({ ...dataFilter, dataFilter: values })\n }\n\n const modifyDataFilterStatus = (values: SellerSelect[]) => {\n setDataFilter({ ...dataFilter, statusFilter: values })\n }\n\n const changeDate = (date: Date, type: string) => {\n if (type === \"start\") setDataFilter({ ...dataFilter, startDateFilter: date })\n else if (type === \"final\") setDataFilter({ ...dataFilter, finalDateFilter: date })\n }\n\n const cleanFilter = () => {\n const lastDate = props.defaultDate?.today ? today : yesterday\n setDataFilter({ ...dataFilter, dataFilter: [], startDateFilter: firstDay, finalDateFilter: lastDate, statusFilter: [] })\n props.filterDates && props.filterDates(getDateString(firstDay), getDateString(lastDate))\n props.setSellerId('')\n props.setTotalItems && props.setTotalItems(0)\n setQuery({ sellerName: undefined, status: undefined, startDate: undefined, finalDate: undefined })\n }\n\n return (\n <div className=\"flex flex-wrap pa0\">\n {!props.disableSelect && (\n <div className=\"w-100\">\n <SelectComponent\n options={props.optionsSelect}\n dataFilter={dataFilter.dataFilter}\n setDataFilter={modifyDataFilterSeller}\n multi={props.multiValue}\n customLabel={\n <FormattedMessage id=\"admin/table.title-seller-label\" />\n }\n />\n </div>\n )}\n {props.optionsStatus && (\n <div className=\"w-100 pt5 mb3\">\n <SelectComponent\n options={props.optionsStatus}\n dataFilter={dataFilter.statusFilter}\n setDataFilter={modifyDataFilterStatus}\n multi\n customLabel={\n <FormattedMessage id=\"admin/table.title-status-label\" />\n }\n />\n </div>\n )}\n <div className=\"flex-ns w-100 justify-around items-end justify-end\">\n <div className=\"w-100-ns pt2 pr2\">\n {props.defaultDate && <DatePickerComponent\n startDatePicker={dataFilter.startDateFilter}\n changeDate={changeDate}\n finalDatePicker={dataFilter.finalDateFilter}\n today={props.defaultDate ? props.defaultDate.today : false}\n />}\n </div>\n <div className=\"pt7 fr z-0\">\n <ButtonGroup\n buttons={[\n <ButtonWithIcon\n isActiveOfGroup\n onClick={() => changesValuesTable()}\n icon={<IconFilter />}\n size=\"small\"\n >\n {<FormattedMessage id=\"admin/table.title-filter\" />}\n </ButtonWithIcon>,\n <ButtonWithIcon\n isActiveOfGroup={false}\n size=\"small\"\n onClick={() => cleanFilter()}\n icon={<IconDelete />}\n />,\n ]}\n />\n </div>\n </div>\n </div>\n )\n}\n\nexport default Filter\n\n```" } ]
code_components-financial-commission_39206c50
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/Filter/itemsFilter.ts from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport SelectComponent from './select'\nimport DatePickerComponent from './datePicker'\n\nexport { SelectComponent, DatePickerComponent }\n\n```" } ]
code_components-financial-commission_efeadd0c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/SellerInvoices/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/no-shadow */\n/* eslint-disable react/jsx-key */\nimport type { DocumentNode } from 'graphql'\nimport type { FC } from 'react'\nimport React, { useEffect, useState } from 'react'\nimport { useQuery } from 'react-apollo'\nimport { FormattedMessage } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { PageBlock, Tag } from 'vtex.styleguide'\n\nimport { status } from '../../constants'\nimport TableComponent from '../Table'\nimport PaginationComponent from '../Table/pagination'\n\ninterface DetailProps {\n invoicesQuery: DocumentNode\n account?: string\n sellerName?: string\n startDate?: string\n finalDate?: string\n dataTableInvoice: Invoice[]\n setDataTableInvoice: (data: Invoice[]) => void\n}\n\nconst SellerInvoices: FC<DetailProps> = ({\n sellerName,\n invoicesQuery,\n startDate,\n finalDate,\n dataTableInvoice,\n setDataTableInvoice,\n}) => {\n const { query } = useRuntime()\n const [page, setPage] = useState(1)\n const [pageSize, setPageSize] = useState(20)\n const [itemFrom, setItemFrom] = useState(1)\n const [itemTo, setItemTo] = useState(20)\n const [totalItems, setTotalItems] = useState(0)\n\n const { data: dataInvoices } = useQuery(invoicesQuery, {\n ssr: false,\n pollInterval: 0,\n variables: {\n sellerInvoiceParams: {\n sellerName,\n dates: {\n startDate,\n endDate: finalDate,\n },\n pagination: {\n page,\n pageSize,\n },\n },\n },\n })\n\n useEffect(() => {\n if (sellerName === '' && !query?.sellerName) {\n setDataTableInvoice([])\n setTotalItems(0)\n }\n }, [query, sellerName, setDataTableInvoice])\n\n useEffect(() => {\n if (dataInvoices) {\n setDataTableInvoice(dataInvoices.invoicesBySeller.data)\n setTotalItems(dataInvoices.invoicesBySeller.pagination.total)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dataInvoices, sellerName])\n\n const schemaTableInvoice = [\n {\n id: 'id',\n title: <FormattedMessage id=\"admin/table-seller-invoice\" />,\n // eslint-disable-next-line react/display-name\n cellRenderer: (props: CellRendererProps) => {\n return (\n // eslint-disable-next-line jsx-a11y/anchor-is-valid\n <a\n href={`/admin/app/commission-report/invoice/${props.data}`}\n style={{ color: '#0C389F' }}\n target=\"_self\"\n rel=\"noreferrer\"\n >\n {props.data}\n </a>\n )\n },\n },\n {\n id: 'invoiceCreatedDate',\n title: <FormattedMessage id=\"admin/table-seller-created\" />,\n },\n {\n id: 'status',\n title: <FormattedMessage id=\"admin/table-seller-status\" />,\n cellRenderer: (props: any) => {\n // eslint-disable-next-line array-callback-return\n const getColor = Object.keys(status).find(\n (itemStatus) => itemStatus === props.data\n )\n\n const bgColor = getColor ? status[getColor].bgColor : ''\n const fontcolor = getColor ? status[getColor].fontColor : ''\n\n return (\n <Tag bgColor={bgColor} color={fontcolor}>\n {props.data}\n </Tag>\n )\n },\n },\n ]\n\n const changeRows = (row: number) => {\n setPageSize(row)\n setItemTo(row)\n setItemFrom(1)\n setPage(1)\n }\n\n const onNextClick = () => {\n const nextPage = page + 1\n\n const currentTo = pageSize * nextPage\n const currentFrom = itemTo + 1\n\n setItemTo(currentTo)\n setItemFrom(currentFrom)\n setPage(nextPage)\n }\n\n const onPrevClick = () => {\n const previousPage = page - 1\n\n const currentTo = itemTo - pageSize\n const currentFrom = itemFrom - pageSize\n\n setItemTo(currentTo)\n setItemFrom(currentFrom)\n setPage(previousPage)\n }\n\n return (\n <PageBlock>\n <div>\n <TableComponent\n schemaTable={schemaTableInvoice}\n items={dataTableInvoice}\n loading={false}\n />\n <PaginationComponent\n setPageSize={setPageSize}\n currentPage={itemFrom}\n pageSize={itemTo}\n setPage={setPage}\n totalItems={totalItems}\n onNextClick={onNextClick}\n changeRows={changeRows}\n onPrevClick={onPrevClick}\n />\n </div>\n </PageBlock>\n )\n}\n\nexport default SellerInvoices\n\n```" } ]
code_components-financial-commission_e2c66ffc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/Dashboard/Totalizer/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React from 'react'\nimport { Totalizer, Spinner } from 'vtex.styleguide'\n\ntype TotalizerProps = {\n item: StatsTotalizer[]\n loading: boolean\n}\n\nconst TotalizerComponent: FC<TotalizerProps> = (props) => {\n if (props.loading) {\n return (\n <div className=\"tc\">\n <Spinner />\n </div>\n )\n }\n\n return <Totalizer items={props.item} />\n}\n\nexport default TotalizerComponent\n\n```" } ]
code_components-financial-commission_9bb1ab41
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/Filter/filterBar/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React from 'react'\nimport { FilterBar } from 'vtex.styleguide'\n\nconst FilterBarComponent: FC = () => {\n const getSimpleVerbs = () => {\n return [\n {\n label: 'is',\n value: '=',\n object: () => {},\n },\n {\n label: 'is not',\n value: '!=',\n object: () => {},\n },\n {\n label: 'contains',\n value: 'contains',\n object: () => {},\n },\n ]\n }\n\n return (\n <div>\n <FilterBar\n alwaysVisibleFilters={['totalOrders']}\n statements={[]}\n onChangeStatements={() => {}}\n clearAllFiltersButtonLabel=\"Clear Filters\"\n options={{\n totalOrders: {\n label: 'Total Orders',\n renderFilterLabel: () => 'All',\n verbs: getSimpleVerbs(),\n },\n }}\n />\n </div>\n )\n}\n\nexport default FilterBarComponent\n\n```" } ]
code_components-financial-commission_7f31b89e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/Filter/datePicker/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { DatePicker } from 'vtex.styleguide'\nimport { addDays } from 'date-fns'\n\nconst DatePickerComponent: FC<DatepickerProps> = (props) => {\n const { culture } = useRuntime()\n const numDates = props.today ? 0 : -1\n\n return (\n <div className=\"flex flex-nowrap\">\n <div id=\"datepicker-left\">\n <DatePicker\n label={<FormattedMessage id=\"admin/table.title-datepicker-start\" />}\n value={props.startDatePicker}\n maxDate={addDays(new Date(), numDates)}\n onChange={(start: Date) => {\n if (props.finalDatePicker.getTime() >= start.getTime())\n props.changeDate(start, 'start')\n }}\n locale={culture.locale}\n size=\"small\"\n />\n </div>\n <div id=\"datepicker-right\">\n <DatePicker\n label={<FormattedMessage id=\"admin/table.title-datepicker-final\" />}\n value={props.finalDatePicker}\n maxDate={addDays(new Date(), numDates)}\n onChange={(final: Date) => {\n if (props.startDatePicker.getTime() <= final.getTime())\n props.changeDate(final, 'final')\n }}\n locale={culture.locale}\n size=\"small\"\n />\n </div>\n </div>\n )\n}\n\nexport default DatePickerComponent\n\n```" } ]
code_components-financial-commission_a787c4d7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of components-financial-commission/react/components/Filter/select/index.tsx from the components-financial-commission VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React from 'react'\nimport { EXPERIMENTAL_Select as Select } from 'vtex.styleguide'\n\nconst SelectComponent: FC<SelectProps> = (props) => {\n return (\n <div>\n <Select\n value={props.dataFilter}\n label={props.customLabel}\n options={props.options}\n onChange={(values: SellerSelect[] | SellerSelect) => {\n if (Array.isArray(values)) props.setDataFilter(values)\n else props.setDataFilter([values])\n }}\n valuesMaxHeight={35}\n multi={props.multi}\n size=\"small\"\n />\n </div>\n )\n}\n\nexport default SelectComponent\n\n```" } ]
code_pixel-interfaces_fa448bc7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of pixel-interfaces/docs/README.md from the pixel-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# VTEX IO Store Pixel Interfaces\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\nDefines Pixel interfaces for other apps. Must be depended by every pixel app.\n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n```" } ]
code_pixel-interfaces_1ab62a93
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of pixel-interfaces/store/interfaces.json from the pixel-interfaces VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"pixel\": {\n \"component\": \"*\",\n \"extensibility\": \"enterprise\",\n \"render\": \"client\"\n },\n \"pixels\": {\n \"component\": \"vtex.render-runtime/ExtensionContainer\",\n \"allowed\": [\"pixel\"],\n \"render\": \"client\"\n }\n}\n```" } ]
code_policies-example-3_fac88131
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of policies-example-3/messages/pt.json from the policies-example-3 VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin.navigation.label\": \"Admin do aplicativo de policies\"\n}\n\n```" } ]
code_policies-example-3_6511c5fc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of policies-example-3/messages/en.json from the policies-example-3 VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin.navigation.label\": \"Admin do aplicativo de policies\"\n}\n\n```" } ]
code_policies-example-3_2a864e64
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of policies-example-3/messages/es.json from the policies-example-3 VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin.navigation.label\": \"Admin do aplicativo de policies\"\n}\n\n```" } ]