id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_b2b-organizations-graphql_d3dac278
|
[
{
"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 b2b-organizations-graphql/node/resolvers/directives/validateAdminUserAccess.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\nimport { AuthenticationError, ForbiddenError } from '@vtex/api'\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\n\nimport type { AuthAuditMetric } from '../../utils/metrics/auth'\nimport sendAuthMetric, { AuthMetric } from '../../utils/metrics/auth'\nimport {\n validateAdminToken,\n validateAdminTokenOnHeader,\n validateApiToken,\n} from './helper'\nimport { LICENSE_MANAGER_ROLES } from '../../constants'\n\nexport class ValidateAdminUserAccess extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (\n root: any,\n args: any,\n context: Context,\n info: any\n ) => {\n const {\n vtex: { adminUserAuthToken, logger },\n } = context\n\n // Get the admin permission from directive arguments, defaulting to VIEW permission\n const adminPermissionArg =\n this.args?.adminPermission || 'B2B_ORGANIZATIONS_VIEW'\n\n const requiredPermission =\n adminPermissionArg === 'B2B_ORGANIZATIONS_VIEW'\n ? LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_VIEW\n : LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_EDIT\n\n // get metrics data\n const operation = field?.astNode?.name?.value ?? context?.request?.url\n const userAgent = context?.request?.headers['user-agent'] as string\n const caller = context?.request?.headers['x-vtex-caller'] as string\n const forwardedHost = context?.request?.headers[\n 'x-forwarded-host'\n ] as string\n\n // set metric fields with initial data\n let metricFields: AuthAuditMetric = {\n operation,\n forwardedHost,\n caller,\n userAgent,\n }\n\n const { hasAdminToken, hasValidAdminToken, hasValidAdminRole } =\n await validateAdminToken(\n context,\n adminUserAuthToken as string,\n requiredPermission\n )\n\n // add admin token metrics\n metricFields = {\n ...metricFields,\n hasAdminToken,\n hasValidAdminToken,\n hasValidAdminRole,\n }\n\n // allow access if has valid admin token and valid admin role\n if (hasValidAdminToken && hasValidAdminRole) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateAdminUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // If there's no valid admin token on context, search for it on header\n const {\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n hasValidAdminRoleOnHeader,\n } = await validateAdminTokenOnHeader(context, requiredPermission)\n\n // add admin header token metrics\n metricFields = {\n ...metricFields,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n hasValidAdminRoleOnHeader,\n }\n\n // allow access if has valid admin token and valid admin role\n if (hasValidAdminTokenOnHeader && hasValidAdminRoleOnHeader) {\n // set adminUserAuthToken on context so it can be used later\n context.vtex.adminUserAuthToken = context?.headers\n .vtexidclientautcookie as string\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateAdminUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n const { hasApiToken, hasValidApiToken, hasValidApiRole } =\n await validateApiToken(context, requiredPermission)\n\n // add API token metrics\n metricFields = {\n ...metricFields,\n hasApiToken,\n hasValidApiToken,\n hasValidApiRole,\n }\n\n // allow access if has valid API token and valid API role\n if (hasValidApiToken && hasValidApiRole) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateAdminUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // deny access if no tokens were provided\n if (!hasAdminToken && !hasAdminTokenOnHeader && !hasApiToken) {\n logger.warn({\n message: 'ValidateAdminUserAccess: No token provided',\n ...metricFields,\n })\n throw new AuthenticationError('No token was provided')\n }\n\n // deny access if no valid tokens were provided or no valid role\n logger.warn({\n message:\n 'ValidateAdminUserAccess: Invalid token or insufficient role permissions',\n requiredPermission,\n ...metricFields,\n })\n throw new ForbiddenError(`Unauthorized Access`)\n }\n }\n}\n\n```"
}
] |
code_b2b-organizations-graphql_b610f38a
|
[
{
"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 b2b-organizations-graphql/node/resolvers/directives/validateStoreUserAccess.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\nimport { AuthenticationError, ForbiddenError } from '@vtex/api'\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\n\nimport type { AuthAuditMetric } from '../../utils/metrics/auth'\nimport sendAuthMetric, { AuthMetric } from '../../utils/metrics/auth'\nimport { LICENSE_MANAGER_ROLES } from '../../constants'\nimport {\n validateAdminToken,\n validateAdminTokenOnHeader,\n validateApiToken,\n validateStoreToken,\n} from './helper'\n\nexport class ValidateStoreUserAccess extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (\n root: any,\n args: any,\n context: Context,\n info: any\n ) => {\n const {\n vtex: { adminUserAuthToken, storeUserAuthToken, logger },\n } = context\n\n // Get the admin permission from directive arguments, defaulting to VIEW permission\n const adminPermissionArg =\n this.args?.adminPermission || 'B2B_ORGANIZATIONS_VIEW'\n\n const requiredPermission =\n adminPermissionArg === 'B2B_ORGANIZATIONS_VIEW'\n ? LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_VIEW\n : LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_EDIT\n\n // get metrics data\n const operation = field?.astNode?.name?.value ?? context?.request?.url\n const userAgent = context?.request?.headers['user-agent'] as string\n const caller = context?.request?.headers['x-vtex-caller'] as string\n const forwardedHost = context?.request?.headers[\n 'x-forwarded-host'\n ] as string\n\n // set metric fields with initial data\n let metricFields: AuthAuditMetric = {\n operation,\n forwardedHost,\n caller,\n userAgent,\n }\n\n const { hasAdminToken, hasValidAdminToken, hasValidAdminRole } =\n await validateAdminToken(\n context,\n adminUserAuthToken as string,\n requiredPermission\n )\n\n // add admin token metrics\n metricFields = {\n ...metricFields,\n hasAdminToken,\n hasValidAdminToken,\n hasValidAdminRole,\n }\n\n // allow access if has valid admin token and valid admin role\n if (hasValidAdminToken && hasValidAdminRole) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // If there's no valid admin token on context, search for it on header\n const {\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n hasValidAdminRoleOnHeader,\n } = await validateAdminTokenOnHeader(context, requiredPermission)\n\n // add admin header token metrics\n metricFields = {\n ...metricFields,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n hasValidAdminRoleOnHeader,\n }\n\n // allow access if has valid admin token and valid admin role\n if (hasValidAdminTokenOnHeader && hasValidAdminRoleOnHeader) {\n // set adminUserAuthToken on context so it can be used later\n context.vtex.adminUserAuthToken = context?.headers\n .vtexidclientautcookie as string\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // If there's no valid admin token on context or header,\n // invalidate the adminUserAuthToken on context\n context.vtex.adminUserAuthToken = undefined\n\n const { hasApiToken, hasValidApiToken, hasValidApiRole } =\n await validateApiToken(context, requiredPermission)\n\n // add API token metrics\n metricFields = {\n ...metricFields,\n hasApiToken,\n hasValidApiToken,\n hasValidApiRole,\n }\n\n // allow access if has valid API token and valid API role\n if (hasValidApiToken && hasValidApiRole) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n const { hasStoreToken, hasValidStoreToken } = await validateStoreToken(\n context,\n storeUserAuthToken as string\n )\n\n // add store token metrics\n metricFields = {\n ...metricFields,\n hasStoreToken,\n hasValidStoreToken,\n }\n\n // allow access if has valid store token (store users don't need LM role validation)\n if (hasValidStoreToken) {\n sendAuthMetric(\n context,\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // deny access if no tokens were provided\n if (!hasAdminToken && !hasApiToken && !hasStoreToken) {\n logger.warn({\n message: 'ValidateStoreUserAccess: No token provided',\n ...metricFields,\n })\n throw new AuthenticationError('No token was provided')\n }\n\n // deny access if no valid tokens were provided or no valid role\n logger.warn({\n message: `ValidateStoreUserAccess: Invalid token or insufficient role permissions`,\n ...metricFields,\n })\n throw new ForbiddenError('Unauthorized Access')\n }\n }\n}\n\n```"
}
] |
code_b2b-organizations-graphql_3f74cf13
|
[
{
"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 b2b-organizations-graphql/node/resolvers/directives/withSession.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable max-params */\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nexport class WithSession extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root: any, args: any, context: any, info: any) => {\n const {\n clients: { session },\n vtex: { sessionToken },\n } = context\n\n context.vtex.sessionData = await session\n .getSession(sessionToken as string, ['*'])\n .then((currentSession: any) => {\n return currentSession.sessionData\n })\n .catch(() => null)\n\n return resolve(root, args, context, info)\n }\n }\n}\n\n```"
}
] |
code_b2b-organizations-graphql_adba6358
|
[
{
"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 b2b-organizations-graphql/node/resolvers/directives/withPermissions.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable max-params */\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nimport type StorefrontPermissions from '../../clients/storefrontPermissions'\n\nexport const getUserPermission = async (\n storefrontPermissions: StorefrontPermissions,\n app = 'vtex.b2b-organizations@3.x'\n) => {\n const result = await storefrontPermissions.checkUserPermission(app)\n\n return result?.data?.checkUserPermission ?? null\n}\n\nexport class WithPermissions extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root: any, args: any, context: any, info: any) => {\n const {\n clients: { storefrontPermissions },\n vtex: { adminUserAuthToken, logger },\n } = context\n\n const appClients = context.vtex as any\n const sender =\n context?.graphql?.query?.senderApp ??\n context?.graphql?.query?.extensions?.persistedQuery?.sender ??\n context?.request?.header['x-b2b-senderapp'] ??\n undefined\n\n appClients.storefrontPermissions = await getUserPermission(\n storefrontPermissions,\n sender\n ).catch((error: any) => {\n if (!adminUserAuthToken) {\n logger.error({\n message: 'getPermissionsError',\n error,\n })\n }\n\n return null\n })\n\n return resolve(root, args, context, info)\n }\n }\n}\n\n```"
}
] |
code_b2b-organizations-graphql_0e326df2
|
[
{
"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 b2b-organizations-graphql/node/resolvers/repository/CostCenterRepository.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { CostCenterInput, Result } from '../../typings'\nimport {\n COST_CENTER_DATA_ENTITY,\n COST_CENTER_SCHEMA_VERSION,\n} from '../../mdSchema'\nimport MarketingTags from '../Mutations/MarketingTags'\n\nconst CostCenterRepository = {\n createCostCenter: async (\n _: void,\n organizationId: string,\n {\n addresses,\n id,\n name,\n paymentTerms,\n phoneNumber,\n businessDocument,\n stateRegistration,\n customFields,\n sellers,\n marketingTags,\n }: CostCenterInput,\n ctx: Context\n ): Promise<Result> => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const costCenter = {\n addresses,\n id,\n name,\n organization: organizationId,\n ...(paymentTerms && { paymentTerms }),\n ...(phoneNumber && { phoneNumber }),\n ...(businessDocument && { businessDocument }),\n ...(stateRegistration && { stateRegistration }),\n ...(customFields && { customFields }),\n ...(sellers && { sellers }),\n }\n\n const createCostCenterResult = await masterdata.createDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: costCenter,\n schema: COST_CENTER_SCHEMA_VERSION,\n })\n\n if (marketingTags && marketingTags?.length > 0) {\n MarketingTags.setMarketingTags(\n _,\n { costId: createCostCenterResult.DocumentId, tags: marketingTags },\n ctx\n ).catch((error) => {\n logger.error({\n error,\n message: 'setMarketingTags-error',\n })\n })\n }\n\n return {\n href: createCostCenterResult.Href,\n id: createCostCenterResult.DocumentId,\n status: '',\n }\n },\n}\n\nexport default CostCenterRepository\n\n```"
}
] |
code_b2b-organizations-graphql_a61c2157
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Mutations/Users.test.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { randAlphaNumeric, randEmail, randUser, randUuid } from '@ngneat/falso'\nimport { GraphQLError } from 'graphql'\n\nimport type { UserArgs } from '../../typings'\nimport Users from './Users'\n\njest.mock('@vtex/api')\njest.mock('@vtex/diagnostics-nodejs', () => ({}))\njest.mock('../config')\njest.mock('../../utils/metrics/impersonate')\n\nconst mockContext = (\n impersonateUser = randUser(),\n permissions: string[] = [],\n costId: string = randUuid(),\n orgId: string = randUuid()\n) => {\n return {\n clients: {\n storefrontPermissions: {\n getB2BUser: jest.fn().mockResolvedValue({\n data: {\n getB2BUser: {\n costId,\n orgId,\n },\n },\n }),\n getUser: jest.fn().mockResolvedValue({\n data: {\n getUser: {\n costId,\n orgId,\n },\n },\n }),\n impersonateUser: jest.fn().mockResolvedValue({\n data: {\n impersonateUser,\n },\n }),\n },\n },\n vtex: {\n logger: jest.fn(),\n sessionData: {\n namespaces: {\n 'storefront-permissions': {\n costcenter: {\n value: costId,\n },\n organization: {\n value: orgId,\n },\n storeUserEmail: randEmail(),\n userId: randUuid(),\n userTargetId: randUuid(),\n },\n },\n },\n storefrontPermissions: {\n permissions,\n },\n },\n } as unknown as Context\n}\n\ndescribe('given an Users Mutation', () => {\n describe('when impersonate an B2B user', () => {\n describe('with invalid permission', () => {\n const user = randUser()\n\n const mockedContext = mockContext()\n\n it('should throws GraphQLError with operation-not-permitted.', async () => {\n await expect(\n Users.impersonateB2BUser(jest.fn() as never, user, mockedContext)\n ).rejects.toThrowError(new GraphQLError('operation-not-permitted'))\n })\n })\n\n describe('with permission impersonate-users-costcenter and the user with same costcenter', () => {\n const user = randUser()\n const impersonateUser = randUser()\n\n const mockedContext = mockContext(impersonateUser, [\n 'impersonate-users-costcenter',\n ])\n\n let result: any\n\n beforeEach(async () => {\n result = await Users.impersonateB2BUser(\n jest.fn() as never,\n user,\n mockedContext\n )\n })\n it('should call impersonate user in storefront permission', () => {\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toHaveBeenCalledTimes(1)\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toBeCalledWith({ userId: user.id })\n })\n\n it('should return impersonate user data', () => {\n expect(result).toEqual(impersonateUser)\n })\n })\n\n describe('with permission impersonate-users-organization and the user with same organization', () => {\n const user = randUser()\n const impersonateUser = randUser()\n\n const mockedContext = mockContext(impersonateUser, [\n 'impersonate-users-organization',\n ])\n\n let result: any\n\n beforeEach(async () => {\n result = await Users.impersonateB2BUser(\n jest.fn() as never,\n user,\n mockedContext\n )\n })\n it('should call impersonate user in storefront permission', () => {\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toHaveBeenCalledTimes(1)\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toBeCalledWith({ userId: user.id })\n })\n\n it('should return impersonate user data', () => {\n expect(result).toEqual(impersonateUser)\n })\n })\n\n describe('with permission impersonate-users-all', () => {\n const user = randUser()\n const impersonateUser = randUser()\n\n const mockedContext = mockContext(impersonateUser, [\n 'impersonate-users-all',\n ])\n\n let result: any\n\n beforeEach(async () => {\n result = await Users.impersonateB2BUser(\n jest.fn() as never,\n user,\n mockedContext\n )\n })\n it('should call impersonate user in storefront permission', () => {\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toHaveBeenCalledTimes(1)\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toBeCalledWith({ userId: user.id })\n })\n\n it('should return impersonate user data', () => {\n expect(result).toEqual(impersonateUser)\n })\n })\n })\n\n describe('when impersonate an user', () => {\n describe('with invalid permission', () => {\n const clId = randAlphaNumeric({ length: 10 }).toString()\n const userId = randUser().id\n const user: Partial<UserArgs> = { clId, userId }\n const mockedContext = mockContext()\n\n it('should throws GraphQLError with operation-not-permitted.', async () => {\n await expect(\n Users.impersonateUser(\n jest.fn() as never,\n user as UserArgs,\n mockedContext\n )\n ).rejects.toThrowError(new GraphQLError('operation-not-permitted'))\n })\n })\n\n describe('with permission impersonate-users-costcenter and the user with same costcenter', () => {\n const clId = randAlphaNumeric({ length: 10 }).toString()\n const userId = randUser().id\n const user: Partial<UserArgs> = { clId, userId }\n const impersonateUser = randUser()\n\n const mockedContext = mockContext(impersonateUser, [\n 'impersonate-users-costcenter',\n ])\n\n let result: any\n\n beforeEach(async () => {\n result = await Users.impersonateUser(\n jest.fn() as never,\n user as UserArgs,\n mockedContext\n )\n })\n it('should call impersonate user in storefront permission', () => {\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toHaveBeenCalledTimes(1)\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toBeCalledWith({ userId })\n })\n\n it('should not return error', () => {\n expect(result?.status).not.toEqual('error')\n })\n })\n\n describe('with permission impersonate-users-organization and the user with same organization', () => {\n const clId = randAlphaNumeric({ length: 10 }).toString()\n const userId = randUser().id\n const user: Partial<UserArgs> = { clId, userId }\n const impersonateUser = randUser()\n\n const mockedContext = mockContext(impersonateUser, [\n 'impersonate-users-organization',\n ])\n\n let result: any\n\n beforeEach(async () => {\n result = await Users.impersonateUser(\n jest.fn() as never,\n user as UserArgs,\n mockedContext\n )\n })\n it('should call impersonate user in storefront permission', () => {\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toHaveBeenCalledTimes(1)\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toBeCalledWith({ userId })\n })\n\n it('should not return error', () => {\n expect(result?.status).not.toEqual('error')\n })\n })\n\n describe('with permission impersonate-users-all', () => {\n const clId = randAlphaNumeric({ length: 10 }).toString()\n const userId = randUser().id\n const user: Partial<UserArgs> = { clId, userId }\n const impersonateUser = randUser()\n\n const mockedContext = mockContext(impersonateUser, [\n 'impersonate-users-all',\n ])\n\n let result: any\n\n beforeEach(async () => {\n result = await Users.impersonateUser(\n jest.fn() as never,\n user as UserArgs,\n mockedContext\n )\n })\n it('should call impersonate user in storefront permission', () => {\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toHaveBeenCalledTimes(1)\n expect(\n mockedContext.clients.storefrontPermissions.impersonateUser\n ).toBeCalledWith({ userId })\n })\n\n it('should not return error', () => {\n expect(result?.status).not.toEqual('error')\n })\n })\n })\n})\n\n```"
}
] |
code_b2b-organizations-graphql_4519c135
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Mutations/Organizations.test.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n randAddress,\n randAirportName,\n randCompanyName,\n randEmail,\n randFirstName,\n randLastName,\n randSuperheroName,\n randUser,\n randUuid,\n randWord,\n} from '@ngneat/falso'\n\nimport {\n COST_CENTER_DATA_ENTITY,\n COST_CENTER_SCHEMA_VERSION,\n ORGANIZATION_DATA_ENTITY,\n ORGANIZATION_SCHEMA_VERSION,\n} from '../../mdSchema'\nimport type {\n AddressInput,\n NormalizedOrganizationInput,\n OrganizationInput,\n OrganizationRequest,\n} from '../../typings'\nimport { ORGANIZATION_REQUEST_STATUSES } from '../../utils/constants'\nimport Organizations from './Organizations'\n\njest.mock('@vtex/api')\njest.mock('@vtex/diagnostics-nodejs', () => ({}))\njest.mock('../config')\njest.mock('../Queries/Settings')\n\nconst mockGetDocument = jest.fn().mockResolvedValue({\n b2bCustomerAdmin: {\n email: randEmail(),\n firstName: randFirstName(),\n lastName: randLastName(),\n },\n defaultCostCenter: {\n address: {},\n },\n status: ORGANIZATION_REQUEST_STATUSES.PENDING,\n} as OrganizationRequest)\n\nconst mockContext = (\n orgId: string = randUuid(),\n roleId: string = randUuid(),\n costId: string = randUuid()\n) => {\n return {\n clients: {\n analytics: {\n sendMetric: jest.fn(),\n },\n masterdata: {\n createDocument: jest\n .fn()\n .mockResolvedValueOnce({\n DocumentId: orgId,\n })\n .mockResolvedValue({\n DocumentId: costId,\n }),\n getDocument: mockGetDocument,\n searchDocuments: jest.fn().mockResolvedValue({}),\n updatePartialDocument: jest.fn().mockResolvedValueOnce({}),\n },\n storefrontPermissions: {\n listRoles: jest.fn().mockResolvedValue({\n data: { listRoles: [{ id: roleId, slug: 'customer-admin' }] },\n }),\n saveUser: jest\n .fn()\n .mockResolvedValue({ data: { saveUser: randUser() } }),\n },\n },\n vtex: {\n logger: jest.fn(),\n },\n } as unknown as Context\n}\n\nafterEach(() => {\n jest.resetAllMocks()\n})\n\ndescribe('given an Organization Mutation', () => {\n describe('when update an organization', () => {\n const orgId = randUuid()\n const input = {\n id: '1',\n notes: 'OK',\n notifyUsers: true,\n status: ORGANIZATION_REQUEST_STATUSES.APPROVED,\n }\n\n let result: { id?: string; message: string; status: string }\n let mockedContext: Context\n\n const createDate = new Date('2023-10-10')\n\n describe('with status APPROVED and state registration', () => {\n const stateRegistration = randWord()\n\n const organization = {\n b2bCustomerAdmin: {\n email: randEmail(),\n firstName: randFirstName(),\n lastName: randLastName(),\n },\n defaultCostCenter: {\n address: randAddress(),\n stateRegistration,\n },\n id: orgId,\n name: randCompanyName(),\n stateRegistration,\n status: ORGANIZATION_REQUEST_STATUSES.PENDING,\n tradeName: randAirportName(),\n } as unknown as OrganizationInput\n\n beforeEach(async () => {\n mockGetDocument.mockResolvedValueOnce(organization)\n jest.useFakeTimers().setSystemTime(createDate)\n mockedContext = mockContext(orgId)\n result = await Organizations.updateOrganizationRequest(\n jest.fn() as never,\n input,\n mockedContext\n )\n })\n\n it('should return organization id with success', () => {\n expect(result.status).toEqual('success')\n expect(result.id).toEqual(orgId)\n })\n\n it('should call create organization with data', () => {\n expect(\n mockedContext.clients.masterdata.createDocument\n ).toHaveBeenNthCalledWith(2, {\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: {\n addresses: [organization.defaultCostCenter?.address],\n organization: orgId,\n stateRegistration,\n },\n schema: COST_CENTER_SCHEMA_VERSION,\n })\n })\n\n it('should save the user in store front permission', () => {\n expect(\n mockedContext.clients.storefrontPermissions.saveUser\n ).toHaveBeenCalledTimes(1)\n })\n })\n\n describe('with status APPROVED and without state registration', () => {\n const organization = {\n b2bCustomerAdmin: {\n email: randEmail(),\n firstName: randFirstName(),\n lastName: randLastName(),\n },\n defaultCostCenter: {},\n id: orgId,\n name: randCompanyName(),\n status: ORGANIZATION_REQUEST_STATUSES.PENDING,\n tradeName: randAirportName(),\n } as unknown as OrganizationInput\n\n beforeEach(async () => {\n mockGetDocument.mockResolvedValueOnce(organization)\n mockedContext = mockContext(orgId)\n\n result = await Organizations.updateOrganizationRequest(\n jest.fn() as never,\n input,\n mockedContext\n )\n })\n\n it('should return organization id with success', () => {\n expect(result.status).toEqual('success')\n expect(result.id).toEqual(orgId)\n })\n\n it('should call create organization without state registration', () => {\n expect(\n mockedContext.clients.masterdata.createDocument\n ).toHaveBeenNthCalledWith(2, {\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: {\n addresses: [],\n organization: orgId,\n },\n schema: COST_CENTER_SCHEMA_VERSION,\n })\n })\n\n it('should save the user in store front permission', () => {\n expect(\n mockedContext.clients.storefrontPermissions.saveUser\n ).toHaveBeenCalledTimes(1)\n })\n })\n })\n describe('when create an organization', () => {\n const orgId = randUuid()\n\n describe('with organization id and without cost center id', () => {\n const costCenter = {\n address: randAddress() as unknown as AddressInput,\n name: randLastName(),\n }\n\n const defaultCostCenter = {\n address: randAddress() as unknown as AddressInput,\n name: randSuperheroName(),\n }\n\n const input = {\n b2bCustomerAdmin: {\n email: randEmail(),\n firstName: randFirstName(),\n },\n costCenters: [costCenter],\n defaultCostCenter,\n id: orgId,\n name: randCompanyName(),\n tradeName: randAirportName(),\n } as NormalizedOrganizationInput\n\n let result: { href: any; id: any }\n let mockedContext: Context\n\n const roleId = randUuid()\n const costId = randUuid()\n\n const createDate = new Date('2020-01-01')\n\n beforeEach(async () => {\n jest.useFakeTimers().setSystemTime(createDate)\n mockedContext = mockContext(orgId, roleId, costId)\n result = await Organizations.createOrganizationAndCostCentersWithId(\n jest.fn() as never,\n { input },\n mockedContext\n )\n })\n\n it('should create the organization with the data expected', () => {\n expect(\n mockedContext.clients.masterdata.createDocument\n ).toHaveBeenNthCalledWith(1, {\n dataEntity: ORGANIZATION_DATA_ENTITY,\n fields: {\n collections: [],\n created: createDate,\n customFields: [],\n id: orgId,\n name: input.name,\n permissions: {\n createQuote: true,\n },\n sellers: [],\n status: 'active',\n tradeName: input.tradeName,\n },\n schema: ORGANIZATION_SCHEMA_VERSION,\n })\n })\n it('should create the cost center specified without set id', () => {\n expect(\n mockedContext.clients.masterdata.createDocument\n ).toHaveBeenNthCalledWith(2, {\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: {\n addresses: [costCenter.address],\n id: undefined,\n name: costCenter.name,\n organization: orgId,\n },\n schema: COST_CENTER_SCHEMA_VERSION,\n })\n })\n it('should create the default cost center', () => {\n expect(\n mockedContext.clients.masterdata.createDocument\n ).toHaveBeenNthCalledWith(3, {\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: {\n addresses: [defaultCostCenter.address],\n name: defaultCostCenter.name,\n organization: orgId,\n },\n schema: COST_CENTER_SCHEMA_VERSION,\n })\n })\n it('should set admin user for each cost center', () => {\n expect(\n mockedContext.clients.storefrontPermissions.saveUser\n ).toBeCalledWith({\n clId: null,\n costId,\n email: input.b2bCustomerAdmin.email,\n name: `${input.b2bCustomerAdmin.firstName} ${input.b2bCustomerAdmin.lastName}`,\n orgId,\n roleId,\n })\n })\n it('should create the organization with the id specified', () => {\n expect(result.id).toEqual(orgId)\n })\n })\n describe('with organization id and cost center id', () => {\n const costId = randUuid()\n const costCenter = {\n id: costId,\n name: randLastName(),\n }\n\n const defaultCostCenter = {\n id: costId,\n name: randSuperheroName(),\n }\n\n const input = {\n b2bCustomerAdmin: {\n email: randEmail(),\n firstName: randFirstName(),\n },\n costCenters: [costCenter],\n defaultCostCenter,\n id: orgId,\n name: randCompanyName(),\n tradeName: randAirportName(),\n } as NormalizedOrganizationInput\n\n let result: { href: any; id: any }\n let mockedContext: Context\n\n const createDate = new Date('2020-01-01')\n\n const roleId = randUuid()\n\n beforeEach(async () => {\n jest.useFakeTimers().setSystemTime(createDate)\n mockedContext = mockContext(orgId, roleId, costId)\n result = await Organizations.createOrganizationAndCostCentersWithId(\n jest.fn() as never,\n { input },\n mockedContext\n )\n })\n\n it('should create the organization with the data expected', () => {\n expect(\n mockedContext.clients.masterdata.createDocument\n ).toHaveBeenNthCalledWith(1, {\n dataEntity: ORGANIZATION_DATA_ENTITY,\n fields: {\n collections: [],\n created: createDate,\n customFields: [],\n id: orgId,\n name: input.name,\n permissions: {\n createQuote: true,\n },\n sellers: [],\n status: 'active',\n tradeName: input.tradeName,\n },\n schema: ORGANIZATION_SCHEMA_VERSION,\n })\n })\n it('should create the cost center specified without set id', () => {\n expect(\n mockedContext.clients.masterdata.createDocument\n ).toHaveBeenNthCalledWith(2, {\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: {\n addresses: [],\n organization: orgId,\n ...costCenter,\n },\n schema: COST_CENTER_SCHEMA_VERSION,\n })\n })\n it('should create the default cost center', () => {\n expect(\n mockedContext.clients.masterdata.createDocument\n ).toHaveBeenNthCalledWith(3, {\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: {\n addresses: [],\n organization: orgId,\n ...defaultCostCenter,\n },\n schema: COST_CENTER_SCHEMA_VERSION,\n })\n })\n it('should set admin user for each cost center', () => {\n expect(\n mockedContext.clients.storefrontPermissions.saveUser\n ).toHaveBeenNthCalledWith(1, {\n clId: null,\n costId: costCenter.id,\n email: input.b2bCustomerAdmin.email,\n name: `${input.b2bCustomerAdmin.firstName} ${input.b2bCustomerAdmin.lastName}`,\n orgId,\n roleId,\n })\n expect(\n mockedContext.clients.storefrontPermissions.saveUser\n ).toHaveBeenNthCalledWith(2, {\n clId: null,\n costId: defaultCostCenter.id,\n email: input.b2bCustomerAdmin.email,\n name: `${input.b2bCustomerAdmin.firstName} ${input.b2bCustomerAdmin.lastName}`,\n orgId,\n roleId,\n })\n })\n it('should create the organization with the id specified', () => {\n expect(result.id).toEqual(orgId)\n })\n })\n })\n})\n\n```"
}
] |
code_b2b-organizations-graphql_1d3914a2
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Mutations/Settings.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport GraphQLError from '../../utils/GraphQLError'\nimport checkConfig, { getAppId } from '../config'\nimport type { B2BSettingsInput } from '../../typings'\n\nexport const B2B_SETTINGS_DOCUMENT_ID = 'b2bSettings'\n\nconst Settings = {\n saveAppSettings: async (_: any, __: any, ctx: Context) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n const app: string = getAppId()\n\n const newSettings = {}\n\n try {\n await vbase.saveJSON('b2borg', app, newSettings)\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'saveAppSettings-error',\n })\n\n return { status: 'error', message: error }\n }\n },\n saveB2BSettings: async (\n _: void,\n {\n input: {\n autoApprove,\n businessReadOnly,\n stateReadOnly,\n defaultPaymentTerms,\n defaultPriceTables,\n uiSettings,\n organizationCustomFields,\n costCenterCustomFields,\n transactionEmailSettings,\n },\n }: {\n input: B2BSettingsInput\n page: number\n pageSize: number\n },\n ctx: Context\n ) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n const B2B_SETTINGS_DATA_ENTITY = 'b2b_settings'\n\n // Get current settings to save them depending on where the saveB2BSettings is coming from. Custom fields come without autoApprove settings and vice versa.\n\n let currentB2BSettings: B2BSettingsInput | undefined\n\n try {\n const getSettingsObj: B2BSettingsInput = await vbase.getJSON(\n B2B_SETTINGS_DATA_ENTITY,\n 'settings'\n )\n\n currentB2BSettings = getSettingsObj\n } catch (e) {\n if (e.response?.status === 404) {\n // when run for the first time on the project - returns 404. ignore in that case\n } else {\n logger.error({\n message: 'saveB2BSettings-currentB2BSettings-error',\n error: e,\n })\n if (e.message) {\n throw new GraphQLError(e.message)\n } else if (e.response?.data?.message) {\n throw new GraphQLError(e.response.data.message)\n } else {\n throw new GraphQLError(e)\n }\n }\n }\n\n try {\n const b2bSettings = {\n autoApprove,\n businessReadOnly,\n stateReadOnly,\n costCenterCustomFields:\n costCenterCustomFields ?? currentB2BSettings?.costCenterCustomFields,\n defaultPaymentTerms,\n defaultPriceTables,\n organizationCustomFields:\n organizationCustomFields ??\n currentB2BSettings?.organizationCustomFields,\n transactionEmailSettings:\n transactionEmailSettings ??\n currentB2BSettings?.transactionEmailSettings,\n uiSettings: {\n showModal:\n uiSettings?.showModal ?? currentB2BSettings?.uiSettings?.showModal,\n clearCart:\n uiSettings?.clearCart ?? currentB2BSettings?.uiSettings?.clearCart,\n topBar: uiSettings?.topBar ?? currentB2BSettings?.uiSettings?.topBar,\n },\n }\n\n await vbase.saveJSON(B2B_SETTINGS_DATA_ENTITY, 'settings', b2bSettings)\n\n return {\n status: 'success',\n }\n } catch (e) {\n logger.error({\n error: e,\n message: 'saveB2BSettings-error',\n })\n if (e.message) {\n throw new GraphQLError(e.message)\n } else if (e.response?.data?.message) {\n throw new GraphQLError(e.response.data.message)\n } else {\n throw new GraphQLError(e)\n }\n }\n },\n\n saveSalesChannels: async (\n _: void,\n { channels }: { channels: any[] },\n ctx: Context\n ) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n try {\n await vbase.saveJSON('b2borg', 'salesChannels', channels)\n } catch (error) {\n logger.error({\n error,\n message: 'saveSalesChannels-Error',\n })\n\n return { status: 'error', message: error }\n }\n\n return { status: 'success', message: '' }\n },\n}\n\nexport default Settings\n\n```"
}
] |
code_b2b-organizations-graphql_8562c8ba
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Mutations/Organizations.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Seller } from '../../clients/sellers'\nimport {\n ORGANIZATION_DATA_ENTITY,\n ORGANIZATION_FIELDS,\n ORGANIZATION_REQUEST_DATA_ENTITY,\n ORGANIZATION_REQUEST_FIELDS,\n ORGANIZATION_REQUEST_SCHEMA_VERSION,\n ORGANIZATION_SCHEMA_VERSION,\n} from '../../mdSchema'\nimport type {\n B2BSettingsInput,\n Collection,\n DefaultCostCenterInput,\n NormalizedOrganizationInput,\n Organization,\n OrganizationInput,\n OrganizationRequest,\n PaymentTerm,\n Price,\n} from '../../typings'\nimport {\n ORGANIZATION_REQUEST_STATUSES,\n ORGANIZATION_STATUSES,\n} from '../../utils/constants'\nimport GraphQLError, { getErrorMessage } from '../../utils/GraphQLError'\nimport {\n sendOrganizationStatusMetric,\n sendUpdateOrganizationMetric,\n} from '../../utils/metrics/organization'\nimport checkConfig from '../config'\nimport message from '../message'\nimport B2BSettings from '../Queries/Settings'\nimport CostCenterRepository from '../repository/CostCenterRepository'\n\nconst createUserAndAttachToOrganization = async ({\n storefrontPermissions,\n email,\n costCenterId,\n organizationId,\n firstName,\n lastName,\n logger,\n}: any) => {\n // get roleId of org admin\n const roles = await storefrontPermissions.listRoles().then((result: any) => {\n return result.data.listRoles\n })\n\n const roleId = roles.find(\n (roleItem: any) => roleItem.slug === 'customer-admin'\n ).id\n\n // grant user org admin role, assign org and cost center\n return storefrontPermissions\n .saveUser({\n clId: null,\n costId: costCenterId,\n email,\n name: `${firstName} ${lastName}`,\n orgId: organizationId,\n roleId,\n })\n .then((result: any) => {\n return result.data.saveUser\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'addUser-error',\n })\n })\n}\n\nconst createOrganization = async (\n _: void,\n {\n id,\n name,\n tradeName,\n paymentTerms,\n priceTables,\n salesChannel,\n sellers,\n customFields,\n collections,\n }: OrganizationInput,\n ctx: Context\n): Promise<{\n Id: string\n Href: string\n DocumentId: string\n}> => {\n const {\n clients: { masterdata },\n } = ctx\n\n const organization = {\n id,\n name,\n ...(tradeName && { tradeName }),\n collections: [],\n created: new Date(),\n ...(paymentTerms?.length && { paymentTerms }),\n ...(priceTables?.length && { priceTables }),\n ...(salesChannel && { salesChannel }),\n ...(sellers && { sellers }),\n ...(collections && { collections }),\n customFields: customFields ?? [],\n status: ORGANIZATION_STATUSES.ACTIVE,\n permissions: { createQuote: true },\n }\n\n return masterdata.createDocument({\n dataEntity: ORGANIZATION_DATA_ENTITY,\n fields: organization,\n schema: ORGANIZATION_SCHEMA_VERSION,\n })\n}\n\nconst findPaymentTerms = async (paymentTermNames: string[], ctx: Context) => {\n const {\n clients: { payments },\n } = ctx\n\n const paymentRules = await payments.getPaymentTerms()\n const paymentTerms = paymentTermNames\n ?.map((paymentTermName: string) => {\n const paymentTerm = paymentRules.find(\n (paymentRule: any) => paymentRule.name === paymentTermName\n )\n\n if (paymentTerm) {\n return {\n id: paymentTerm.id.toString(),\n name: paymentTerm.name,\n } as PaymentTerm\n }\n\n return null\n })\n .filter((paymentTerm: any) => paymentTerm !== null)\n\n return paymentTerms\n}\n\nconst findSellers = async (sellerNames: string[], ctx: Context) => {\n const {\n clients: { sellers },\n } = ctx\n\n const availableSellers = (await sellers.getSellers())?.items\n const sellersFound = sellerNames\n ?.map((sellerName: string) => {\n const seller = availableSellers.find((s: any) => s.name === sellerName)\n\n if (seller) {\n return {\n id: seller.id,\n name: seller.name,\n } as Seller\n }\n\n return null\n })\n .filter((seller: any) => seller !== null)\n\n return sellersFound\n}\n\nconst findCollections = async (collectionsNames: string[], ctx: Context) => {\n const {\n clients: { catalog },\n } = ctx\n\n const collectionsFound = collectionsNames\n .map(async (collectionName: string) => {\n const availableCollections = (\n await catalog.collectionsAvailable(collectionName)\n )?.items\n\n const collection = availableCollections.find(\n (c: any) => c.name === collectionName\n )\n\n if (collection) {\n return {\n id: collection.id.toString(),\n name: collection.name,\n } as Collection\n }\n\n return null\n })\n .filter((collection: any) => collection !== null)\n\n return Promise.all(collectionsFound)\n}\n\nconst createOrganizationAndCostCenterWithAdminUser = async (\n _: void,\n organization: NormalizedOrganizationInput,\n ctx: Context\n) => {\n const {\n clients: { storefrontPermissions, mail },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n try {\n // copy fields from NormalizedOrganizationInput to OrganizationInput\n // and transform fields that need transformation\n const organizationInput = {\n id: organization.id,\n name: organization.name,\n tradeName: organization.tradeName,\n b2bCustomerAdmin: organization.b2bCustomerAdmin,\n defaultCostCenter: organization.defaultCostCenter,\n costCenters: organization.costCenters,\n customFields: organization.customFields,\n permissions: { createQuote: true },\n paymentTerms: organization.paymentTerms\n ? await findPaymentTerms(organization.paymentTerms, ctx)\n : [],\n priceTables: organization.priceTables,\n salesChannel: organization.salesChannel,\n sellers: organization.sellers\n ? await findSellers(organization.sellers, ctx)\n : [],\n collections: organization.collections\n ? await findCollections(organization.collections, ctx)\n : [],\n } as OrganizationInput\n\n // create organization\n const createOrganizationResult = await createOrganization(\n _,\n organizationInput,\n ctx\n )\n\n const organizationId = createOrganizationResult.DocumentId\n\n const { defaultCostCenter, costCenters } = organization\n const { email, firstName, lastName } = organization.b2bCustomerAdmin\n\n const settings = (await B2BSettings.getB2BSettings(\n undefined,\n undefined,\n ctx\n )) as B2BSettingsInput\n\n if (costCenters?.length) {\n await Promise.all(\n costCenters?.map(async (costCenter: DefaultCostCenterInput) => {\n const addresses = costCenter.address ? [costCenter.address] : []\n\n const { id: costCenterId } =\n await CostCenterRepository.createCostCenter(\n _,\n organizationId,\n {\n addresses,\n ...costCenter,\n },\n ctx\n )\n\n const userToAdd = costCenter.user ?? {\n email,\n firstName,\n lastName,\n }\n\n createUserAndAttachToOrganization({\n costCenterId,\n email: userToAdd.email,\n firstName: userToAdd.firstName,\n lastName: userToAdd.lastName,\n logger,\n organizationId,\n storefrontPermissions,\n })\n })\n )\n }\n\n if (defaultCostCenter) {\n const addresses = defaultCostCenter.address\n ? [defaultCostCenter.address]\n : []\n\n const { id: costCenterId } = await CostCenterRepository.createCostCenter(\n _,\n organizationId,\n {\n addresses,\n ...defaultCostCenter,\n },\n ctx\n )\n\n await createUserAndAttachToOrganization({\n costCenterId,\n email,\n firstName,\n lastName,\n logger,\n organizationId,\n storefrontPermissions,\n })\n }\n\n if (settings?.transactionEmailSettings?.organizationCreated) {\n message({\n logger,\n mail,\n storefrontPermissions,\n }).organizationCreated(organizationInput.name)\n }\n\n return {\n href: createOrganizationResult.Href,\n id: organizationId,\n status: '',\n }\n } catch (error) {\n logger.error({\n error,\n message: 'createOrganization-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n}\n\nconst Organizations = {\n createOrganization: async (\n _: void,\n {\n input: {\n name,\n tradeName,\n defaultCostCenter,\n costCenters,\n customFields,\n paymentTerms,\n priceTables,\n salesChannel,\n sellers,\n },\n notifyUsers = true,\n }: { input: OrganizationInput; notifyUsers?: boolean },\n ctx: Context\n ) => {\n const {\n clients: { storefrontPermissions, mail },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n try {\n const organization = {\n customFields,\n name,\n paymentTerms,\n priceTables,\n salesChannel,\n sellers,\n tradeName,\n } as OrganizationInput\n\n // create organization\n const createOrganizationResult = await createOrganization(\n _,\n organization,\n ctx\n )\n\n const organizationId = createOrganizationResult.DocumentId\n\n let costCenterResult: any[] = []\n\n if (!defaultCostCenter && costCenters?.length) {\n costCenterResult = await Promise.all(\n costCenters?.map(async (costCenter: any) => {\n const addresses = costCenter.address ? [costCenter.address] : []\n\n CostCenterRepository.createCostCenter(\n _,\n organizationId,\n {\n addresses,\n ...costCenter,\n },\n ctx\n )\n })\n )\n } else if (defaultCostCenter) {\n const addresses = defaultCostCenter.address\n ? [defaultCostCenter.address]\n : []\n\n costCenterResult = [\n await CostCenterRepository.createCostCenter(\n _,\n organizationId,\n {\n addresses,\n ...defaultCostCenter,\n },\n ctx\n ),\n ]\n }\n\n const settings = (await B2BSettings.getB2BSettings(\n undefined,\n undefined,\n ctx\n )) as B2BSettingsInput\n\n if (\n notifyUsers &&\n settings?.transactionEmailSettings?.organizationCreated\n ) {\n message({\n storefrontPermissions,\n logger,\n mail,\n }).organizationCreated(name)\n }\n\n return {\n costCenterId: costCenterResult[0].id,\n href: createOrganizationResult.Href,\n id: createOrganizationResult.DocumentId,\n status: '',\n }\n } catch (error) {\n logger.error({\n error,\n message: 'createOrganization-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n createOrganizationRequest: async (\n _: void,\n {\n input: {\n b2bCustomerAdmin,\n costCenters,\n defaultCostCenter,\n customFields,\n name,\n tradeName,\n priceTables,\n salesChannel,\n paymentTerms,\n sellers,\n },\n notifyUsers = true,\n }: { input: OrganizationInput; notifyUsers?: boolean },\n ctx: Context\n ) => {\n const {\n clients: { masterdata, storefrontPermissions, mail },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n const now = new Date()\n\n const settings = (await B2BSettings.getB2BSettings(\n undefined,\n undefined,\n ctx\n )) as B2BSettingsInput\n\n const status = ORGANIZATION_REQUEST_STATUSES.PENDING\n\n paymentTerms =\n paymentTerms ??\n (settings?.defaultPaymentTerms as unknown as PaymentTerm[])\n priceTables =\n priceTables ?? (settings?.defaultPriceTables as unknown as Price[])\n\n if (!defaultCostCenter && costCenters?.length) {\n defaultCostCenter = costCenters.shift()\n }\n\n const organizationRequest = {\n name,\n ...(tradeName && { tradeName }),\n ...(priceTables && { priceTables }),\n ...(salesChannel && { salesChannel }),\n ...(paymentTerms && { paymentTerms }),\n ...(sellers && { sellers }),\n b2bCustomerAdmin,\n costCenters,\n created: now,\n customFields: customFields ?? [],\n defaultCostCenter,\n notes: '',\n status,\n }\n\n try {\n const result = (await masterdata.createDocument({\n dataEntity: ORGANIZATION_REQUEST_DATA_ENTITY,\n fields: organizationRequest,\n schema: ORGANIZATION_REQUEST_SCHEMA_VERSION,\n })) as any\n\n if (settings?.autoApprove) {\n await Organizations.updateOrganizationRequest(\n _,\n {\n id: result.DocumentId,\n notes: 'Auto approved',\n notifyUsers,\n status: ORGANIZATION_REQUEST_STATUSES.APPROVED,\n },\n ctx\n )\n }\n\n if (settings?.transactionEmailSettings?.organizationRequestCreated) {\n message({\n logger,\n mail,\n storefrontPermissions,\n }).organizationRequestCreated(\n organizationRequest.name,\n b2bCustomerAdmin.firstName,\n b2bCustomerAdmin.email,\n ''\n )\n }\n\n return {\n href: result.Href,\n id: result.DocumentId,\n status: organizationRequest.status,\n }\n } catch (error) {\n logger.error({\n error,\n message: 'createOrganizationRequest-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n createOrganizationAndCostCentersWithId: async (\n _: void,\n { input }: { input: NormalizedOrganizationInput },\n ctx: Context\n ): Promise<{\n href: string\n id: string\n }> => {\n const {\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n try {\n // create organization\n const { href, id } = await createOrganizationAndCostCenterWithAdminUser(\n _,\n input,\n ctx\n )\n\n return {\n href,\n id,\n }\n } catch (error) {\n logger.error({\n error,\n message: 'createOrganizationWitId-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n deleteOrganizationRequest: async (\n _: void,\n { id }: { id: string },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n } = ctx\n\n try {\n await masterdata.deleteDocument({\n dataEntity: ORGANIZATION_REQUEST_DATA_ENTITY,\n id,\n })\n\n return { status: 'success', message: '' }\n } catch (e) {\n throw new GraphQLError(getErrorMessage(e))\n }\n },\n updateOrganization: async (\n _: void,\n {\n id,\n name,\n tradeName,\n status,\n collections,\n paymentTerms,\n priceTables,\n customFields,\n salesChannel,\n sellers,\n notifyUsers = true,\n permissions,\n }: {\n id: string\n name: string\n tradeName?: string\n status: string\n collections: any[]\n paymentTerms: any[]\n priceTables: any[]\n customFields: any[]\n salesChannel?: string\n sellers?: any[]\n notifyUsers?: boolean\n permissions?: Permissions\n },\n ctx: Context\n ) => {\n const {\n clients: { storefrontPermissions, mail, masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n const settings = (await B2BSettings.getB2BSettings(\n undefined,\n undefined,\n ctx\n )) as B2BSettingsInput\n\n let currentOrganizationData: Organization | undefined\n\n try {\n currentOrganizationData = await masterdata.getDocument({\n dataEntity: ORGANIZATION_DATA_ENTITY,\n fields: ORGANIZATION_FIELDS,\n id,\n })\n\n if (\n currentOrganizationData?.status !== status &&\n notifyUsers &&\n settings?.transactionEmailSettings?.organizationStatusChanged\n ) {\n await message({\n logger,\n mail,\n storefrontPermissions,\n }).organizationStatusChanged(name, id, status)\n }\n } catch (error) {\n logger.warn({\n error,\n message: 'updateOrganization-emailOnStatusChangeError',\n })\n }\n\n try {\n const fields = {\n collections,\n ...((tradeName || tradeName === '') && { tradeName }),\n customFields,\n name,\n paymentTerms,\n priceTables,\n ...(salesChannel && { salesChannel }),\n ...(sellers && { sellers }),\n status,\n permissions,\n }\n\n await masterdata.updatePartialDocument({\n dataEntity: ORGANIZATION_DATA_ENTITY,\n fields,\n id,\n })\n\n sendUpdateOrganizationMetric(ctx, logger, {\n account: ctx.vtex.account,\n currentOrganizationData,\n updatedProperties: fields,\n })\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'updateOrganization-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n updateOrganizationRequest: async (\n _: void,\n {\n id,\n status,\n notes,\n notifyUsers = true,\n }: { id: string; status: string; notes: string; notifyUsers: boolean },\n ctx: Context\n ) => {\n const {\n clients: { masterdata, mail, storefrontPermissions },\n vtex: { logger },\n } = ctx\n\n const settings = (await B2BSettings.getB2BSettings(\n undefined,\n undefined,\n ctx\n )) as B2BSettingsInput\n\n if (\n status !== ORGANIZATION_REQUEST_STATUSES.APPROVED &&\n status !== ORGANIZATION_REQUEST_STATUSES.DECLINED\n ) {\n throw new GraphQLError('Invalid status')\n }\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n let organizationRequest: OrganizationRequest\n\n try {\n // get organization request\n organizationRequest = await masterdata.getDocument({\n dataEntity: ORGANIZATION_REQUEST_DATA_ENTITY,\n fields: ORGANIZATION_REQUEST_FIELDS,\n id,\n })\n } catch (error) {\n logger.error({\n error,\n message: 'getOrganizationRequest-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n\n // don't allow update if status is already approved or declined\n if (organizationRequest.status !== ORGANIZATION_REQUEST_STATUSES.PENDING) {\n throw new GraphQLError('Organization request already processed')\n }\n\n const { email, firstName } = organizationRequest.b2bCustomerAdmin\n\n // if we reach this block, status is declined\n try {\n if (status === ORGANIZATION_REQUEST_STATUSES.APPROVED) {\n try {\n // the following copy is fine as organizationRequest does not contain fields that need transformation\n const normalizedOrganizationRequest = {\n ...organizationRequest,\n } as unknown as NormalizedOrganizationInput\n\n const { id: organizationId } =\n await createOrganizationAndCostCenterWithAdminUser(\n _,\n normalizedOrganizationRequest,\n ctx\n )\n\n if (\n notifyUsers &&\n settings?.transactionEmailSettings?.organizationApproved\n ) {\n message({\n logger,\n mail,\n storefrontPermissions,\n }).organizationApproved(\n organizationRequest.name,\n firstName,\n email,\n notes\n )\n }\n\n await masterdata.updatePartialDocument({\n dataEntity: ORGANIZATION_REQUEST_DATA_ENTITY,\n fields: { status, notes },\n id,\n })\n\n sendOrganizationStatusMetric(ctx, logger, {\n account: ctx.vtex.account,\n status: ORGANIZATION_REQUEST_STATUSES.APPROVED,\n })\n\n return { status: 'success', message: '', id: organizationId }\n } catch (e) {\n logger.error({\n error: e,\n message: 'updateOrganizationRequest-error',\n })\n if (e.message) {\n throw new GraphQLError(e.message)\n } else if (e.response?.data?.message) {\n throw new GraphQLError(e.response.data.message)\n } else {\n throw new GraphQLError(e)\n }\n }\n }\n\n // update request status to declined\n await masterdata.updatePartialDocument({\n dataEntity: ORGANIZATION_REQUEST_DATA_ENTITY,\n fields: { status, notes },\n id,\n })\n\n if (\n notifyUsers &&\n settings?.transactionEmailSettings?.organizationDeclined\n ) {\n message({ storefrontPermissions, logger, mail }).organizationDeclined(\n organizationRequest.name,\n firstName,\n email,\n notes\n )\n }\n\n sendOrganizationStatusMetric(ctx, logger, {\n account: ctx.vtex.account,\n status: ORGANIZATION_REQUEST_STATUSES.DECLINED,\n })\n\n return { status: 'success', message: '' }\n } catch (e) {\n throw new GraphQLError(getErrorMessage(e))\n }\n },\n}\n\nexport default Organizations\n\n```"
}
] |
code_b2b-organizations-graphql_b5630763
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Mutations/CostCenters.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n COST_CENTER_DATA_ENTITY,\n ORGANIZATION_DATA_ENTITY,\n} from '../../mdSchema'\nimport type {\n AddressInput,\n CostCenterInput,\n CostCenterInputWithId,\n} from '../../typings'\nimport GraphQLError, { getErrorMessage } from '../../utils/GraphQLError'\nimport Organizations from '../Queries/Organizations'\nimport costCenters from '../Queries/CostCenters'\nimport checkConfig from '../config'\nimport CostCenterRepository from '../repository/CostCenterRepository'\n\nconst CostCenters = {\n createCostCenter: async (\n _: void,\n {\n organizationId,\n input: {\n id,\n name,\n addresses,\n phoneNumber,\n businessDocument,\n stateRegistration,\n customFields,\n marketingTags,\n sellers,\n paymentTerms,\n },\n }: { organizationId: string; input: CostCenterInput },\n ctx: Context\n ) => {\n const {\n vtex,\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n if (!organizationId) {\n // get user's organization from session\n const { sessionData } = vtex as any\n\n if (!sessionData?.namespaces['storefront-permissions']) {\n throw new GraphQLError('organization-data-not-found')\n }\n\n const {\n organization: { value: userOrganizationId },\n } = sessionData.namespaces['storefront-permissions'] ?? {\n organization: {\n value: null,\n },\n }\n\n organizationId = userOrganizationId\n }\n\n try {\n const costCenter: CostCenterInput = {\n addresses,\n businessDocument,\n customFields,\n marketingTags,\n id,\n name,\n phoneNumber,\n sellers,\n stateRegistration,\n paymentTerms,\n }\n\n return await CostCenterRepository.createCostCenter(\n _,\n organizationId,\n costCenter,\n ctx\n )\n } catch (error) {\n logger.error({\n error,\n message: 'createCostCenter-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n createCostCenterWithId: async (\n _: void,\n {\n organizationId,\n input: {\n id,\n name,\n addresses,\n phoneNumber,\n businessDocument,\n stateRegistration,\n customFields,\n marketingTags,\n sellers,\n paymentTerms,\n },\n }: { organizationId: string; input: CostCenterInputWithId },\n ctx: Context\n ) => {\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n // check if organization exists\n const organization = (await Organizations.getOrganizationById(\n _,\n { id: organizationId },\n ctx\n )) as {\n status: string\n }\n\n if (!organization) {\n throw new Error('Organization not found')\n }\n\n // check if cost center id already exists\n let costCenter = null\n\n try {\n costCenter = await costCenters.getCostCenterById(_, { id }, ctx)\n } catch (error) {\n costCenter = null // cost center does not exist so we don't need to do anything\n }\n\n if (costCenter) {\n throw new Error('Cost Center already exists')\n }\n\n // create cost center\n const newCostCenter: CostCenterInput = {\n addresses,\n businessDocument,\n customFields,\n marketingTags,\n id,\n name,\n phoneNumber,\n sellers,\n stateRegistration,\n paymentTerms,\n }\n\n const { id: costCenterId } = await CostCenterRepository.createCostCenter(\n _,\n organizationId,\n newCostCenter,\n ctx\n )\n\n return { id: costCenterId }\n },\n\n createCostCenterAddress: async (\n _: void,\n { costCenterId, address }: { costCenterId: string; address: AddressInput },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n try {\n const costCenter: CostCenterInput = await masterdata.getDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: ['addresses'],\n id: costCenterId,\n })\n\n const addresses = costCenter.addresses ?? []\n\n addresses.push(address)\n\n await masterdata.updatePartialDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: {\n addresses,\n },\n id: costCenterId,\n })\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'createCostCenterAddress-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n deleteCostCenter: async (_: void, { id }: { id: string }, ctx: Context) => {\n const {\n clients: { masterdata },\n } = ctx\n\n try {\n await masterdata.deleteDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n id,\n })\n\n return { status: 'success', message: '' }\n } catch (e) {\n throw new GraphQLError(getErrorMessage(e))\n }\n },\n\n deleteOrganization: async (_: void, { id }: { id: string }, ctx: Context) => {\n const {\n clients: { masterdata },\n } = ctx\n\n try {\n await masterdata.deleteDocument({\n dataEntity: ORGANIZATION_DATA_ENTITY,\n id,\n })\n\n return { status: 'success', message: '' }\n } catch (e) {\n throw new GraphQLError(getErrorMessage(e))\n }\n },\n\n updateCostCenter: async (\n _: void,\n {\n id,\n input: {\n name,\n addresses,\n paymentTerms,\n phoneNumber,\n businessDocument,\n stateRegistration,\n customFields,\n },\n }: { id: string; input: CostCenterInput },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n try {\n await masterdata.updatePartialDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: {\n name,\n ...(addresses?.length && { addresses }),\n ...(paymentTerms?.length && { paymentTerms }),\n ...((phoneNumber || phoneNumber === '') && { phoneNumber }),\n ...((stateRegistration || stateRegistration === '') && {\n stateRegistration,\n }),\n ...((businessDocument || businessDocument === '') && {\n businessDocument,\n }),\n ...((customFields || customFields === '') && {\n customFields,\n }),\n },\n id,\n })\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'updateCostCenter-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n updateCostCenterAddress: async (\n _: void,\n { costCenterId, address }: { costCenterId: string; address: AddressInput },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n try {\n const costCenter: CostCenterInput = await masterdata.getDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: ['addresses'],\n id: costCenterId,\n })\n\n let addresses = costCenter.addresses ?? []\n\n addresses = addresses.map((current: AddressInput) => {\n if (address.addressId === current.addressId) {\n return address\n }\n\n return current\n })\n\n await masterdata.updatePartialDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: {\n addresses,\n },\n id: costCenterId,\n })\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'updateCostCenterAddress-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n}\n\nexport default CostCenters\n\n```"
}
] |
code_b2b-organizations-graphql_d7e98e05
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Mutations/Users.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { MessageSFPUserAddError, StatusAddUserError } from '../../constants'\nimport GraphQLError, { getErrorMessage } from '../../utils/GraphQLError'\nimport type { ImpersonateMetricParams } from '../../utils/metrics/impersonate'\nimport {\n sendImpersonateB2BUserMetric,\n sendImpersonateUserMetric,\n} from '../../utils/metrics/impersonate'\nimport {\n sendAddUserMetric,\n sendRemoveUserMetric,\n sendUpdateUserMetric,\n} from '../../utils/metrics/user'\nimport type { UserArgs } from '../../typings'\n\nexport const getUserRoleSlug: (\n id: string,\n ctx: Context\n) => Promise<string> = async (id, ctx) => {\n const {\n clients: { storefrontPermissions },\n vtex: { logger },\n } = ctx\n\n return storefrontPermissions\n .getUser(id)\n .then((result: any) => {\n return result.data.getUser\n })\n .then((userData: any) => {\n return storefrontPermissions.getRole(userData.roleId)\n })\n .then((result: any) => {\n return result?.data?.getRole?.slug ?? ''\n })\n .catch((error: any) => {\n logger.warn({\n error,\n message: 'getUserRoleSlug-error',\n })\n\n return ''\n })\n}\n\nconst isUserPermitted = ({\n storefrontPermissions,\n sessionData,\n orgId,\n roleSlug,\n}: any) =>\n (storefrontPermissions?.permissions?.includes('add-users-organization') &&\n sessionData.namespaces['storefront-permissions']?.organization?.value ===\n orgId &&\n !roleSlug.includes('sales')) ||\n (storefrontPermissions?.permissions?.includes('add-sales-users-all') &&\n roleSlug.includes('sales'))\n\nconst getRoleSlug = async ({\n clId,\n ctx,\n logger,\n roleId,\n storefrontPermissionsClient,\n}: any) =>\n clId\n ? getUserRoleSlug(clId, ctx)\n : storefrontPermissionsClient\n .getRole(roleId)\n .then((result: any) => {\n return result?.data?.getRole?.slug ?? ''\n })\n .catch((error: any) => {\n logger.warn({\n error,\n message: 'saveUser-getRoleError',\n })\n\n return ''\n })\n\nconst getUser = async ({ masterdata, logger, userId, clId }: any) =>\n (await masterdata\n .getDocument({\n dataEntity: 'CL',\n fields: ['userId'],\n id: clId,\n })\n .then((res: any) => {\n return res?.userId ?? undefined\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'saveUser-getDocumentError',\n })\n\n return error\n })) ?? userId\n\nconst checkUserIsAllowed = async ({\n adminUserAuthToken,\n clId,\n ctx,\n logger,\n orgId,\n roleId,\n sessionData,\n storefrontPermissionsClient,\n storefrontPermissions,\n}: any) => {\n if (!adminUserAuthToken) {\n if (!sessionData?.namespaces['storefront-permissions']?.organization) {\n throw new GraphQLError('organization-data-not-found')\n }\n\n const roleSlug = await getRoleSlug({\n clId,\n ctx,\n logger,\n roleId,\n storefrontPermissionsClient,\n })\n\n const permitted = isUserPermitted({\n orgId,\n roleSlug,\n sessionData,\n storefrontPermissions,\n })\n\n if (!permitted) {\n throw new GraphQLError('operation-not-permitted')\n }\n }\n}\n\nconst getUserFromStorefrontPermissions = ({\n clId: clientId,\n storefrontPermissionsClient,\n logger,\n}: {\n clId: string\n storefrontPermissionsClient: any\n logger: any\n}) =>\n storefrontPermissionsClient\n .getUser(clientId)\n .then((result: any) => {\n return result?.data?.getUser ?? {}\n })\n .catch((error: any) => {\n logger.warn({\n error,\n message: 'impersonateUser-getUserError',\n })\n\n return error\n })\n\nconst Users = {\n impersonateB2BUser: async (_: void, { id }: { id: string }, ctx: Context) => {\n const {\n clients: { storefrontPermissions: storefrontPermissionsClient },\n\n vtex: { adminUserAuthToken, logger, sessionData, storefrontPermissions },\n } = ctx as Context | any\n\n const getB2BUserFromStorefrontPermissions = ({\n id: b2bId,\n }: {\n id: string\n }) =>\n storefrontPermissionsClient\n .getB2BUser(b2bId)\n .then((result: any) => result?.data?.getB2BUser ?? {})\n\n const user = await getB2BUserFromStorefrontPermissions({ id })\n\n if (!adminUserAuthToken) {\n if (!sessionData?.namespaces['storefront-permissions']?.organization) {\n throw new GraphQLError('organization-data-not-found')\n }\n\n const canImpersonateUsersWithCostCenterPermission =\n storefrontPermissions?.permissions?.includes(\n 'impersonate-users-costcenter'\n ) &&\n user?.costId ===\n sessionData?.namespaces['storefront-permissions']?.costcenter?.value\n\n const canImpersonateUsersWithOrganizationPermission =\n storefrontPermissions?.permissions?.includes(\n 'impersonate-users-organization'\n ) &&\n user?.orgId ===\n sessionData?.namespaces['storefront-permissions']?.organization?.value\n\n const canImpersonateUsersWithAllPermission =\n storefrontPermissions?.permissions?.includes('impersonate-users-all')\n\n if (\n !canImpersonateUsersWithCostCenterPermission &&\n !canImpersonateUsersWithOrganizationPermission &&\n !canImpersonateUsersWithAllPermission\n ) {\n throw new GraphQLError('operation-not-permitted')\n }\n }\n\n const impersonation = await storefrontPermissionsClient\n .impersonateUser({ userId: id })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'impersonateUser-impersonateUserError',\n })\n\n return { status: 'error', message: error }\n })\n\n if (impersonation?.errors) {\n throw new GraphQLError(impersonation?.errors)\n }\n\n const {\n orgId: targetOrganizationId,\n costId: targetCostCenterId,\n id: targetId,\n email: targetEmail,\n } = user\n\n const metricParams: ImpersonateMetricParams = {\n account: sessionData?.namespaces?.account?.accountName,\n target: {\n costCenterId: targetCostCenterId,\n organizationId: targetOrganizationId,\n email: targetEmail,\n id: targetId,\n },\n user: {\n costCenterId:\n sessionData?.namespaces['storefront-permissions']?.costcenter.value,\n organizationId:\n sessionData?.namespaces['storefront-permissions']?.organization.value,\n email: sessionData?.namespaces?.profile?.email.value,\n id: sessionData?.namespaces['storefront-permissions']?.userId.value,\n },\n }\n\n sendImpersonateB2BUserMetric(ctx, metricParams)\n\n return (\n impersonation?.data?.impersonateUser ?? {\n status: 'error',\n }\n )\n },\n /**\n *\n * Mutation to impersonate a user\n *\n * @param _\n * @param clId\n * @param userId\n * @param ctx\n */\n impersonateUser: async (\n _: void,\n { clId, userId }: UserArgs,\n ctx: Context\n ) => {\n const {\n clients: {\n masterdata,\n storefrontPermissions: storefrontPermissionsClient,\n },\n\n vtex: { adminUserAuthToken, logger, sessionData, storefrontPermissions },\n } = ctx as Context | any\n\n if (!adminUserAuthToken && clId) {\n if (!sessionData?.namespaces['storefront-permissions']?.organization) {\n throw new GraphQLError('organization-data-not-found')\n }\n\n const userInfo = await getUserFromStorefrontPermissions({\n clId,\n logger,\n storefrontPermissionsClient,\n })\n\n const canImpersonateUsersWithCostCenterPermission =\n storefrontPermissions?.permissions?.includes(\n 'impersonate-users-costcenter'\n ) &&\n userInfo?.costId ===\n sessionData?.namespaces['storefront-permissions']?.costcenter?.value\n\n const canImpersonateUsersWithOrganizationPermission =\n storefrontPermissions?.permissions?.includes(\n 'impersonate-users-organization'\n ) &&\n userInfo?.orgId ===\n sessionData?.namespaces['storefront-permissions']?.organization?.value\n\n const canImpersonateUsersWithAllPermission =\n storefrontPermissions?.permissions?.includes('impersonate-users-all')\n\n if (\n !canImpersonateUsersWithCostCenterPermission &&\n !canImpersonateUsersWithOrganizationPermission &&\n !canImpersonateUsersWithAllPermission\n ) {\n throw new GraphQLError('operation-not-permitted')\n }\n }\n\n if (!userId && clId) {\n const userIdFromCl = await masterdata\n .getDocument({\n dataEntity: 'CL',\n fields: ['userId'],\n id: clId,\n })\n .then((res: any) => {\n return res?.userId ?? undefined\n })\n .catch((error: any) => {\n logger.warn({\n error,\n message: 'impersonateUser-getUserIdError',\n })\n\n return error\n })\n\n if (!userIdFromCl) {\n logger.warn({\n message: `userId ${userIdFromCl} not found in CL`,\n })\n\n return { status: 'error', message: 'userId not found in CL' }\n }\n\n userId = userIdFromCl\n\n const userData = await getUserFromStorefrontPermissions({\n clId,\n logger,\n storefrontPermissionsClient,\n })\n\n if (userData && !userData.userId) {\n await storefrontPermissionsClient.saveUser({\n ...userData,\n userId,\n })\n }\n }\n\n return impersonateUser(\n ctx,\n storefrontPermissionsClient,\n userId,\n logger,\n sessionData?.namespaces?.account?.accountName,\n sessionData?.namespaces['storefront-permissions']\n )\n },\n\n removeUserWithEmail: async (\n _: void,\n { orgId, costId, email }: UserArgs,\n ctx: Context\n ) => {\n const {\n clients: { events, storefrontPermissions: storefrontPermissionsClient },\n vtex: { logger },\n } = ctx as any\n\n return storefrontPermissionsClient\n .getUsersByEmail(email, orgId, costId)\n .then((result: any) => {\n const user = result.data.getUsersByEmail[0]\n\n if (!user) {\n logger.error({ message: 'User not found' })\n\n return { status: 'error', message: 'User not found' }\n }\n\n const { id } = user\n const { userId } = user\n\n const fields = {\n email,\n id,\n userId,\n }\n\n return storefrontPermissionsClient\n .deleteUser(fields)\n .then((response: any) => {\n events.sendEvent('', 'b2b-organizations-graphql.removeUser', {\n id,\n email,\n })\n sendRemoveUserMetric(ctx, logger, ctx.vtex.account, fields)\n\n return response.data.deleteUser\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'removeUser-deleteUserError',\n })\n\n return { status: 'error', message: error }\n })\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'getUsers-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n })\n },\n\n /**\n *\n * Mutation to remove a user\n *\n * @param _\n * @param id\n * @param userId\n * @param email\n * @param clId\n * @param ctx\n */\n removeUser: async (\n _: void,\n { id, userId, email, clId }: UserArgs,\n ctx: Context\n ) => {\n const {\n clients: { events, storefrontPermissions: storefrontPermissionsClient },\n vtex: { adminUserAuthToken, logger, sessionData, storefrontPermissions },\n } = ctx as Context | any\n\n if (!id || !clId || !email) {\n throw new GraphQLError('user-information-not-provided')\n }\n\n if (!adminUserAuthToken) {\n if (!sessionData?.namespaces['storefront-permissions']?.organization) {\n throw new GraphQLError('organization-data-not-found')\n }\n\n const roleSlug = await getUserRoleSlug(clId, ctx)\n\n const permitted =\n (storefrontPermissions?.permissions?.includes(\n 'remove-users-organization'\n ) &&\n !roleSlug.includes('sales')) ||\n storefrontPermissions?.permissions?.includes('remove-sales-users-all')\n\n if (!permitted) {\n throw new GraphQLError('operation-not-permitted')\n }\n }\n\n const fields = {\n email,\n id,\n userId,\n }\n\n return storefrontPermissionsClient\n .deleteUser(fields)\n .then((result: any) => {\n events.sendEvent('', 'b2b-organizations-graphql.removeUser', {\n id,\n email,\n })\n\n sendRemoveUserMetric(ctx, logger, ctx.vtex.account, fields)\n\n return result.data.deleteUser\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'removeUser-deleteUserError',\n })\n\n return { status: 'error', message: error }\n })\n },\n\n addUser: async (\n _: void,\n { id, roleId, userId, orgId, costId, clId, name, email }: UserArgs,\n ctx: Context\n ) => {\n const {\n clients: { storefrontPermissions: storefrontPermissionsClient },\n vtex: { adminUserAuthToken, logger, sessionData, storefrontPermissions },\n } = ctx as any\n\n try {\n await checkUserIsAllowed({\n adminUserAuthToken,\n clId,\n ctx,\n logger,\n orgId,\n roleId,\n sessionData,\n storefrontPermissions,\n storefrontPermissionsClient,\n })\n } catch (error) {\n logger.error({\n error,\n message: 'addUser-checkUserIsAllowedError',\n })\n throw error\n }\n\n const fields = {\n costId,\n email,\n id,\n name,\n orgId,\n roleId,\n userId,\n }\n\n return storefrontPermissionsClient\n .addUser(fields)\n .then((result: any) => {\n sendAddUserMetric(ctx, logger, ctx.vtex.account, fields)\n\n return result.data.addUser\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'addUser-error',\n })\n\n const message = error.graphQLErrors[0]?.message ?? error.message\n let status = ''\n\n if (message.includes(MessageSFPUserAddError.DUPLICATED)) {\n status = StatusAddUserError.DUPLICATED\n } else if (\n message.includes(MessageSFPUserAddError.DUPLICATED_ORGANIZATION)\n ) {\n status = StatusAddUserError.DUPLICATED_ORGANIZATION\n } else {\n status = StatusAddUserError.ERROR\n }\n\n return { status, message }\n })\n },\n\n createUserWithEmail: async (\n _: void,\n { orgId, costId, roleId, name, email, canImpersonate }: UserArgs,\n ctx: Context\n ) => {\n const {\n clients: { storefrontPermissions: storefrontPermissionsClient },\n vtex: { logger },\n } = ctx as any\n\n try {\n const result = await storefrontPermissionsClient.addUser({\n orgId,\n costId,\n roleId,\n name,\n email,\n canImpersonate,\n })\n\n return result.data.addUser\n } catch (error) {\n logger.error({\n error,\n message: 'createUserWithEmail-error',\n })\n const message = error.graphQLErrors?.[0]?.message ?? error.message\n let status = ''\n\n if (message.includes(MessageSFPUserAddError.DUPLICATED)) {\n status = StatusAddUserError.DUPLICATED\n } else if (\n message.includes(MessageSFPUserAddError.DUPLICATED_ORGANIZATION)\n ) {\n status = StatusAddUserError.DUPLICATED_ORGANIZATION\n } else {\n status = StatusAddUserError.ERROR\n }\n\n return { status, message }\n }\n },\n\n updateUser: async (\n _: void,\n { id, roleId, userId, orgId, costId, clId, name, email }: UserArgs,\n ctx: Context\n ) => {\n const {\n clients: {\n masterdata,\n storefrontPermissions: storefrontPermissionsClient,\n },\n vtex: { adminUserAuthToken, logger, sessionData, storefrontPermissions },\n } = ctx as any\n\n try {\n await checkUserIsAllowed({\n adminUserAuthToken,\n clId,\n ctx,\n logger,\n orgId,\n roleId,\n sessionData,\n storefrontPermissions,\n storefrontPermissionsClient,\n })\n } catch (error) {\n logger.error({\n error,\n message: 'addUser-checkUserIsAllowedError',\n })\n throw error\n }\n\n if (clId && !userId) {\n userId = await getUser({\n clId,\n logger,\n masterdata,\n userId,\n })\n }\n\n const fields = {\n clId,\n costId,\n email,\n id,\n name,\n orgId,\n roleId,\n userId,\n }\n\n return storefrontPermissionsClient\n .updateUser(fields)\n .then((result: any) => {\n sendUpdateUserMetric(ctx, logger, ctx.vtex.account, fields)\n\n return result.data.updateUser\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'updateUser-error',\n })\n\n return { status: 'error', message: error }\n })\n },\n\n /**\n *\n * Create and update a user\n *\n * @deprecated\n *\n * @param _\n * @param id\n * @param roleId\n * @param userId\n * @param orgId\n * @param costId\n * @param clId\n * @param name\n * @param email\n * @param ctx\n */\n saveUser: async (\n _: void,\n { id, roleId, userId, orgId, costId, clId, name, email }: UserArgs,\n ctx: Context\n ) => {\n const {\n clients: {\n masterdata,\n storefrontPermissions: storefrontPermissionsClient,\n },\n vtex: { adminUserAuthToken, logger, sessionData, storefrontPermissions },\n } = ctx as any\n\n try {\n await checkUserIsAllowed({\n adminUserAuthToken,\n clId,\n ctx,\n logger,\n orgId,\n roleId,\n sessionData,\n storefrontPermissions,\n storefrontPermissionsClient,\n })\n } catch (error) {\n logger.error({\n error,\n message: 'addUser-checkUserIsAllowedError',\n })\n throw error\n }\n\n if (clId && !userId) {\n userId = await getUser({\n clId,\n logger,\n masterdata,\n userId,\n })\n }\n\n return storefrontPermissionsClient\n .saveUser({\n clId,\n costId,\n email,\n id,\n name,\n orgId,\n roleId,\n userId,\n })\n .then((result: any) => {\n return result.data.saveUser\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'addUser-error',\n })\n\n return { status: 'error', message: error }\n })\n },\n}\n\nexport default Users\n\nasync function impersonateUser(\n ctx: Context,\n storefrontPermissionsClient: any,\n userId: string | undefined,\n logger: any,\n accountName: string,\n storefrontPermissions: {\n costcenter: { value: string }\n userId: { value: string }\n organization: { value: string }\n storeUserEmail: { value: string }\n }\n) {\n return storefrontPermissionsClient\n .impersonateUser({ userId })\n .then((_: any) => {\n const {\n costcenter,\n userId: userTargetId,\n organization,\n storeUserEmail,\n } = storefrontPermissions\n\n const metricParams: ImpersonateMetricParams = {\n account: accountName,\n target: {\n costCenterId: costcenter.value,\n organizationId: organization.value,\n email: storeUserEmail.value,\n id: userTargetId.value,\n },\n user: undefined, // no information about original user at this point\n }\n\n sendImpersonateUserMetric(ctx, metricParams)\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'impersonateUser-impersonateUserError',\n })\n\n return { status: 'error', message: error }\n })\n}\n\n```"
}
] |
code_b2b-organizations-graphql_4700bfbc
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Mutations/MarketingTags.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { MARKETING_TAGS } from '../../utils/constants'\n\nconst MarketingTags = {\n setMarketingTags: async (\n _: void,\n { costId, tags }: { costId: string; tags: string[] },\n ctx: Context\n ) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n if (!costId || !tags) {\n throw new Error('Invalid parameters')\n }\n\n try {\n await vbase.saveJSON(MARKETING_TAGS.VBASE_BUCKET, costId, {\n tags,\n })\n\n return { status: 'success', message: '', id: costId }\n } catch (error) {\n logger.error({\n error,\n message: 'setMarketingTags.error',\n })\n\n return { status: 'error', message: error }\n }\n },\n}\n\nexport default MarketingTags\n\n```"
}
] |
code_b2b-organizations-graphql_556c3924
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Queries/Settings.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport GraphQLError from '../../utils/GraphQLError'\nimport checkConfig from '../config'\nimport type { B2BSettingsInput } from '../../typings'\nimport type { GetSellersOpts } from '../../clients/sellers'\n\nconst B2BSettings = {\n getB2BSettings: async (_: void, __: void, ctx: Context) => {\n const {\n clients: { vbase },\n } = ctx\n\n const B2B_SETTINGS_DATA_ENTITY = 'b2b_settings'\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n let settings: Partial<B2BSettingsInput> | null = null\n\n try {\n settings = await vbase.getJSON<B2BSettingsInput | null>(\n B2B_SETTINGS_DATA_ENTITY,\n 'settings',\n true\n )\n\n settings = {\n ...settings,\n // if custom fields are null, set to an empty array\n costCenterCustomFields: settings?.costCenterCustomFields ?? [],\n organizationCustomFields: settings?.organizationCustomFields ?? [],\n transactionEmailSettings: settings?.transactionEmailSettings ?? {\n organizationApproved: true,\n organizationCreated: true,\n organizationDeclined: true,\n organizationRequestCreated: false,\n organizationStatusChanged: true,\n },\n }\n } catch (e) {\n if (e.message) {\n throw new GraphQLError(e.message)\n } else if (e.response?.data?.message) {\n throw new GraphQLError(e.response.data.message)\n } else {\n throw new GraphQLError(e)\n }\n }\n\n return settings\n },\n getSellers: async (_: void, __: void, ctx: Context) => {\n const {\n clients: { sellers },\n } = ctx\n\n return (await sellers.getSellers())?.items\n },\n getSellersPaginated: async (\n _: void,\n options: GetSellersOpts,\n ctx: Context\n ) => {\n const {\n clients: { sellers },\n } = ctx\n\n try {\n return await sellers.getSellersPaginated(options)\n } catch (e) {\n if (e.message) {\n throw new GraphQLError(e.message)\n } else if (e.response?.data?.message) {\n throw new GraphQLError(e.response.data.message)\n } else {\n throw new GraphQLError(e)\n }\n }\n },\n getAccount: async (_: void, __: void, ctx: Context) => {\n const {\n clients: { lm },\n } = ctx\n\n return lm.getAccount().catch((e) => {\n if (e.message) {\n throw new GraphQLError(e.message)\n } else if (e.response?.data?.message) {\n throw new GraphQLError(e.response.data.message)\n } else {\n throw new GraphQLError(e)\n }\n })\n },\n}\n\nexport default B2BSettings\n\n```"
}
] |
code_b2b-organizations-graphql_785c517b
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Queries/Organizations.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n ORGANIZATION_DATA_ENTITY,\n ORGANIZATION_FIELDS,\n ORGANIZATION_REQUEST_DATA_ENTITY,\n ORGANIZATION_REQUEST_FIELDS,\n ORGANIZATION_REQUEST_SCHEMA_VERSION,\n ORGANIZATION_SCHEMA_VERSION,\n} from '../../mdSchema'\nimport type {\n GetOrganizationsByEmailWithStatus,\n Organization,\n} from '../../typings'\nimport GraphQLError, { getErrorMessage } from '../../utils/GraphQLError'\nimport checkConfig from '../config'\nimport { organizationStatus } from '../fieldResolvers'\n\nconst getWhereByStatus = ({ status }: { status: string[] }) => {\n const whereArray = []\n\n if (status?.length) {\n const statusArray = [] as string[]\n\n status.forEach((stat) => {\n statusArray.push(`status=${stat}`)\n })\n const statuses = `(${statusArray.join(' OR ')})`\n\n whereArray.push(statuses)\n }\n\n return whereArray\n}\n\nconst Organizations = {\n checkOrganizationIsActive: async (\n _: void,\n params: { id: string } | null,\n ctx: Context\n ) => {\n const {\n clients: { session },\n vtex: { logger, sessionToken, adminUserAuthToken },\n } = ctx\n\n const sessionData = await session\n .getSession(sessionToken as string, ['*'])\n .then((currentSession: any) => {\n return currentSession.sessionData\n })\n .catch((error: any) => {\n logger.warn({\n error,\n message: 'checkOrganizationIsActive-error',\n })\n\n return null\n })\n\n if (!sessionData) {\n throw new Error('No session data for this current user')\n }\n\n let orgId =\n sessionData?.namespaces?.['storefront-permissions']?.organization?.value\n\n if (params?.id && adminUserAuthToken) {\n orgId = params?.id\n }\n\n const organization = (await Organizations.getOrganizationById(\n _,\n { id: orgId },\n ctx\n )) as { status: string; permissions?: { createQuote: boolean } }\n\n if (!organization) {\n throw new Error('Organization not found')\n }\n\n return organization?.status === 'active'\n },\n\n getOrganizationById: async (\n _: void,\n { id }: { id: string },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n try {\n const org: Organization = await masterdata.getDocument({\n dataEntity: ORGANIZATION_DATA_ENTITY,\n fields: ORGANIZATION_FIELDS,\n id,\n })\n\n return {\n ...org,\n // the previous data registered doesn't have this propertty on masterdata\n // so we need to add it to the response\n permissions: org.permissions ?? { createQuote: true },\n }\n } catch (error) {\n logger.error({ error, message: 'getOrganizationById-error' })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getOrganizations: async (\n _: void,\n {\n status,\n search,\n page,\n pageSize,\n sortOrder,\n sortedBy,\n }: {\n status: string[]\n search: string\n page: number\n pageSize: number\n sortOrder: string\n sortedBy: string\n },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n const whereArray = getWhereByStatus({ status })\n\n if (search) {\n whereArray.push(`name=\"*${search}*\"`)\n }\n\n const where = whereArray.join(' AND ')\n\n try {\n const organizationsDB =\n (await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: ORGANIZATION_DATA_ENTITY,\n fields: ORGANIZATION_FIELDS,\n pagination: { page, pageSize },\n schema: ORGANIZATION_SCHEMA_VERSION,\n sort: `${sortedBy} ${sortOrder}`,\n ...(where && { where }),\n })) as {\n data: Organization[]\n pagination: { total: number; page: number; pageSize: number }\n }\n\n const mappedOrganizations = organizationsDB.data.map((org) => {\n return {\n ...org,\n // the previous data registered doesn't have this propertty on masterdata\n // so we need to add it to the response\n permissions: org.permissions ?? { createQuote: true },\n }\n })\n\n return {\n data: mappedOrganizations,\n pagination: organizationsDB.pagination,\n }\n } catch (error) {\n logger.error({\n error,\n message: 'getOrganizations-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getOrganizationsByEmail: async (\n _: void,\n { email }: { email: string },\n ctx: Context\n ) => {\n const {\n clients: { storefrontPermissions, session },\n vtex: { logger, sessionToken, adminUserAuthToken },\n } = ctx\n\n const organizationFilters: string[] = []\n let fromSession = false\n\n const sessionData = await session\n .getSession(sessionToken as string, ['*'])\n .then((currentSession: any) => {\n return currentSession.sessionData\n })\n .catch((error: any) => {\n logger.warn({\n error,\n message: 'getOrganizationsByEmail-session-error',\n })\n\n return null\n })\n\n let checkUserPermission = null\n\n if (sessionData?.namespaces) {\n const checkUserPermissionResult = await storefrontPermissions\n .checkUserPermission('vtex.b2b-organizations@3.x')\n .catch((error: any) => {\n logger.error({\n error,\n message: 'checkUserPermission-error',\n })\n\n return {\n data: {\n checkUserPermission: null,\n },\n }\n })\n\n checkUserPermission = checkUserPermissionResult?.data?.checkUserPermission\n }\n\n if (\n (!adminUserAuthToken &&\n !checkUserPermission?.permissions.includes('add-sales-users-all')) ||\n !(email?.length > 0)\n ) {\n if (checkUserPermission?.permissions.includes('add-users-organization')) {\n const orgId =\n sessionData?.namespaces?.['storefront-permissions']?.organization\n ?.value\n\n if (!orgId) {\n throw new Error('No permission for getting the organizations')\n }\n\n organizationFilters.push(orgId)\n }\n\n if (!(email?.length > 0)) {\n email = sessionData?.namespaces?.profile?.email?.value\n fromSession = true\n }\n }\n\n const organizations = (\n await storefrontPermissions.getOrganizationsByEmail(email)\n ).data?.getOrganizationsByEmail?.filter(({ orgId }: { orgId: string }) => {\n return (\n fromSession ||\n (organizationFilters.length > 0\n ? organizationFilters.find((id: string) => orgId === id)\n : true)\n )\n })\n\n try {\n return organizations\n } catch (error) {\n logger.error({\n error,\n message: 'getOrganizationsByEmail-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getActiveOrganizationsByEmail: async (\n _: void,\n { email }: { email: string },\n ctx: Context\n ) => {\n const {\n vtex: { logger },\n } = ctx\n\n const organizations = await Organizations.getOrganizationsByEmail(\n _,\n { email },\n ctx\n )\n\n const organizationsWithStatus: GetOrganizationsByEmailWithStatus[] =\n await Promise.all(\n organizations.map(async (organization: { orgId: string }) => {\n const status = await organizationStatus(\n { orgId: organization.orgId },\n _,\n ctx\n )\n\n return { ...organization, status }\n })\n )\n\n const activeOrganizations = organizationsWithStatus.filter(\n (organization) => organization.status === 'active'\n )\n\n try {\n return activeOrganizations\n } catch (error) {\n logger.error({\n error,\n message: 'getActiveOrganizationsByEmail-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getOrganizationsPaginatedByEmail: async (\n _: void,\n {\n email,\n page = 1,\n pageSize = 25,\n }: {\n email?: string\n page: number\n pageSize: number\n },\n { clients: { storefrontPermissions }, vtex: { logger } }: any\n ) => {\n try {\n const {\n data: { getOrganizationsPaginatedByEmail },\n } = await storefrontPermissions.getOrganizationsPaginatedByEmail(\n email,\n page,\n pageSize\n )\n\n return getOrganizationsPaginatedByEmail\n } catch (error) {\n logger.error({\n error,\n message: 'getOrganizationsPaginatedByEmail-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getOrganizationByIdStorefront: async (\n _: void,\n { id }: { id: string },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { sessionData, logger },\n } = ctx as any\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n if (!sessionData?.namespaces['storefront-permissions']) {\n throw new GraphQLError('organization-data-not-found')\n }\n\n const {\n organization: { value: userOrganizationId },\n } = sessionData.namespaces['storefront-permissions'] ?? {\n organization: {\n value: null,\n },\n }\n\n if (!id) {\n // get user's organization from session\n id = userOrganizationId\n }\n\n if (id !== userOrganizationId) {\n throw new GraphQLError('operation-not-permitted')\n }\n\n const organization: Organization = await masterdata.getDocument({\n dataEntity: ORGANIZATION_DATA_ENTITY,\n fields: ORGANIZATION_FIELDS,\n id,\n })\n\n if (organization?.status !== 'active') {\n throw new Error('This organization is not active')\n }\n\n try {\n return {\n ...organization,\n permissions: organization.permissions ?? { createQuote: true },\n }\n } catch (error) {\n logger.error({\n error,\n message: 'getOrganizationByIdStorefront-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getOrganizationRequestById: async (\n _: void,\n { id }: { id: string },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n try {\n return await masterdata.getDocument({\n dataEntity: ORGANIZATION_REQUEST_DATA_ENTITY,\n fields: ORGANIZATION_REQUEST_FIELDS,\n id,\n })\n } catch (error) {\n logger.error({\n error,\n message: 'getOrganizationRequestById-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getOrganizationRequests: async (\n _: void,\n {\n status,\n search,\n page,\n pageSize,\n sortOrder,\n sortedBy,\n }: {\n status: string[]\n search: string\n page: number\n pageSize: number\n sortOrder: string\n sortedBy: string\n },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n const whereArray = getWhereByStatus({ status })\n\n if (search) {\n if (search.match(/[a-z\\d]+@[a-z]+\\.[a-z]{2,3}/gm)) {\n whereArray.push(`b2bCustomerAdmin.email=${search}`)\n } else {\n whereArray.push(`name=\"*${search}*\"`)\n }\n }\n\n const where = whereArray.join(' AND ')\n\n try {\n return await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: ORGANIZATION_REQUEST_DATA_ENTITY,\n fields: ORGANIZATION_REQUEST_FIELDS,\n pagination: { page, pageSize },\n schema: ORGANIZATION_REQUEST_SCHEMA_VERSION,\n sort: `${sortedBy} ${sortOrder}`,\n ...(where && { where }),\n })\n } catch (error) {\n logger.error({\n error,\n message: 'getOrganizationRequests-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n}\n\nexport default Organizations\n\n```"
}
] |
code_b2b-organizations-graphql_9ca8ca77
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Queries/CostCenters.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n COST_CENTER_DATA_ENTITY,\n COST_CENTER_FIELDS,\n COST_CENTER_SCHEMA_VERSION,\n} from '../../mdSchema'\nimport type { Address, CostCenter } from '../../typings'\nimport GraphQLError, { getErrorMessage } from '../../utils/GraphQLError'\nimport checkConfig from '../config'\nimport Organizations from './Organizations'\n\nconst getCostCenters = async ({\n id,\n masterdata,\n page,\n pageSize,\n search,\n sortOrder,\n sortedBy,\n}: any) => {\n const searchClause = search ? ` AND name=\"*${search}*\"` : ''\n const where = `organization=${id}${searchClause}`\n\n try {\n return await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: COST_CENTER_FIELDS,\n pagination: { page, pageSize },\n schema: COST_CENTER_SCHEMA_VERSION,\n sort: `${sortedBy} ${sortOrder}`,\n ...(where && { where }),\n })\n } catch (error) {\n throw new GraphQLError(getErrorMessage(error))\n }\n}\n\nconst hashCode = function hash(arg: null | string | number | number[]) {\n const str = arg === null ? '' : arg.toString()\n\n if (str.length === 0) {\n return 0\n }\n\n return str.split('').reduce((a, b) => ((a << 5) - a + b.charCodeAt(0)) | 0, 0)\n}\n\nconst setGUID = (address: Address) => {\n return (\n hashCode(address.street) +\n hashCode(address.complement) +\n hashCode(address.city) +\n hashCode(address.state)\n ).toString()\n}\n\nconst addMissingAddressIds = async (costCenter: CostCenter, ctx: Context) => {\n const {\n clients: { masterdata },\n } = ctx\n\n let changed = false\n const { addresses } = costCenter\n\n for (const [index, address] of addresses.entries()) {\n if (!address.addressId) {\n addresses[index].addressId = setGUID(address)\n changed = true\n }\n }\n\n if (changed) {\n await masterdata.createOrUpdatePartialDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: { addresses },\n id: costCenter.id,\n })\n }\n\n return addresses\n}\n\nconst costCenters = {\n getCostCenterById: async (_: void, { id }: { id: string }, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n try {\n const result: CostCenter = await masterdata.getDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: COST_CENTER_FIELDS,\n id,\n })\n\n /* MasterData client returns empty string when it doesn't find the document */\n if ((result as unknown as string) !== '') {\n result.addresses = await addMissingAddressIds(result, ctx)\n }\n\n return result\n } catch (error) {\n logger.error({ error, message: 'getCostCenterById-error' })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getCostCenterByIdStorefront: async (\n _: void,\n { id }: { id: string },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n vtex,\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n if (!(await Organizations.checkOrganizationIsActive(_, null, ctx))) {\n throw new Error('This organization is not active')\n }\n\n const { sessionData } = vtex as any\n\n if (!sessionData?.namespaces['storefront-permissions']) {\n throw new GraphQLError('organization-data-not-found')\n }\n\n const {\n organization: { value: userOrganizationId },\n costcenter: { value: userCostCenterId },\n } = sessionData.namespaces['storefront-permissions'] ?? {\n organization: {\n value: null,\n },\n costcenter: {\n value: null,\n },\n }\n\n if (!id) {\n // get user's organization from session\n id = userCostCenterId\n }\n\n try {\n const costCenter: CostCenter = await masterdata.getDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: COST_CENTER_FIELDS,\n id,\n })\n\n if (costCenter.organization !== userOrganizationId) {\n const error = () => {\n throw new GraphQLError('operation-not-permitted')\n }\n\n error()\n }\n\n costCenter.addresses = await addMissingAddressIds(costCenter, ctx)\n\n return costCenter\n } catch (error) {\n logger.error({ error, message: 'getCostCenterByIdStorefront-error' })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getPaymentTerms: async (_: void, __: void, ctx: Context) => {\n const {\n clients: { payments },\n vtex: { logger },\n } = ctx\n\n try {\n return await payments.getPaymentTerms()\n } catch (error) {\n logger.error({ error, message: 'getPaymentTerms-error' })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getCostCenters: async (\n _: void,\n {\n search,\n page,\n pageSize,\n sortOrder,\n sortedBy,\n }: {\n search: string\n page: number\n pageSize: number\n sortOrder: string\n sortedBy: string\n },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n let where = ''\n\n if (search) {\n where = `name=\"*${search}*\" OR businessDocument=\"*${search}*\"`\n }\n\n try {\n return await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: COST_CENTER_FIELDS,\n pagination: { page, pageSize },\n schema: COST_CENTER_SCHEMA_VERSION,\n sort: `${sortedBy} ${sortOrder}`,\n ...(where && { where }),\n })\n } catch (error) {\n logger.error({\n error,\n message: 'getCostCenters-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n },\n\n getCostCentersByOrganizationId: async (\n _: void,\n {\n id,\n search,\n page,\n pageSize,\n sortOrder,\n sortedBy,\n }: {\n id: string\n search: string\n page: number\n pageSize: number\n sortOrder: string\n sortedBy: string\n },\n ctx: Context\n ) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n try {\n return await getCostCenters({\n id,\n masterdata,\n page,\n pageSize,\n search,\n sortOrder,\n sortedBy,\n })\n } catch (error) {\n logger.error({\n error,\n message: 'getCostCentersByOrganizationId-error',\n })\n throw error\n }\n },\n\n getCostCentersByOrganizationIdStorefront: async (\n _: void,\n {\n id,\n search,\n page,\n pageSize,\n sortOrder,\n sortedBy,\n }: {\n id: string\n search: string\n page: number\n pageSize: number\n sortOrder: string\n sortedBy: string\n },\n ctx: Context\n ) => {\n const {\n clients: { masterdata, storefrontPermissions },\n vtex: { logger, sessionData },\n } = ctx as any\n\n // create schema if it doesn't exist\n await checkConfig(ctx)\n\n if (!(await Organizations.checkOrganizationIsActive(_, null, ctx))) {\n throw new Error('This organization is not active')\n }\n\n let checkUserPermission = null\n\n if (sessionData?.namespaces) {\n const checkUserPermissionResult = await storefrontPermissions\n .checkUserPermission('vtex.b2b-organizations@3.x')\n .catch((error: any) => {\n logger.error({\n error,\n message: 'checkUserPermission-error',\n })\n\n return {\n data: {\n checkUserPermission: null,\n },\n }\n })\n\n checkUserPermission = checkUserPermissionResult?.data?.checkUserPermission\n }\n\n const isSalesAdmin = checkUserPermission?.role.slug.match(/sales-admin/)\n\n if (!isSalesAdmin) {\n if (!sessionData?.namespaces['storefront-permissions']) {\n throw new GraphQLError('organization-data-not-found')\n }\n\n const {\n organization: { value: userOrganizationId },\n } = sessionData.namespaces['storefront-permissions'] ?? {\n organization: {\n value: null,\n },\n }\n\n if (!id) {\n // get user's organization from session\n id = userOrganizationId\n }\n\n if (id !== userOrganizationId) {\n throw new GraphQLError('operation-not-permitted')\n }\n }\n\n try {\n return await getCostCenters({\n id,\n masterdata,\n page,\n pageSize,\n search,\n sortOrder,\n sortedBy,\n })\n } catch (error) {\n logger.error({\n error,\n message: 'getCostCentersByOrganizationId-error',\n })\n throw error\n }\n },\n}\n\nexport default costCenters\n\n```"
}
] |
code_b2b-organizations-graphql_6632cbf6
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Queries/Users.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n ORGANIZATION_DATA_ENTITY,\n ORGANIZATION_FIELDS,\n ORGANIZATION_SCHEMA_VERSION,\n schemas,\n} from '../../mdSchema'\nimport { toHash } from '../../utils'\nimport GraphQLError, { getErrorMessage } from '../../utils/GraphQLError'\nimport { getAppId } from '../config'\n\nconst SCROLL_AWAIT_TIME = 100\nconst SLEEP_ADD_PERCENTAGE = 0.1\nconst SCROLL_SIZE = 1000\n\nconst USER_DATA_ENTITY = 'b2b_users'\nconst USER_DATA_ENTITY_SCHEMA = 'v0.1.2'\n\n// This function checks if given email is an user part of a buyer org.\nexport const isUserPartOfBuyerOrg = async (email: string, ctx: Context) => {\n const {\n clients: { masterdata },\n } = ctx\n\n try {\n const where = `email=${email}`\n const resp = await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: USER_DATA_ENTITY,\n fields: ['id'], // we don't need to fetch all fields, only if there is an entry or not\n pagination: {\n page: 1,\n pageSize: 1, // we only need to know if there is at least one user entry\n },\n schema: USER_DATA_ENTITY_SCHEMA,\n ...(where ? { where } : {}),\n })\n\n const { data } = resp as unknown as {\n data: any\n }\n\n if (data.length > 0) {\n return true\n }\n } catch (error) {\n // if it fails at somepoint, we treat it like no user was found\n // on any buyer org, so we just let the function return false\n }\n\n return false\n}\n\n/**\n * Checks the permissions by applying the following rules:\n * @param checkUserPermission\n */\nconst isSalesAdmin = (checkUserPermission: any) =>\n checkUserPermission?.role.slug.match(/sales-admin/) || false\n\nconst getCheckUserPermission = async ({\n storefrontPermissions,\n logger,\n}: any) => {\n const {\n data: { checkUserPermission },\n }: any = await storefrontPermissions\n .checkUserPermission('vtex.b2b-organizations@3.x')\n .catch((error: any) => {\n logger.error({\n error,\n message: 'checkUserPermission-error',\n })\n\n return {\n data: {\n checkUserPermission: null,\n },\n }\n })\n\n return checkUserPermission\n}\n\nconst getChannels = async (ctx: Context) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n let channels = {}\n\n try {\n channels = await vbase.getJSON('b2borg', 'salesChannels')\n } catch (err) {\n if (err.response.status === 404) {\n await vbase.saveJSON('b2borg', 'salesChannels', {})\n } else {\n logger.error({\n error: err,\n message: 'getChannels-Error',\n })\n }\n }\n\n return channels\n}\n\n/**\n * Checks the user permissions and returns the organizationId updated\n * @param validateUserAdmin\n * @param vtex\n * @param storefrontPermissions\n * @param adminUserAuthToken\n * @param organizationId\n * @param logger\n */\nconst checkUserPermissions = async ({\n validateUserAdmin,\n vtex,\n storefrontPermissions,\n adminUserAuthToken,\n organizationId,\n logger,\n}: any) => {\n const { sessionData } = vtex\n\n let checkUserPermission = null\n\n if (sessionData?.namespaces) {\n checkUserPermission = await getCheckUserPermission({\n logger,\n storefrontPermissions,\n })\n }\n\n const condition = validateUserAdmin\n ? !adminUserAuthToken && !isSalesAdmin(checkUserPermission)\n : !adminUserAuthToken\n\n if (condition) {\n if (!sessionData?.namespaces['storefront-permissions']) {\n throw new GraphQLError('organization-data-not-found')\n }\n\n const {\n organization: { value: userOrganizationId },\n } = sessionData?.namespaces['storefront-permissions'] ?? {\n organization: {\n value: null,\n },\n }\n\n if (!organizationId) {\n // get user's organization from session\n organizationId = userOrganizationId\n }\n\n if (organizationId !== userOrganizationId) {\n throw new GraphQLError('operation-not-permitted')\n }\n }\n\n return { organizationId }\n}\n\nconst sleep = (ms: number) => {\n const time = ms + SLEEP_ADD_PERCENTAGE * ms\n\n return new Promise((resolve) => setTimeout(resolve, time))\n}\n\nconst Users = {\n getAppSettings: async (_: void, __: void, ctx: Context) => {\n const {\n clients: { masterdata, vbase },\n vtex: { logger },\n } = ctx\n\n const app: string = getAppId()\n const settings: any = await vbase.getJSON('b2borg', app).catch((error) => {\n logger.error({\n error,\n message: 'b2borg.getAppSettings-Error',\n })\n\n return {}\n })\n\n if (!settings.adminSetup) {\n settings.adminSetup = {}\n }\n\n const currHash = toHash(schemas)\n\n if (\n !settings.adminSetup?.schemaHash ||\n settings.adminSetup?.schemaHash !== currHash\n ) {\n const updates: any = []\n\n schemas.forEach((schema) => {\n updates.push(\n masterdata\n .createOrUpdateSchema({\n dataEntity: schema.name,\n schemaBody: schema.body,\n schemaName: schema.version,\n })\n .then(() => true)\n .catch((e: any) => {\n if (e.response.status !== 304) {\n throw e\n }\n\n return true\n })\n )\n })\n\n await Promise.all(updates)\n .then(() => {\n settings.adminSetup.schemaHash = currHash\n })\n .catch((e) => {\n if (e.response.status !== 304) {\n throw new Error(e)\n }\n })\n\n await vbase.saveJSON('b2borg', app, settings)\n }\n\n return settings\n },\n\n getOrganizationsWithoutSalesManager: async (\n _: void,\n __: void,\n ctx: Context\n ) => {\n const {\n clients: { storefrontPermissions, session, masterdata },\n vtex: { adminUserAuthToken, logger, sessionToken },\n } = ctx\n\n const sessionData = await session\n .getSession(sessionToken as string, ['*'])\n .then((currentSession: any) => {\n return currentSession.sessionData\n })\n .catch((error: any) => {\n logger.warn({\n error,\n message: 'getOrganizationsWithoutSalesManager-session-error',\n })\n\n return null\n })\n\n let checkUserPermission = null\n\n if (sessionData?.namespaces) {\n checkUserPermission = await getCheckUserPermission({\n logger,\n storefrontPermissions,\n })\n }\n\n if (!adminUserAuthToken && !isSalesAdmin(checkUserPermission)) {\n throw new GraphQLError('operation-not-permitted')\n }\n\n // getting all users\n const users = await storefrontPermissions\n .listAllUsers()\n .then((result: any) => {\n return result.data.listAllUsers\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'getOrganizationsWithoutSalesManager-getUsers-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n })\n\n let token: string | undefined\n let hasMore = true\n const organizations = [] as any[]\n\n const scrollMasterData = async () => {\n await sleep(SCROLL_AWAIT_TIME)\n const {\n mdToken,\n data,\n }: {\n mdToken: string\n data: any\n } = await masterdata.scrollDocuments({\n dataEntity: ORGANIZATION_DATA_ENTITY,\n fields: ORGANIZATION_FIELDS,\n mdToken: token,\n schema: ORGANIZATION_SCHEMA_VERSION,\n size: SCROLL_SIZE,\n })\n\n if (!data.length && token) {\n hasMore = false\n }\n\n if (!token && mdToken) {\n token = mdToken\n }\n\n organizations.push(...data)\n if (hasMore) {\n await scrollMasterData()\n }\n }\n\n try {\n await scrollMasterData()\n } catch (error) {\n logger.error({\n error,\n message: 'scrollMasterData-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n }\n\n return organizations.filter((organization) => {\n return !users\n .filter((user: any) => user.role === 'sales-manager')\n .find((user: any) => user.orgId === organization.id)\n })\n },\n\n getUsers: async (\n _: void,\n {\n organizationId,\n costCenterId,\n }: { organizationId: string; costCenterId: string },\n ctx: Context\n ) => {\n const {\n clients: { storefrontPermissions },\n vtex: { adminUserAuthToken, logger },\n vtex,\n } = ctx\n\n if (!adminUserAuthToken) {\n const { organizationId: orgId } = await checkUserPermissions({\n adminUserAuthToken,\n logger,\n organizationId,\n storefrontPermissions,\n validateUserAdmin: false,\n vtex,\n })\n\n organizationId = orgId\n }\n\n const variables = {\n ...(organizationId && { organizationId }),\n ...(costCenterId && { costCenterId }),\n }\n\n return storefrontPermissions\n .listUsers(variables)\n .then((result: any) => {\n return result.data.listUsers\n })\n .catch((error) => {\n logger.error({\n error,\n message: 'getUsers-getUsers-error',\n })\n\n throw new GraphQLError(getErrorMessage(error))\n })\n },\n\n getUsersPaginated: async (\n _: void,\n {\n organizationId,\n costCenterId,\n search = '',\n page = 1,\n pageSize = 25,\n sortOrder = 'asc',\n sortedBy = 'email',\n }: {\n organizationId: string\n costCenterId: string\n search: string\n page: number\n pageSize: number\n sortOrder: string\n sortedBy: string\n },\n ctx: Context\n ) => {\n const {\n clients: { storefrontPermissions },\n vtex: { adminUserAuthToken, logger },\n vtex,\n } = ctx\n\n if (!adminUserAuthToken) {\n const { organizationId: orgId } = await checkUserPermissions({\n adminUserAuthToken,\n logger,\n organizationId,\n storefrontPermissions,\n validateUserAdmin: true,\n vtex,\n })\n\n organizationId = orgId\n }\n\n const variables = {\n ...(organizationId && { organizationId }),\n ...(costCenterId && { costCenterId }),\n page,\n pageSize,\n search,\n sortOrder,\n sortedBy,\n }\n\n return storefrontPermissions\n .listUsersPaginated(variables)\n .then((result: any) => {\n return result.data.listUsersPaginated\n })\n .catch((error) => {\n logger.error({\n error,\n message: 'getUsers-error',\n })\n throw new GraphQLError(getErrorMessage(error))\n })\n },\n\n getSalesChannels: async (_: void, __: void, ctx: Context) => {\n return getChannels(ctx)\n },\n\n getBinding: async (_: void, { email }: { email: string }, ctx: Context) => {\n const {\n clients: { catalog },\n vtex: { logger },\n } = ctx\n\n let access = false\n let availableSalesChannels: any = {}\n\n try {\n availableSalesChannels = await catalog\n .salesChannelAvailable(email)\n .then((res: any) => {\n return res.map((item: any) => {\n return item.Id.toString()\n })\n })\n } catch {\n logger.info({\n message: 'getBinding-availableSalesChannels',\n data: { email },\n })\n }\n\n try {\n const selectedChannels: any = await getChannels(ctx).then((res: any) => {\n if (res.length) {\n return res.map((item: any) => {\n return item.id\n })\n }\n\n return null\n })\n\n if (selectedChannels) {\n if (availableSalesChannels.length) {\n access =\n selectedChannels.filter((item: any) =>\n availableSalesChannels.includes(item)\n ).length > 0\n }\n } else {\n access = true\n }\n } catch (err) {\n logger.warn({\n error: err,\n message: 'getBinding-Error',\n })\n }\n\n return access\n },\n}\n\nexport default Users\n\n```"
}
] |
code_b2b-organizations-graphql_695a655c
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Queries/MarketingTags.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { MARKETING_TAGS } from '../../utils/constants'\n\nconst MarketingTags = {\n getMarketingTags: async (\n _: void,\n { costId }: { costId: string },\n ctx: Context\n ) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n try {\n return await vbase.getJSON(MARKETING_TAGS.VBASE_BUCKET, costId)\n } catch (error) {\n const { data } = error.response as any\n\n if (data.code !== 'FileNotFound') {\n logger.error({\n error,\n message: 'getMarketingTags.error',\n })\n }\n\n return { status: 'error', message: error }\n }\n },\n}\n\nexport default MarketingTags\n\n```"
}
] |
code_b2b-organizations-graphql_a896f4c1
|
[
{
"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 b2b-organizations-graphql/node/resolvers/Routes/index.ts from the b2b-organizations-graphql VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ForbiddenError, UserInputError } from '@vtex/api'\n\nimport {\n COST_CENTER_DATA_ENTITY,\n ORGANIZATION_DATA_ENTITY,\n} from '../../mdSchema'\n\nconst getUserAndPermissions = async (ctx: Context) => {\n const {\n vtex: { storeUserAuthToken, sessionToken, logger },\n clients: { vtexId, session, storefrontPermissions },\n } = ctx\n\n const token: any = storeUserAuthToken\n\n const sessionData = await session\n .getSession(sessionToken as string, ['*'])\n .then((currentSession: any) => {\n return currentSession.sessionData\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'orders-getSession-error',\n })\n\n return null\n })\n\n const profileEmail = sessionData?.namespaces?.profile?.email?.value\n const impersonatedEmail =\n sessionData?.namespaces?.impersonate?.storeUserEmail?.value\n\n if (!impersonatedEmail && !token) {\n throw new ForbiddenError('Access denied')\n }\n\n let checkUserPermission = null\n\n if (sessionData?.namespaces) {\n const checkUserPermissionResult = await storefrontPermissions\n // It is necessary to send the app name, because the check user return the permissions relative to orders-history to access the page.\n .checkUserPermission('vtex.b2b-orders-history@2.x')\n .catch((error: any) => {\n logger.error({\n message: 'checkUserPermission-error',\n error,\n })\n\n return {\n data: {\n checkUserPermission: null,\n },\n }\n })\n\n checkUserPermission = checkUserPermissionResult?.data?.checkUserPermission\n }\n\n const organizationId =\n sessionData?.namespaces['storefront-permissions']?.organization?.value\n\n const costCenterId =\n sessionData?.namespaces['storefront-permissions']?.costcenter?.value\n\n const authUser = impersonatedEmail\n ? { user: impersonatedEmail }\n : await vtexId.getAuthenticatedUser(token)\n\n return {\n authEmail: authUser?.user,\n impersonatedEmail,\n profileEmail,\n permissions: checkUserPermission?.permissions,\n organizationId,\n costCenterId,\n }\n}\n\nconst checkPermissionAgainstOrder = ({\n permissions,\n authEmail,\n profileEmail,\n organizationId,\n costCenterId,\n orderData,\n}: {\n permissions?: string[]\n authEmail?: string\n profileEmail: string\n organizationId?: string\n costCenterId?: string\n orderData: any\n}) => {\n if (\n authEmail === orderData?.clientProfileData?.email ||\n profileEmail === orderData?.clientProfileData?.email\n ) {\n return true\n }\n\n if (permissions?.includes('all-orders')) {\n return true\n }\n\n if (\n permissions?.includes('organization-orders') &&\n organizationId === orderData?.marketingData?.utmCampaign\n ) {\n return true\n }\n\n if (\n permissions?.includes('costcenter-orders') &&\n costCenterId === orderData?.marketingData?.utmMedium\n ) {\n return true\n }\n\n return false\n}\n\nconst getOrder = async (ctx: Context) => {\n const {\n vtex: {\n route: {\n params: { orderId },\n },\n },\n clients: { orders },\n } = ctx\n\n if (!orderId) {\n throw new UserInputError('Order ID is required')\n }\n\n const order: any = await orders.order(String(orderId))\n\n // Some dependencies rely on this property not being null but an empty array instead.\n // The new orders endpoint might return null for this property instead of an empty array,\n // so we make sure to set it to an empty array to avoid breaking dependencies.\n // For more info: https://vtex-dev.atlassian.net/browse/B2BTEAM-1376\n order.marketplaceItems = order.marketplaceItems ?? []\n\n return order\n}\n\nconst Index = {\n checkout: async (ctx: Context) => {\n const {\n vtex: { storeUserAuthToken, sessionToken, logger },\n clients: { session, masterdata },\n } = ctx\n\n const token: any = storeUserAuthToken\n const response: any = {}\n\n ctx.response.status = !token ? 403 : 200\n\n if (token) {\n const sd = await session\n .getSession(sessionToken as string, ['*'])\n .then((currentSession: any) => {\n return currentSession.sessionData\n })\n .catch((error: any) => {\n logger.error({\n error,\n message: 'checkout-getSession-error',\n })\n\n return null\n })\n\n if (sd?.namespaces['storefront-permissions']) {\n if (sd.namespaces['storefront-permissions']?.organization?.value) {\n response.organization = await masterdata.getDocument({\n dataEntity: ORGANIZATION_DATA_ENTITY,\n fields: ['paymentTerms'],\n id: sd.namespaces['storefront-permissions']?.organization?.value,\n })\n }\n\n if (sd.namespaces['storefront-permissions']?.costcenter?.value) {\n response.costcenter = await masterdata.getDocument({\n dataEntity: COST_CENTER_DATA_ENTITY,\n fields: ['addresses'],\n id: sd.namespaces['storefront-permissions']?.costcenter?.value,\n })\n }\n }\n }\n\n ctx.set('Content-Type', 'application/json')\n ctx.set('Cache-Control', 'no-cache, no-store')\n\n ctx.response.body = response\n },\n order: async (ctx: Context) => {\n const order = await getOrder(ctx)\n\n const {\n permissions,\n authEmail,\n impersonatedEmail,\n profileEmail,\n organizationId,\n costCenterId,\n } = await getUserAndPermissions(ctx)\n\n const permitted = checkPermissionAgainstOrder({\n permissions,\n orderData: order,\n authEmail: impersonatedEmail ?? authEmail,\n profileEmail,\n organizationId,\n costCenterId,\n })\n\n if (!permitted) {\n throw new ForbiddenError('Access denied')\n }\n\n ctx.set('Content-Type', 'application/json')\n ctx.set('Cache-Control', 'no-cache, no-store')\n\n ctx.response.body = order\n\n ctx.response.status = 200\n },\n orders: async (ctx: Context) => {\n const {\n clients: { oms },\n request: { querystring },\n } = ctx\n\n const {\n permissions,\n authEmail,\n impersonatedEmail,\n organizationId,\n costCenterId,\n } = await getUserAndPermissions(ctx)\n\n const filterByPermission = (userPermissions: string[]) => {\n if (userPermissions.includes('all-orders')) {\n return ``\n }\n\n if (userPermissions.includes('organization-orders')) {\n return `&f_UtmCampaign=${organizationId}`\n }\n\n if (userPermissions.includes('costcenter-orders')) {\n return `&f_UtmMedium=${costCenterId}`\n }\n\n return `&clientEmail=${impersonatedEmail ?? authEmail}`\n }\n\n const pastYear: any = new Date()\n\n pastYear.setDate(pastYear.getDate() - 365)\n\n const now = new Date().toISOString()\n let query = `f_creationDate=creationDate:[${pastYear.toISOString()} TO ${now}]&${querystring}`\n\n if (permissions?.length) {\n query += filterByPermission(permissions)\n } else {\n query += `&clientEmail=${impersonatedEmail ?? authEmail}`\n }\n\n const orders: any = await oms.search(query)\n\n ctx.set('Content-Type', 'application/json')\n ctx.set('Cache-Control', 'no-cache, no-store')\n\n ctx.response.body = orders\n\n ctx.response.status = 200\n },\n requestCancellation: async (ctx: Context) => {\n const {\n vtex: {\n route: {\n params: { orderId },\n },\n },\n clients: { checkout },\n } = ctx\n\n const order = await getOrder(ctx)\n\n const {\n permissions,\n authEmail,\n impersonatedEmail,\n profileEmail,\n organizationId,\n costCenterId,\n } = await getUserAndPermissions(ctx)\n\n const permitted = checkPermissionAgainstOrder({\n permissions,\n orderData: order,\n authEmail: impersonatedEmail ?? authEmail,\n profileEmail,\n organizationId,\n costCenterId,\n })\n\n if (!permitted) {\n throw new ForbiddenError('Access denied')\n }\n\n const reason = `order canceled by user: ${authEmail}`\n\n const requestCancellationResponse = await checkout.requestCancellation(\n orderId as string,\n reason\n )\n\n ctx.set('Content-Type', 'application/json')\n ctx.set('Cache-Control', 'no-cache, no-store')\n\n ctx.response.body = requestCancellationResponse.data\n\n ctx.response.status = requestCancellationResponse.status\n },\n}\n\nexport default Index\n\n```"
}
] |
code_btg360_92636f56
|
[
{
"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 btg360/docs/README.md from the btg360 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# BTG360\n\nBTG 360 uses behavioral targert technology so you can achieve even more assertive results\nwith email marketing campaigns based on browsing and / or purchasing behavior of each\none of the registered users in your lists.\n\nFor more information please visit, [AllIn](https://allinmail.com.br/) website.\n\n## How to install\n\nOpen the VTEX App Store and install this app on your store.\n\nNow, open the app settings on your admin and fill in the BTG360 options.\n\nor\n\nRun the following command:\n\n```sh\nvtex install vtex.btg360@0.x\n```\n```"
}
] |
code_btg360_01fdd366
|
[
{
"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 btg360/react/index.tsx from the btg360 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { PixelMessage } from './typings/events'\nimport { canUseDOM } from 'vtex.render-runtime'\nimport { fetchEmail, clientEvent } from './helpers'\n\nconst eventQueue: PixelMessage[] = []\n\nfunction processMessageQueue() {\n for (const e of eventQueue) {\n handleMessage(e)\n }\n}\n\nfunction handleOrEnqueueMessage (e: PixelMessage) {\n if (window.__BTG_SCRIPTS_READY__) {\n handleMessage(e)\n } else {\n eventQueue.push(e)\n }\n}\n\nasync function handleMessage(e: PixelMessage) {\n const {\n Btg360,\n __btg360: { BTGId: account, BTGDomain: domain },\n location: { pathname },\n } = window\n\n switch (e.data.eventName) {\n case 'vtex:pageInfo': {\n clientEvent(account, domain, Btg360)\n if (e.data.eventType === 'internalSiteSearchView') {\n const items = pathname\n .split('?')[0]\n .split('/')\n .filter(item => item.toLocaleLowerCase())\n .map(keyword => ({ keyword }))\n const event = 'search'\n const BTG360SearchEvent: Btg360Event = {\n account,\n domain,\n event,\n items,\n }\n Btg360.add(BTG360SearchEvent)\n }\n break\n }\n case 'vtex:orderPlaced': {\n const email = await fetchEmail()\n const { transactionId, transactionProducts: items } = e.data\n const BTG360TransactionEvent: Btg360Event = {\n account,\n domain,\n event: 'transaction',\n items: items.map(\n ({\n id,\n name,\n price,\n categoryTree: [department = '', category = '', subcategory = ''],\n brand,\n }): Btg360EventItemTransaction => ({\n email,\n transactionId,\n id,\n name,\n price: price.toFixed(2),\n department,\n category,\n subcategory,\n brand,\n })\n ),\n }\n\n Btg360.add(BTG360TransactionEvent)\n clientEvent(account, domain, Btg360)\n break\n }\n case 'vtex:productView': {\n const {\n product: {\n productId,\n productName: name,\n categories,\n brand,\n items: [\n {\n sellers: [\n {\n commertialOffer: { Price: price },\n },\n ],\n },\n ],\n },\n } = e.data\n const email = await fetchEmail()\n const [categoryTree] = categories\n const [\n department = '',\n category = '',\n subcategory = '',\n ] = categoryTree.split('/').filter(item => item)\n const BTG360ProductEventItem: Btg360EventItemProduct = {\n id: productId,\n name,\n email,\n price: price.toFixed(2),\n department,\n category,\n subcategory,\n brand,\n }\n const BTG360ProductEvent: Btg360Event = {\n account,\n domain,\n event: 'product',\n items: [BTG360ProductEventItem],\n }\n\n Btg360.add(BTG360ProductEvent)\n break\n }\n case 'vtex:addToCart': {\n const { items } = e.data\n const email = await fetchEmail()\n const BTG360CartEvent = {\n account,\n domain,\n event: 'cart',\n items: items.map(\n ({ name, price, skuId: id, brand, category: categoryTree }) => {\n const [\n department = '',\n category = '',\n subcategory = '',\n ] = categoryTree.split('/')\n return {\n email,\n id,\n name: name.toUpperCase(),\n price: price.toFixed(2),\n department,\n category,\n subcategory,\n brand,\n }\n }\n ),\n }\n\n Btg360.add(BTG360CartEvent)\n break\n }\n }\n}\n\nif (canUseDOM) {\n window.addEventListener('message', handleOrEnqueueMessage)\n window.addEventListener('btgReady', processMessageQueue)\n}\n\n```"
}
] |
code_btg360_c973c114
|
[
{
"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 btg360/react/package.json from the btg360 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.btg360\",\n \"version\": \"1.1.0\",\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json './**/*.ts'\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^10.12.18\",\n \"tslint\": \"^5.11.0\",\n \"tslint-config-vtex\": \"^2.0.0\",\n \"tslint-eslint-rules\": \"^5.4.0\",\n \"typescript\": \"3.7.3\"\n }\n}\n\n```"
}
] |
code_btg360_0b619310
|
[
{
"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 btg360/react/tslint.json from the btg360 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"compilerOptions\": {\n \"alwaysStrict\": true,\n \"esModuleInterop\": true,\n \"jsx\": \"react\",\n \"lib\": [\"es2017\", \"dom\", \"es2018.promise\"],\n \"module\": \"es6\",\n \"moduleResolution\": \"node\",\n \"noImplicitAny\": true,\n \"noImplicitReturns\": true,\n \"noImplicitThis\": true,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"skipLibCheck\": true,\n \"sourceMap\": true,\n \"strictFunctionTypes\": true,\n \"strictNullChecks\": true,\n \"strictPropertyInitialization\": true,\n \"target\": \"es2017\",\n \"typeRoots\": [\"node_modules/@types\"],\n \"types\": [\"node\", \"jest\", \"graphql\"]\n },\n \"exclude\": [\"node_modules\"],\n \"include\": [\"./typings/*.d.ts\", \"./**/*.tsx\", \"./**/*.ts\"],\n \"typeAcquisition\": {\n \"enable\": false\n }\n}\n\n```"
}
] |
code_btg360_236a5d25
|
[
{
"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 btg360/store/interfaces.json from the btg360 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"pixel.btg360\": {\n \"component\": \"index\"\n }\n}\n\n```"
}
] |
code_btg360_16dc5540
|
[
{
"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 btg360/react/typings/events.d.ts from the btg360 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface PixelMessage extends MessageEvent {\n data:\n | ProductViewData\n | ProductClickData\n | OrderPlacedData\n | PageViewData\n | PageInfoData\n | ProductImpressionData\n | AddToCartData\n | RemoveToCartData\n | CategoryViewData\n | DepartmentViewData;\n}\n\nexport interface EventData {\n event: string;\n eventName: string;\n currency: string;\n}\n\nexport interface PageViewData extends EventData {\n event: \"pageView\";\n eventName: \"vtex:pageView\";\n pageTitle: string;\n pageUrl: string;\n referrer: string;\n}\n\nexport interface PageInfoData extends EventData {\n event: \"pageInfo\";\n eventName: \"vtex:pageInfo\";\n eventType: string;\n accountName: string;\n pageCategory: string;\n pageDepartment: string;\n pageFacets: string[];\n pageTitle: string;\n pageUrl: string;\n}\n\nexport interface CategoryViewData extends EventData {\n event: \"categoryView\";\n eventName: \"vtex:categoryView\";\n products: Product[];\n}\n\nexport interface DepartmentViewData extends EventData {\n event: \"departmentView\";\n eventName: \"vtex:departmentView\";\n products: Product[];\n}\n\nexport interface AddToCartData extends EventData {\n event: \"addToCart\";\n eventName: \"vtex:addToCart\";\n items: AddToCartProduct[];\n}\n\nexport interface RemoveToCartData extends EventData {\n event: \"removeFromCart\";\n eventName: \"vtex:removeFromCart\";\n items: any[];\n}\n\nexport interface OrderPlacedData extends Order, EventData {\n event: \"orderPlaced\";\n eventName: \"vtex:orderPlaced\";\n}\n\nexport interface ProductViewData extends EventData {\n event: \"productView\";\n eventName: \"vtex:productView\";\n product: Product;\n}\n\nexport interface ProductClickData extends EventData {\n event: \"productClick\";\n eventName: \"vtex:productClick\";\n product: Product;\n}\n\nexport interface ProductImpressionData extends EventData {\n event: \"productImpression\";\n eventName: \"vtex:productImpression\";\n product: Product;\n position: number;\n list: string;\n}\n\nexport interface Order {\n currency: string;\n accountName: string;\n orderGroup: string;\n salesChannel: string;\n coupon: string;\n visitorType: string;\n visitorContactInfo: string[];\n transactionId: string;\n transactionDate: string;\n transactionAffiliation: string;\n transactionTotal: number;\n transactionShipping: number;\n transactionTax: number;\n transactionCurrency: string;\n transactionPaymentType: PaymentType[];\n transactionShippingMethod: ShippingMethod[];\n transactionProducts: ProductOrder[];\n transactionPayment: {\n id: string;\n };\n}\n\ninterface PaymentType {\n group: string;\n paymentSystemName: string;\n installments: number;\n value: number;\n}\n\ninterface ShippingMethod {\n itemId: string;\n selectedSla: string;\n}\n\ninterface ProductOrder {\n id: string;\n name: string;\n sku: string;\n skuRefId: string;\n skuName: string;\n brand: string;\n brandId: string;\n seller: string;\n sellerId: string;\n category: string;\n categoryId: string;\n categoryTree: string[];\n categoryIdTree: string[];\n originalPrice: number;\n price: number;\n sellingPrice: number;\n tax: number;\n quantity: number;\n components: any[];\n measurementUnit: string;\n unitMultiplier: number;\n}\n\nexport interface Product {\n brand: string;\n categoryId?: string; // inconsistency\n categories: string[];\n productId: string;\n productName: string;\n selectedSku: {\n itemId: string\n }; // inconsistency\n items: Item[];\n sku: Item;\n [key: string]: any;\n}\n\ninterface Item {\n itemId: string;\n name: string;\n seller?: Seller;\n [key: string]: any;\n}\n\ninterface Seller {\n commertialOffer: CommertialOffer;\n AvailableQuantity: number;\n [key: string]: any;\n}\n\ninterface CommertialOffer {\n Price: number;\n [key: string]: any;\n}\n\ninterface AddToCartProduct {\n brand: string;\n name: string;\n price: number;\n quantity: number;\n skuId: string;\n variant: string;\n category: string;\n}\n\n```"
}
] |
code_btg360_fc95d102
|
[
{
"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 btg360/react/typings/vtex.render-runtime.d.ts from the btg360 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime' {\n export const canUseDOM: boolean\n}\n\n```"
}
] |
code_btg360_2a65b3e8
|
[
{
"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 btg360/react/typings/global.d.ts from the btg360 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Window extends Window {\n __btg360: BTG360Configs\n Btg360: Btg360\n __BTG_SCRIPTS_READY__?: boolean\n}\n\ninterface ProfileData {\n UserId: string\n IsReturningUser: boolean\n IsUserDefined: boolean\n IsPJ: boolean\n FirstName: string\n LastName: string\n Gender: null\n Email: string\n}\n\ninterface BTG360Configs {\n BTGId: string\n BTGDomain: string\n}\n\ninterface Btg360 {\n add(e: Btg360Event): void\n debug(): void\n}\n\ninterface Btg360Event {\n account: string\n domain: string\n event: string\n items: (\n | Btg360EventItemTransaction\n | Btg360EventItemProduct\n | Btg360EventItemKeyword)[]\n | Array<>\n}\n\ninterface BTG360EventItemClient {\n email: string\n}\n\ninterface Btg360EventItemTransaction {\n email: string\n transactionId: string\n id: string\n name: string\n price: string\n department: string\n category: string\n subcategory: string\n brand: string\n}\n\ninterface Btg360EventItemProduct {\n email: string\n id: string\n name: string\n price: string\n department: string\n category: string\n subcategory: string\n brand: string\n}\n\ninterface Btg360EventItemKeyword {\n keyword: string\n}\n\n```"
}
] |
code_btg360_4129ba55
|
[
{
"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 btg360/react/helpers/index.tsx from the btg360 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nexport async function fetchEmail(): Promise<string> {\n const { Email: email } = await (await fetch(\n '/no-cache/profileSystem/getProfile'\n )).json()\n\n if(email == undefined) {\n return ''\n }\n\n return email\n}\n\nexport async function clientEvent(account: string, domain: string, Btg360: any) {\n const email = await fetchEmail()\n const BTG360ClientEvent: Btg360Event = {\n account,\n domain,\n event: 'client',\n items: [{email}]\n }\n\n Btg360.add(BTG360ClientEvent)\n}\n\n```"
}
] |
code_ideacrm_632f14ff
|
[
{
"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 ideacrm/docs/README.md from the ideacrm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Idea CRM\n\n📢 Use this project, [contribute](https://github.com/vtex-apps/ideacrm) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\nIdea CRM is a first party integration app for the platform's customer relationship management solution. It enables you to control customer interactions, providing measurements and trackability through Chat, Phone, Email, SMS, Tickets, Social Network and other applications.\nFor more on the Idea CRM solution, please visit their [website](https://www.gvp.com.br/crm)\n\n## Configuration\n\n1. Open the **VTEX App Store** and install the Idea CRM app on your store. You can also run the following command in your terminal:\n\n```sh\nvtex install vtex.ideacrm@0.x\n```\n\n2. In the admin's side bar, access **Apps** within the **Account settings** section.\n3. Select the **Idea CRM** box and fill out the necessary fields in order to complete the app's configuration.\n```"
}
] |
code_speedy-gtm_1b2eda2a
|
[
{
"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 speedy-gtm/docs/README.md from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/google-tag-manager) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Google Tag Manager\n\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\nThe VTEX Google Tag Manager (GTM) app is a first party integration to the [Google Tag Manager solution](https://tagmanager.google.com).\n\n\n\n## Installing the Google Tag Manager app\n\n1. Access the **Apps** section in your account's admin page and look for the Google Tag Manager box;\n2. Then, click on the **Install** button;\n3. You'll see a warning message about needing to enter the necessary configurations. Scroll down and type in your **GTM ID** in the `Google Tag Manager` field.\n4. Click on **Save**.\n\n> Access the [Google Tag Manager page](https://tagmanager.google.com/) and log in to your account in order to find out what is your account **GTM ID**. Use the number provided by the `Container ID` column.\n\n### Step 2 - Creating Google Analytics variables\nTo set up Google Tag Manager in your store, you must create and set up all necessary variables, triggers, and tags. Follow the [Setting up Google Tag Manager documentation](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-setting-up-google-tag-manager) to create them.\n\n### Step 3 - Persisting campaign data throughout a user session\nTo prevent GTM from creating additional session identifiers every time a user navigates the website, you must add the variables `originalLocation` and `originalReferrer` to your GTM container and configure your store’s Google Analytics tags. Notice that this is important to persist campaign data throughout a user session and avoid providing inconsistent campaign data to Google Analytics (GA). \n\n>⚠️ The `originalLocation` and `originalReferrer` variables are available for VTEX IO Google Tag Manager versions `2.x` and `3.x`. \n\n#### Creating the variables Original Location and Original Referrer\n\n1. Log in to your [GTM account](https://tagmanager.google.com) and click on the GTM container you want to work with.\n\n \n\n2. On the container page, click on **Variables**.\n3. In the **Built-In Variables** section, check if the `Page URL` and `Page Path` variables are enabled. Otherwise, click on `Configure` and select `Page URL` and `Page Path` to enable them.\n4. Go to the **User-Defined Variables** section and click on `New`. A side popup will open.\n5. Replace the `Untitled Variable` value with `Original Location`.\n6. Click on **Variable Configuration**.\n7. On **Page Variables**, click on **Data Layer Variable**.\n8. In the `Data Layer Variable Name` field, type `originalLocation`.\n9. Enable the `Set Default Value` option and fill in the `Default Value` field with the following value:\n \n ```\n {{Page URL}}\n ```\n \n \n\n10. Click `Save`. Once you have saved the `originalLocation` variable, create the `originalReferrer` as described in the steps below.\n11. In the **User-Defined Variables** section, click on `New`. A side popup will open.\n12. Replace the `Untitled Variable` value with `Original Referrer`.\n13. Click on **Variable Configuration**.\n14. On **Page Variables**, click on **Data Layer Variable**.\n15. In the `Data Layer Variable Name` field, type `originalReferrer`.\n16. Enable the `Set Default Value` option and fill in the `Default Value` field with the following value:\n \n ```\n {{Referrer}}\n ```\n \n \n\n17. Click `Save`.\n\n#### Updating Google Analytics Settings variables and tags\n\nNow, let's configure every Google Analytics Settings variable that fires the `originalLocation` and `originalReferrer` variables.\n\n1. Go to the **Variables** section; \n2. On **User-Defined Variables**, click on the name of one of the Google Analytics Settings variables\n\n \n\n3. Click on the **Variable Configuration** box;\n4. Go to **More Settings > Fields to Set**;\n5. Click on `Add Field`;\n6. Set the `Field Name` field as `location` and `Value` as `{{Original Location}}`;\n7. Then, click on `Add Field` again;\n6. Set the `Field Name` field as `referrer` and `Value` as `{{Original Referrer}}`;\n8. Click on `Save`.\n\nIf you have any Google Analytics tags using the Google Analytics Settings variables you have changed, apply the same changes above directly on the tags that need it.\n\n#### Publishing your changes\n\nOnce you have set up the Google Analytics variables and tags, follow Google's official guide on [how to submit and publish your store’s container](https://support.google.com/tagmanager/answer/6107163).\n\n## Restrictions\n\nIn order to avoid performance problems and unforeseen behavior, our VTEX IO Google Tag Manager solution uses the native GTM **blacklist** feature. You can read more about this feature on the [Google Developer Guide](https://developers.google.com/tag-manager/web/restrict).\n\nWe, by default, blacklist the `html` ID, which automatically blocklists all the tags, variables, and triggers of the type `customScripts`. The main consequence of this blocklist is that **Custom HTML tags will not be triggered**.\n\n>⚠️ The HTML blacklist is the VTEX Google Tag Manager app's default. If you want to disable this restriction, go to `https://{accountName}.myvtex.com/admin/apps/vtex.google-tag-manager@2.x/setup` and check the toggle below.\n\n<img src=\"https://user-images.githubusercontent.com/11340665/103930428-7c762e80-50fd-11eb-9cab-bc9e542b4dbf.png\"/>\n\nMost of the widely used Custom HTML tags are integrations with third-party services, like Customer Chat, Analytics, Remarketing, and Pixel tags. If your store needs a Custom HTML for one of those cases, the integration can either be done by transforming the tags into a [VTEX IO Pixel App](https://developers.vtex.com/docs/guides/pixel-apps) or by removing this restriction.\n\nCheck below the full list of tags and variables that are blocked, by default, in the VTEX IO Google Tag Manager solution.\n\n### Blocked tags\n\n- Custom HTML Tag - `html`\n- Eulerian Analytics Tag - `ela`\n- SaleCycle JavaScript Tag - `scjs`\n- Upsellit Global Footer Tag - `uslt`\n- Upsellit Confirmation Tag - `uspt`\n\n### Blocked variables\n\n- Custom JavaScript Variable - `jsm`\n\nCheck out a list with all the GTM available tags on the [Google Developer Guide](https://developers.google.com/tag-manager/devguide).\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\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 are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```"
}
] |
code_speedy-gtm_ad118658
|
[
{
"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 speedy-gtm/react/index.tsx from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { canUseDOM } from 'vtex.render-runtime'\n\nimport { sendEnhancedEcommerceEvents } from './modules/enhancedEcommerceEvents'\nimport { sendExtraEvents } from './modules/extraEvents'\nimport { sendLegacyEvents } from './modules/legacyEvents'\nimport { PixelMessage } from './typings/events'\n\n// no-op for extension point\nexport default function() {\n return null\n}\n\nexport function handleEvents(e: PixelMessage) {\n sendEnhancedEcommerceEvents(e)\n sendExtraEvents(e)\n sendLegacyEvents(e)\n}\n\nif (canUseDOM) {\n window.addEventListener('message', handleEvents)\n}\n\n```"
}
] |
code_speedy-gtm_d8409754
|
[
{
"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 speedy-gtm/react/package.json from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"version\": \"3.5.4\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"author\": \"VTEX\",\n \"license\": \"ISC\",\n \"devDependencies\": {\n \"@types/node\": \"^12.0.0\",\n \"@vtex/test-tools\": \"^3.3.2\"\n }\n}\n\n```"
}
] |
code_speedy-gtm_7758ff75
|
[
{
"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 speedy-gtm/public/metadata/messages/es-AR.json from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Google Tag Manager\",\n \"headline\": \"Integre su tienda con la plataforma de tracking de conversiones y navegación de Google.\",\n \"overview\": \"Google Tag Manager es un servicio para rastrear las actividades de sus visitantes en ecommerce y puede ser usado para evaluar la efectividad de sus anuncios, generar audiencias de remarketing y mapear información sobre cómo su tienda está sendo utilizada. \\\\n\\\\n Esta aplicación implementa la tag de Google Tag Manager en el código de cada página de su sitio, lo que le permite realizar un tracking de los eventos de conversión y navegación dentro de las mejores prácticas de análisis de Google. Usted deberá ingresar su ID de cuenta GTM en la página de configuración de la aplicación.\",\n \"features\": [\n \"Configura Google Tag Manager con el admin de VTEX\",\n \"Envia todo los eventos de Google Enhanced Ecommerce\"\n ],\n \"additionalInformation\": \"La gestión de tags, eventos y triggers se realiza directamente utilizando la plataforma de Google Tag Manager (http://tagmanager.google.com/) después de instalar y configurar la aplicación. Los eventos disponibles por defecto con la implementación de la aplicación se pueden consultar en la documentación.\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n }\n\n```"
}
] |
code_speedy-gtm_d15a715d
|
[
{
"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 speedy-gtm/public/metadata/messages/pt-BR.json from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Google Tag Manager\",\n \"headline\": \"Integre-se à plataforma de tracking de navegação e conversão do Google.\",\n \"overview\": \"O Google Tag Manager é um serviço de rastreamento das atividades dos visitantes do seu ecommerce que pode ser utilizado para avaliar a eficiência de seus anúncios, gerar públicos de remarketing e mapear insights sobre o uso da sua loja.\\\\n\\\\n Este app implementa a tag do Google Tag Manager no código de todas as páginas do seu site, permitindo que você rastreie eventos de navegação e conversão dentro dos padrões e boas práticas de analytics do Google. Você precisará inserir o ID da sua conta do GTM na página de configuração do aplicativo.\",\n \"features\": [\n \"Configure o Google Tag Manager pelo admin da VTEX\",\n \"Envia todos os eventos do Google Enhanced Ecommerce\"\n ],\n \"additionalInformation\": \"A gestão das tags, eventos e triggers é feita diretamente pela platafoma do Google Tag Manager (http://tagmanager.google.com/) após a instalação e configuração do app. Os eventos disponíveis por padrão com a implementação do app podem ser consultados na documentação.\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n }\n\n```"
}
] |
code_speedy-gtm_c42bd2ce
|
[
{
"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 speedy-gtm/public/metadata/messages/en-US.json from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Google Tag Manager\",\n \"headline\": \"Integrate your store with Google's navigation and conversion tracking platform.\",\n \"overview\": \"Google Tag Manager is a service for tracking the activities of your ecommerce visitors and can be used to assess the effectiveness of your ads, generate remarketing audiences and map insights into how your store is being used.\\\\n\\\\n This app implements the Google Tag Manager tag in the code of every page on your site, allowing you to track navigation and conversion events within Google’s best practices and analytics standards. You will need to enter your GTM account ID on the application's setup page.\",\n \"features\": [\n \"Configure Google Tag Manager using the VTEX admin panel\",\n \"Send all Google Enhanced Commerce events\"\n ],\n \"additionalInformation\": \"The management of tags, events and triggers is done directly through the Google Tag Manager platform (http://tagmanager.google.com/) after installing and configuring the app. The events available by default with the app's implementation can be consulted in our documentation.\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n }\n\n```"
}
] |
code_speedy-gtm_27061be7
|
[
{
"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 speedy-gtm/react/typings/events.d.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface PixelMessage extends MessageEvent {\n data:\n | ProductViewData\n | ProductClickData\n | OrderPlacedData\n | OrderPlacedTrackedData\n | PageViewData\n | LegacyProductViewData\n | ProductImpressionData\n | AddToCartData\n | RemoveFromCartData\n | CartChangedData\n | HomePageInfo\n | ProductPageInfoData\n | SearchPageInfoData\n | UserData\n | CartIdData\n | CartLoadedData\n | PromoViewData\n | PromotionClickData\n | AddPaymentInfoData\n | AddShippingInfoData\n | SignUpData\n | LoginData\n | ShareData\n | BeginCheckoutData\n | ViewCartData\n | RefundData\n | AddToWishlistData\n | SearchData\n}\n\nexport interface EventData {\n event: string\n eventName: string\n currency: string\n}\n\nexport interface PageInfoData extends EventData {\n event: 'pageInfo'\n eventName: 'vtex:pageInfo'\n accountName: string\n pageTitle: string\n pageUrl: string\n}\n\nexport interface LegacyProductViewData extends EventData {\n event: 'pageInfo'\n eventName: 'vtex:pageInfo'\n eventType: 'productView'\n}\n\nexport interface UserData extends PageInfoData {\n eventType: 'userData'\n eventName: 'vtex:userData'\n firstName?: string\n lastName?: string\n document?: string\n id?: string\n email?: string\n phone?: string\n isAuthenticated: boolean\n}\n\nexport interface CartIdData extends PageInfoData {\n eventType: 'cartId'\n eventName: 'vtex:cartId'\n cartId: string\n}\n\nexport interface HomePageInfo extends PageInfoData {\n eventType: 'homeView'\n}\n\nexport interface ProductPageInfoData extends PageInfoData {\n eventType: 'productPageInfo'\n}\n\nexport interface SearchPageInfoData extends PageInfoData {\n eventType:\n | 'internalSiteSearchView'\n | 'categoryView'\n | 'departmentView'\n | 'emptySearchView'\n category?: CategoryMetaData\n department?: DepartmentMetaData\n search?: SearchMetaData\n}\n\ninterface CategoryMetaData {\n id: string\n name: string\n}\n\ninterface DepartmentMetaData {\n id: string\n name: string\n}\n\ninterface SearchMetaData {\n term: string\n category: CategoryMetaData\n results: number\n}\n\nexport interface PageViewData extends EventData {\n event: 'pageView'\n eventName: 'vtex:pageView'\n pageTitle: string\n pageUrl: string\n referrer: string\n}\n\nexport interface AddToCartData extends EventData {\n event: 'addToCart'\n eventName: 'vtex:addToCart'\n items: CartItem[]\n}\n\nexport interface RemoveFromCartData extends EventData {\n event: 'removeFromCart'\n eventName: 'vtex:removeFromCart'\n items: CartItem[]\n}\n\nexport interface CartChangedData extends EventData {\n event: 'cartChanged'\n eventName: 'vtex:cartChanged'\n items: CartItem[]\n}\n\nexport interface OrderPlacedData extends Order, EventData {\n event: 'orderPlaced'\n eventName: 'vtex:orderPlaced'\n}\n\nexport interface OrderPlacedTrackedData extends Order, EventData {\n event: 'orderPlacedTracked'\n eventName: 'vtex:orderPlacedTracked'\n}\n\nexport interface ProductViewData extends EventData {\n event: 'productView'\n eventName: 'vtex:productView'\n product: Product\n list?: string\n}\n\nexport interface ProductClickData extends EventData {\n event: 'productClick'\n eventName: 'vtex:productClick'\n product: ProductSummary\n position: number\n list?: string\n}\n\nexport interface ProductImpressionData extends EventData {\n event: 'productImpression'\n eventName: 'vtex:productImpression'\n impressions: Impression[]\n product?: ProductSummary // deprecated, use impressions list!\n position?: number // deprecated, use impressions list!\n list: string\n}\n\nexport interface CartLoadedData extends EventData {\n event: 'cartLoaded'\n eventName: 'vtex:cartLoaded'\n orderForm: OrderForm\n}\n\nexport interface PromoViewData extends EventData {\n event: 'promoView'\n eventType: 'vtex:promoView'\n eventName: 'vtex:promoView'\n promotions: Promotion[]\n}\n\nexport interface PromotionClickData extends EventData {\n event: 'promotionClick'\n eventType: 'vtex:promotionClick'\n eventName: 'vtex:promotionClick'\n promotions: Promotion[]\n}\n\nexport interface AddPaymentInfoData extends EventData {\n event: 'addPaymentInfo'\n eventType: 'vtex:addPaymentInfo'\n eventName: 'vtex:addPaymentInfo'\n payment: PaymentType\n items: CartItem[]\n}\n\nexport interface BeginCheckoutData extends EventData {\n event: 'beginCheckout'\n eventType: 'vtex:beginCheckout'\n eventName: 'vtex:beginCheckout'\n items: CartItem[]\n}\n\nexport interface AddShippingInfoData extends EventData {\n event: 'addShippingInfo'\n eventType: 'vtex:addShippingInfo'\n eventName: 'vtex:addShippingInfo'\n items: CartItem[]\n shippingTier: string\n value: number\n}\n\nexport interface ViewCartData extends EventData {\n event: 'viewCart'\n eventType: 'vtex:viewCart'\n eventName: 'vtex:viewCart'\n items: CartItem[]\n}\n\nexport interface AddToWishlistData extends EventData {\n event: 'addToWishlist'\n eventType: 'vtex:addToWishlist'\n eventName: 'vtex:addToWishlist'\n items: {\n selectedItem: SelectedItem\n product: ProductSummary\n }\n list: string\n}\n\nexport interface SelectedItem {\n attachments?: any[]\n complementName?: string\n ean?: string\n estimatedDateArrival?: any\n images?: Image[]\n itemId?: string\n kitItems?: any[]\n measurementUnit?: string\n name?: string\n nameComplete?: string\n referenceId?: any\n sellers: Seller[]\n unitMultiplier?: number\n variations?: any[]\n videos?: any[]\n}\n\nexport interface Seller {\n addToCartLink: string\n commercialOffer: any\n sellerDefault: boolean\n sellerId: string\n sellerName: string\n}\n\nexport interface Image {\n cacheId: string\n imageId: string\n imageLabel: string\n imageTag: string\n imageText: string\n imageUrl: string\n}\n\nexport interface RefundData extends EventData {\n event: 'refund'\n eventType: 'vtex:refund'\n eventName: 'vtex:refund'\n order: {\n transactionId: string\n tax: number\n shipping: number\n value: number\n items: ProductOrder[]\n }\n}\n\nexport interface SearchData extends EventData {\n event: 'search'\n eventType: 'vtex:search'\n eventName: 'vtex:search'\n term: string\n}\n\nexport interface ShareData extends EventData {\n event: 'share'\n eventType: 'vtex:share'\n eventName: 'vtex:share'\n method: string\n contentType: string\n itemId: string\n}\n\nexport interface LoginData extends EventData {\n event: 'login'\n eventType: 'vtex:login'\n eventName: 'vtex:login'\n method: string\n}\n\nexport interface SignUpData extends LoginData, EventData {\n event: 'signUp'\n eventType: 'vtex:signUp'\n eventName: 'vtex:signUp'\n}\n\ntype PromotionProduct = Pick<ProductSummary, 'productId' | 'productName'>\n\ninterface Promotion {\n id?: string\n name?: string\n creative?: string\n position?: string\n products?: PromotionProduct[]\n}\n\ninterface CartItemAdditionalInfo {\n brandName: string\n brandId: string\n}\n\ninterface CartItem {\n id: string\n productCategories: Record<string, string> | null\n productCategoryIds?: string\n additionalInfo: CartItemAdditionalInfo | null\n brand: string\n ean: string\n category: string\n detailUrl: string\n imageUrl: string\n name: string\n skuName: string\n price: number\n priceIsInt?: boolean\n sellingPrice: number\n productId: string\n productRefId: string\n quantity: number\n skuId: string\n referenceId: string // SKU reference id\n variant: string\n}\n\ninterface Totalizer {\n id: string\n name: string\n value: number\n}\n\ninterface ClientProfileData {\n email: string\n firstName: string\n lastName: string\n}\n\ninterface Address {\n addressId: string\n postalCode: string\n street: string\n number: string\n neighborhood: string\n complement: string\n city: string\n state: string\n}\n\ninterface DeliveryOption {\n id: string\n price: number\n estimate: string\n isSelected: boolean\n}\n\ninterface Shipping {\n selectedAddress: Address\n deliveryOptions?: DeliveryOption[]\n}\n\ninterface MarketingData {\n coupon: string\n utmCampaign: string\n utmSource: string\n utmMedium: string\n utmiCampaign: string\n utmiPage: string\n utmiPart: string\n}\n\nexport interface OrderForm {\n id: string\n totalizers: Totalizer[]\n sellers: Seller[]\n salesChannel: string\n items: CartItem[]\n canEditData: boolean\n loggedIn: boolean\n clientProfileData?: ClientProfileData\n shipping?: Shipping\n value: number\n marketingData?: MarketingData\n}\n\nexport interface Order {\n accountName: string\n corporateName: string\n coupon: string\n currency: string\n openTextField: string\n orderGroup: string\n salesChannel: string\n visitorAddressCity: string\n visitorAddressComplement: string\n visitorAddressCountry: string\n visitorAddressNeighborhood: string\n visitorAddressNumber: string\n visitorAddressPostalCode: string\n visitorAddressState: string\n visitorAddressStreet: string\n visitorContactInfo: string[]\n visitorContactPhone: string\n visitorType: string\n transactionId: string\n transactionDate: string\n transactionAffiliation: string\n transactionTotal: number\n transactionShipping: number\n transactionSubtotal: number\n transactionDiscounts: number\n transactionTax: number\n transactionCurrency: string\n transactionPaymentType: PaymentType[]\n transactionShippingMethod: ShippingMethod[]\n transactionLatestShippingEstimate: Date\n transactionProducts: ProductOrder[]\n transactionPayment: {\n id: string\n }\n}\n\nexport interface Impression {\n product: ProductSummary\n position: number\n}\n\nexport interface PaymentType {\n group: string\n paymentSystemName: string\n installments: number\n value: number\n}\n\nexport interface ShippingMethod {\n itemId: string\n selectedSla: string\n}\n\nexport interface ProductOrder {\n id: string\n name: string\n sku: string\n skuRefId: string\n skuName: string\n productRefId: string\n ean: string\n slug: string\n brand: string\n brandId: string\n seller: string\n sellerId: string\n category: string\n categoryId: string\n categoryTree: string[]\n categoryIdTree: string[]\n priceTags: PriceTag[]\n originalPrice: number\n price: number\n sellingPrice: number\n tax: number\n quantity: number\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n components: any[]\n measurementUnit: string\n unitMultiplier: number\n}\n\nexport interface PriceTag {\n identifier: string\n isPercentual: boolean\n value: number\n}\n\nexport interface Product {\n brand: string\n brandId: string\n categories: string[]\n categoryId: string\n categoryTree: Array<{ id: string; name: string }>\n detailUrl: string\n items: Item[]\n linkText: string\n productId: string\n productName: string\n productReference: string\n selectedSku: Item\n}\n\nexport interface Item {\n itemId: string\n name: string\n ean: string\n referenceId: { Key: string; Value: string }\n imageUrl: string\n sellers: Seller[]\n}\n\nexport interface ProductSummary {\n brand: string\n brandId: string\n categories: string[]\n items: ItemSummary[]\n linkText: string\n productId: string\n productName: string\n productReference: string\n selectedItem: SelectedItem\n sku: ItemSummary\n}\n\ninterface ItemSummary {\n itemId: string\n ean: string\n name: string\n referenceId: { Key: string; Value: string }\n seller: Seller\n sellers: Seller[]\n}\n\nexport interface Seller {\n commertialOffer: CommertialOffer\n sellerId: string\n sellerDefault: boolean\n}\n\nexport interface CommertialOffer {\n Price: number\n PriceWithoutDiscount: number\n ListPrice: number\n AvailableQuantity: number\n}\n\nexport type ProductViewReferenceId = Array<Item['referenceId']>\n\n```"
}
] |
code_speedy-gtm_8146461a
|
[
{
"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 speedy-gtm/react/typings/vtex.render-runtime.d.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import { Component, ComponentType, ReactElement, ReactType } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n interface ExtensionPointProps {\n id: string\n [key: string]: any\n }\n\n export const ExtensionPoint: ComponentType<ExtensionPointProps>\n\n interface ChildBlockProps {\n id: string\n }\n\n export const ChildBlock: ComponentType<ChildBlockProps>\n export const useChildBlock = function({\n id: string,\n }): Record<string, unknown> {}\n\n export const Helmet: ReactElement\n export const Link: ReactType\n export const NoSSR: ReactElement\n export const RenderContextConsumer: ReactElement\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends unknown>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n}\n\n```"
}
] |
code_speedy-gtm_b2067a09
|
[
{
"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 speedy-gtm/react/typings/global.d.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Window extends Window {\n dataLayer: any[]\n\n __gtm__: {\n sendGA4Events: string\n }\n}\n\n```"
}
] |
code_speedy-gtm_81fb40a4
|
[
{
"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 speedy-gtm/react/typings/gtm.d.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface AnalyticsEcommerceProduct {\n id: string\n name: string\n category: string\n brand: string\n variant: string\n price: number\n quantity: number\n dimension1: string\n dimension2: string\n dimension3: string\n}\n\n```"
}
] |
code_speedy-gtm_093f9409
|
[
{
"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 speedy-gtm/react/__tests__/index.test.tsx from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport productImpressionData from '../__mocks__/productImpression'\nimport productDetails from '../__mocks__/productDetail'\nimport productClick from '../__mocks__/productClick'\nimport { buildViewPromotionData } from '../__mocks__/viewPromotion'\nimport { handleEvents } from '../index'\nimport updateEcommerce from '../modules/updateEcommerce'\nimport {\n Promotion,\n PromotionClickData,\n AddToCartData,\n RemoveFromCartData,\n CartItem,\n} from '../typings/events'\nimport { creditCardPaymentInfoMock } from '../__mocks__/addPaymentInfo'\nimport shouldSendGA4Events from '../modules/utils/shouldSendGA4Events'\nimport { beginCheckoutMock } from '../__mocks__/beginCheckout'\nimport { shippingInfoMock } from '../__mocks__/addShippingInfo'\nimport {\n viewCartWithItemsMock,\n viewCartWithNoItemsMock,\n} from '../__mocks__/viewCart'\nimport { transaction, refundTransaction } from '../__mocks__/transaction'\nimport productWishlist from '../__mocks__/addToWishlist'\n\njest.mock('../modules/utils/shouldSendGA4Events')\n\njest.mock('../modules/updateEcommerce', () => jest.fn())\n\nconst mockedUpdate = updateEcommerce as jest.Mock\n\nbeforeEach(() => {\n mockedUpdate.mockReset()\n})\n\ntest('productImpression', () => {\n const message = new MessageEvent('message', {\n data: productImpressionData,\n })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('productImpression', {\n event: 'productImpression',\n ecommerce: {\n currencyCode: 'USD',\n impressions: [\n {\n brand: 'Mizuno',\n category: 'Apparel & Accessories/Shoes',\n id: '16',\n variant: '35',\n list: 'Shelf',\n name: 'Classic Shoes Top',\n position: 1,\n price: '38.9',\n dimension1: '12531',\n dimension2: '232344',\n dimension3: 'Classic Pink',\n },\n {\n brand: 'Nintendo',\n category: 'Apparel & Accessories/Watches',\n id: '15',\n variant: '32',\n list: 'Shelf',\n name: 'Gorgeous Top Watch',\n position: 2,\n price: '2200',\n dimension1: '',\n dimension2: '',\n dimension3: 'Grey',\n },\n ],\n },\n })\n})\n\ntest('productDetail', () => {\n const message = new MessageEvent('message', {\n data: productDetails,\n })\n\n handleEvents(message)\n\n expect(updateEcommerce).toHaveBeenCalledWith('productDetail', {\n event: 'productDetail',\n ecommerce: {\n detail: {\n actionField: {\n list: 'List of products',\n },\n products: [\n {\n brand: 'Mizuno',\n category: 'Apparel & Accessories/Shoes',\n id: '16',\n variant: '35',\n name: 'Classic Shoes Top',\n price: 1540.99,\n dimension1: '123',\n dimension2: '12531',\n dimension3: 'Classic Pink',\n dimension4: 'available',\n },\n ],\n },\n },\n })\n})\n\ntest('productClick', () => {\n const message = new MessageEvent('message', {\n data: productClick,\n })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('productClick', {\n event: 'productClick',\n ecommerce: {\n click: {\n actionField: {\n list: 'List of products',\n },\n products: [\n {\n brand: 'Mizuno',\n category: 'Apparel & Accessories/Shoes',\n id: '16',\n variant: '35',\n name: 'Classic Shoes Top',\n position: 3,\n price: 38.9,\n dimension1: '12531',\n dimension2: '',\n dimension3: 'Classic Pink',\n },\n ],\n },\n },\n })\n})\n\ndescribe('GA4 events', () => {\n const sendGA4Events = true\n const mockedShouldSendGA4Events = shouldSendGA4Events as jest.Mock\n\n beforeEach(() => {\n mockedShouldSendGA4Events.mockReset()\n mockedShouldSendGA4Events.mockReturnValue(sendGA4Events)\n })\n\n describe('view_item_list', () => {\n it('sends an event that signifies that some content was shown to the user', () => {\n const message = new MessageEvent('message', {\n data: productImpressionData,\n })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('view_item_list', {\n ecommerce: {\n item_list_name: 'Shelf',\n items: [\n {\n discount: 0,\n index: 1,\n item_brand: 'Mizuno',\n item_category: 'Apparel & Accessories',\n item_category2: 'Shoes',\n item_id: '16',\n item_name: 'Classic Shoes Top',\n item_variant: '35',\n price: 38.9,\n quantity: 1,\n dimension1: '12531',\n dimension2: '232344',\n dimension3: 'Classic Pink',\n dimension4: 'available',\n },\n {\n discount: 0,\n index: 2,\n item_brand: 'Nintendo',\n item_category: 'Apparel & Accessories',\n item_category2: 'Watches',\n item_id: '15',\n item_name: 'Gorgeous Top Watch',\n item_variant: '32',\n price: 2200,\n quantity: 0,\n dimension1: '',\n dimension2: '',\n dimension3: 'Grey',\n dimension4: 'unavailable',\n },\n ],\n },\n })\n })\n })\n\n describe('view_item', () => {\n it('sends an event that signifies that some content was shown to the user', () => {\n const message = new MessageEvent('message', { data: productDetails })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('view_item', {\n ecommerce: {\n currency: 'USD',\n value: 1540.99,\n items: [\n {\n item_id: '16',\n item_name: 'Classic Shoes Top',\n item_list_name: 'List of products',\n item_brand: 'Mizuno',\n item_variant: '35',\n price: 1540.99,\n quantity: 1,\n discount: 0,\n item_category: 'Apparel & Accessories',\n item_category2: 'Shoes',\n dimension1: '123',\n dimension2: '12531',\n dimension3: 'Classic Pink',\n dimension4: 'available',\n },\n ],\n },\n })\n })\n })\n\n describe('select_item', () => {\n it('sends an event that signifies an item was selected from a list', () => {\n const message = new MessageEvent('message', { data: productClick })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('select_item', {\n ecommerce: {\n item_list_name: 'List of products',\n items: [\n {\n item_id: '16',\n item_name: 'Classic Shoes Top',\n item_list_name: 'List of products',\n item_brand: 'Mizuno',\n item_variant: '35',\n index: 3,\n price: 38.9,\n quantity: 1,\n discount: 0,\n item_category: 'Apparel & Accessories',\n item_category2: 'Shoes',\n dimension1: '12531',\n dimension2: '',\n dimension3: 'Classic Pink',\n dimension4: 'available',\n },\n ],\n },\n })\n })\n })\n\n describe('select_promotion', () => {\n it('sends an event that signifies a promotion was selected from a list', () => {\n const promotion: Promotion = {\n id: 'P_12345',\n name: 'Summer Sale',\n creative: 'Summer Banner',\n position: 'featured_app_1',\n }\n\n const data: PromotionClickData = {\n currency: 'USD',\n event: 'promotionClick',\n eventName: 'vtex:promotionClick',\n eventType: 'vtex:promotionClick',\n promotions: [promotion],\n }\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('select_promotion', {\n ecommerce: {\n creative_name: 'Summer Banner',\n creative_slot: 'featured_app_1',\n promotion_id: 'P_12345',\n promotion_name: 'Summer Sale',\n },\n })\n })\n })\n\n describe('add_to_cart', () => {\n it('sends an event that signifies an item being added to the cart', () => {\n type CartItemMockType = Pick<\n CartItem,\n | 'name'\n | 'brand'\n | 'price'\n | 'skuId'\n | 'skuName'\n | 'quantity'\n | 'category'\n | 'productId'\n | 'productRefId'\n | 'referenceId'\n | 'variant'\n >\n\n const cartItem1: CartItemMockType = {\n productId: '200000202',\n skuId: '2000304',\n brand: 'Sony',\n name: 'Top Wood',\n skuName: 'top_wood_200',\n price: 197.99,\n category: 'Home & Decor',\n quantity: 1,\n productRefId: '123',\n referenceId: '456',\n variant: 'Red',\n }\n\n const cartItem2: CartItemMockType = {\n productId: '200000203',\n skuId: '2000305',\n brand: 'Sony',\n name: 'Top Wood 2',\n skuName: 'top_wood_300',\n price: 150.9,\n category: 'Home & Decor/Tables',\n quantity: 2,\n productRefId: '789',\n referenceId: '101',\n variant: 'Blue',\n }\n\n const data: AddToCartData = {\n currency: 'USD',\n event: 'addToCart',\n eventName: 'vtex:addToCart',\n items: [cartItem1 as CartItem, cartItem2 as CartItem],\n }\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('add_to_cart', {\n ecommerce: {\n currency: 'USD',\n value: 499.79,\n items: [\n {\n item_id: '200000202',\n item_brand: 'Sony',\n item_name: 'Top Wood',\n item_variant: '2000304',\n item_category: 'Home & Decor',\n quantity: 1,\n price: 197.99,\n dimension1: '123',\n dimension2: '456',\n dimension3: 'Red',\n dimension4: 'available',\n },\n {\n item_id: '200000203',\n item_brand: 'Sony',\n item_name: 'Top Wood 2',\n item_variant: '2000305',\n item_category: 'Home & Decor',\n item_category2: 'Tables',\n quantity: 2,\n price: 150.9,\n dimension1: '789',\n dimension2: '101',\n dimension3: 'Blue',\n dimension4: 'available',\n },\n ],\n },\n })\n })\n })\n\n describe('remove_from_cart', () => {\n it('sends an event that signifies an item being removed from cart', () => {\n type CartItemMockType = Pick<\n CartItem,\n | 'name'\n | 'brand'\n | 'price'\n | 'skuId'\n | 'skuName'\n | 'quantity'\n | 'category'\n | 'productId'\n | 'productRefId'\n | 'referenceId'\n | 'variant'\n >\n\n const cartItem: CartItemMockType = {\n productId: '200000202',\n skuId: '2000304',\n brand: 'Sony',\n name: 'Top Wood',\n skuName: 'top_wood_200',\n price: 197.99,\n category: 'Home & Decor',\n quantity: 3,\n productRefId: '123',\n referenceId: '456',\n variant: 'Red',\n }\n\n const data: RemoveFromCartData = {\n currency: 'USD',\n event: 'removeFromCart',\n eventName: 'vtex:removeFromCart',\n items: [cartItem as CartItem],\n }\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('remove_from_cart', {\n ecommerce: {\n currency: 'USD',\n value: 593.97,\n items: [\n {\n item_id: '200000202',\n item_brand: 'Sony',\n item_name: 'Top Wood',\n item_variant: '2000304',\n item_category: 'Home & Decor',\n quantity: 3,\n price: 197.99,\n dimension1: '123',\n dimension2: '456',\n dimension3: 'Red',\n dimension4: 'available',\n },\n ],\n },\n })\n })\n })\n\n describe('purchase', () => {\n it('sends an event that signifies a successful checkout on orderPlaced page', () => {\n const data = transaction\n\n data.event = 'orderPlaced'\n data.eventName = 'vtex:orderPlaced'\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('purchase', {\n ecommerce: {\n coupon: null,\n currency: 'USD',\n items: [\n {\n item_brand: 'New Offers!!',\n item_category: 'Apparel & Accessories',\n item_id: '9',\n item_name: 'Top Everyday Necessaire',\n item_variant: '20',\n price: 1600.99,\n quantity: 2,\n dimension1: '',\n dimension2: '9812983',\n dimension3: '100 RMS',\n dimension4: 'available',\n },\n ],\n shipping: 1942.61,\n tax: 0,\n transaction_id: '1310750551387',\n value: 5144.59,\n },\n })\n })\n })\n\n describe('view_promotion', () => {\n it('sends an event that signifies a promotion was viewed from a list', () => {\n const data = buildViewPromotionData({\n id: 'P_12345',\n name: 'Summer Sale',\n creative: 'Summer Banner',\n position: 'featured_app_1',\n products: [\n {\n productId: 'SKU_20',\n productName: 'Tea Leaves',\n },\n {\n productId: 'SKU_30',\n productName: 'Coffee Beans',\n },\n ],\n })\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('view_promotion', {\n ecommerce: {\n creative_name: 'Summer Banner',\n creative_slot: 'featured_app_1',\n promotion_id: 'P_12345',\n promotion_name: 'Summer Sale',\n items: [\n {\n item_id: 'SKU_20',\n item_name: 'Tea Leaves',\n },\n {\n item_id: 'SKU_30',\n item_name: 'Coffee Beans',\n },\n ],\n },\n })\n })\n })\n\n describe('add_payment_info', () => {\n it('sends an event when a user add a payment information (credit card)', () => {\n const data = creditCardPaymentInfoMock\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('add_payment_info', {\n ecommerce: {\n currency: 'USD',\n value: 211.19,\n payment_type: 'creditCard',\n items: [\n {\n item_id: '200000202',\n item_brand: 'Sony',\n item_name: 'Top Wood',\n item_variant: '2000304',\n item_category: 'Home & Decor',\n quantity: 1,\n price: 197.99,\n dimension1: '123',\n dimension2: '456',\n dimension3: 'Red',\n dimension4: 'available',\n },\n ],\n },\n })\n })\n })\n\n describe('begin_checkout', () => {\n it('sends an event when a user access the checkout page', () => {\n const data = beginCheckoutMock\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('begin_checkout', {\n ecommerce: {\n currency: 'USD',\n value: 650.69,\n items: [\n {\n item_id: '200000202',\n item_brand: 'Sony',\n item_name: 'Top Wood',\n item_variant: '2000304',\n item_category: 'Home & Decor',\n quantity: 1,\n price: 197.99,\n dimension1: '123',\n dimension2: '456',\n dimension3: 'Red',\n dimension4: 'available',\n },\n {\n item_id: '200000203',\n item_brand: 'Sony',\n item_name: 'Top Wood 2',\n item_variant: '2000305',\n item_category: 'Home & Decor',\n item_category2: 'Tables',\n quantity: 3,\n price: 150.9,\n dimension1: '789',\n dimension2: '101',\n dimension3: 'Blue',\n dimension4: 'available',\n },\n ],\n },\n })\n })\n })\n\n describe('view_cart', () => {\n it('sends an event when a user opens the cart with items', () => {\n const data = viewCartWithItemsMock\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('view_cart', {\n ecommerce: {\n currency: 'USD',\n value: 546.88,\n items: [\n {\n item_id: '200000202',\n item_brand: 'Sony',\n item_name: 'Top Wood',\n item_variant: '2000304',\n item_category: 'Home & Decor',\n quantity: 2,\n price: 197.99,\n dimension1: '123',\n dimension2: '456',\n dimension3: 'Red',\n dimension4: 'available',\n },\n {\n item_id: '200000203',\n item_brand: 'Sony',\n item_name: 'Top Wood 2',\n item_variant: '2000305',\n item_category: 'Home & Decor',\n item_category2: 'Tables',\n quantity: 1,\n price: 150.9,\n dimension1: '789',\n dimension2: '101',\n dimension3: 'Blue',\n dimension4: 'available',\n },\n ],\n },\n })\n })\n\n it('sends an event when a user opens the cart with no items', () => {\n const data = viewCartWithNoItemsMock\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('view_cart', {\n ecommerce: {\n currency: 'USD',\n value: 0.0,\n items: [],\n },\n })\n })\n })\n\n describe('refund', () => {\n it('sends an event when the user refunds an order', () => {\n const data = refundTransaction\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('refund', {\n ecommerce: {\n currency: 'USD',\n items: [\n {\n item_brand: 'New Offers!!',\n item_category: 'Apparel & Accessories',\n item_id: '9',\n item_name: 'Top Everyday Necessaire',\n item_variant: '20',\n price: 1600.99,\n quantity: 2,\n dimension1: '',\n dimension2: '9812983',\n dimension3: '100 RMS',\n dimension4: 'available',\n },\n ],\n shipping: 1942.61,\n tax: 0,\n transaction_id: '1310750551387',\n value: 3543.6,\n },\n })\n })\n })\n\n describe('add_shipping_info', () => {\n it('sends an event when a user add a shipping info', () => {\n const data = shippingInfoMock\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('add_shipping_info', {\n ecommerce: {\n currency: 'USD',\n value: 1958.35,\n shipping_tier: 'Ground',\n items: [\n {\n item_id: '200000202',\n item_brand: 'Sony',\n item_name: 'Top Wood',\n item_variant: '2000304',\n item_category: 'Home & Decor',\n quantity: 1,\n price: 197.99,\n dimension1: '123',\n dimension2: '456',\n dimension3: 'Red',\n dimension4: 'available',\n },\n ],\n },\n })\n })\n })\n\n describe('add_to_wishlist', () => {\n it('sends an event when the user add a product to wishlist', () => {\n const message = new MessageEvent('message', { data: productWishlist })\n\n message.data.eventName = 'vtex:addToWishlist'\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('add_to_wishlist', {\n ecommerce: {\n currency: 'USD',\n value: 1540.99,\n items: [\n {\n item_id: '16',\n item_name: 'Classic Shoes Top',\n item_list_name: 'List of products',\n item_brand: 'Mizuno',\n item_variant: '35',\n price: 1540.99,\n quantity: 1,\n discount: 0,\n item_category: 'Apparel & Accessories',\n item_category2: 'Shoes',\n dimension1: '123',\n dimension2: '12531',\n dimension3: 'Classic Pink',\n dimension4: 'available',\n },\n ],\n },\n })\n })\n })\n describe('login', () => {\n it('sends an event when a user login on store with any method', () => {\n const data = {\n event: 'login',\n eventName: 'vtex:login',\n method: 'Google',\n }\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('login', {\n ecommerce: {\n method: 'Google',\n },\n })\n })\n })\n describe('search', () => {\n it('sends an event when a user search for a term on store', () => {\n const data = {\n event: 'search',\n eventName: 'vtex:search',\n term: 'Top Wood',\n }\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('search', {\n ecommerce: {\n search_term: 'Top Wood',\n },\n })\n })\n })\n\n describe('sign_up', () => {\n it('sends an event when a user signup on store with any method', () => {\n const data = {\n event: 'signUp',\n eventName: 'vtex:signUp',\n method: 'Google',\n }\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('sign_up', {\n ecommerce: {\n method: 'Google',\n },\n })\n })\n })\n\n describe('share', () => {\n it('sends an event when a user share a product via any type', () => {\n const data = {\n event: 'share',\n eventName: 'vtex:share',\n method: 'Facebook',\n contentType: 'image',\n itemId: '10',\n }\n\n const message = new MessageEvent('message', { data })\n\n handleEvents(message)\n\n expect(mockedUpdate).toHaveBeenCalledWith('share', {\n ecommerce: {\n method: 'Facebook',\n content_type: 'image',\n item_id: '10',\n },\n })\n })\n })\n})\n\n```"
}
] |
code_speedy-gtm_7f741f4a
|
[
{
"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 speedy-gtm/react/modules/push.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createOrGetAnalyticsData } from './analytics'\n\nwindow.dataLayer = window.dataLayer || []\n\nlet isFirstPush = true\n\nexport default function push(rawEvent: Record<string, unknown>) {\n const {\n location: originalLocation,\n referrer: originalReferrer,\n origin,\n } = createOrGetAnalyticsData()\n\n let event = rawEvent\n\n if (isFirstPush || origin === 'fresh') {\n isFirstPush = false\n\n event = {\n ...rawEvent,\n originalLocation,\n originalReferrer,\n }\n }\n\n window.dataLayer.push(event)\n}\n\n```"
}
] |
code_speedy-gtm_074a8d8e
|
[
{
"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 speedy-gtm/react/modules/updateEcommerce.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport push from './push'\n\nexport default function updateEcommerce(\n eventName: string,\n data: Record<string, unknown>\n) {\n push({ ecommerce: null, ecommerceV2: null })\n\n data.event ? push(data) : push({ event: eventName, ...data })\n}\n\n```"
}
] |
code_speedy-gtm_9687e3d4
|
[
{
"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 speedy-gtm/react/modules/enhancedEcommerceEvents.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport updateEcommerce from './updateEcommerce'\nimport {\n PixelMessage,\n ProductOrder,\n Impression,\n CartItem,\n} from '../typings/events'\nimport { AnalyticsEcommerceProduct } from '../typings/gtm'\nimport {\n purchase,\n selectItem,\n selectPromotion,\n viewItem,\n viewItemList,\n viewPromotion,\n addToCart,\n removeFromCart,\n addPaymentInfo,\n beginCheckout,\n addShippingInfo,\n viewCart,\n search,\n login,\n refund,\n addToWishlist,\n signUp,\n share,\n} from './gaEvents'\nimport {\n getCategory,\n getSeller,\n getProductNameWithoutVariant,\n getPurchaseObjectData,\n} from './utils'\nimport {\n customDimensionSkuAvailability,\n productViewSkuReference,\n} from './customDimensions'\n\nexport async function sendEnhancedEcommerceEvents(e: PixelMessage) {\n switch (e.data.eventName) {\n case 'vtex:productView': {\n const {\n productId,\n productReference,\n selectedSku,\n productName,\n brand,\n categories,\n } = e.data.product\n\n const productAvailableQuantity = getSeller(selectedSku.sellers)\n .commertialOffer.AvailableQuantity\n\n const isAvailable = customDimensionSkuAvailability(\n productAvailableQuantity\n )\n\n // Product summary list title. Ex: 'List of products'\n const list = e.data.list ? { actionField: { list: e.data.list } } : {}\n\n let price\n\n try {\n price = getSeller(selectedSku.sellers).commertialOffer.Price\n } catch {\n price = undefined\n }\n\n const data = {\n ecommerce: {\n detail: {\n ...list,\n products: [\n {\n brand,\n category: getCategory(categories),\n id: productId,\n variant: selectedSku.itemId,\n name: productName,\n dimension1: productReference ?? '',\n dimension2: productViewSkuReference(e.data.product) ?? '',\n dimension3: selectedSku.name,\n dimension4: isAvailable,\n price,\n },\n ],\n },\n },\n event: 'productDetail',\n }\n\n viewItem(e.data)\n updateEcommerce('productDetail', data)\n\n return\n }\n\n case 'vtex:productClick': {\n const { product, position } = e.data\n const {\n productName,\n brand,\n categories,\n sku,\n productId,\n productReference,\n } = product\n\n // Product summary list title. Ex: 'List of products'\n const list = e.data.list ? { actionField: { list: e.data.list } } : {}\n\n let price\n\n try {\n price = getSeller(sku?.sellers ?? product.items[0].sellers)\n .commertialOffer.Price\n } catch {\n price = undefined\n }\n\n const data = {\n event: 'productClick',\n ecommerce: {\n click: {\n ...list,\n products: [\n {\n brand,\n category: getCategory(categories),\n id: productId,\n variant: sku.itemId,\n name: productName,\n dimension1: productReference ?? '',\n dimension2: sku.referenceId?.Value ?? '',\n dimension3: sku.name,\n price,\n position,\n },\n ],\n },\n },\n }\n\n selectItem(e.data)\n updateEcommerce('productClick', data)\n\n return\n }\n\n case 'vtex:addToCart': {\n const { items } = e.data\n\n const data = {\n ecommerce: {\n add: {\n products: items.map(item => ({\n brand: item.brand,\n category: item.category,\n id: item.productId,\n variant: item.skuId,\n name: item.name, // Product name\n price:\n item.priceIsInt === true\n ? `${item.price / 100}`\n : `${item.price}`,\n quantity: item.quantity,\n dimension1: item.productRefId ?? '',\n dimension2: item.referenceId ?? '', // SKU reference id\n dimension3: item.variant, // SKU name (variant)\n })),\n },\n currencyCode: e.data.currency,\n },\n event: 'addToCart',\n }\n\n addToCart(e.data)\n updateEcommerce('addToCart', data)\n\n return\n }\n\n case 'vtex:removeFromCart': {\n const { items } = e.data\n\n const data = {\n ecommerce: {\n currencyCode: e.data.currency,\n remove: {\n products: items.map(item => ({\n brand: item.brand,\n category: item.category,\n id: item.productId,\n variant: item.skuId,\n name: item.name, // Product name\n price:\n item.priceIsInt === true\n ? `${item.price / 100}`\n : `${item.price}`,\n quantity: item.quantity,\n dimension1: item.productRefId ?? '',\n dimension2: item.referenceId ?? '', // SKU reference id\n dimension3: item.variant, // SKU name (variant)\n })),\n },\n },\n event: 'removeFromCart',\n }\n\n removeFromCart(e.data)\n updateEcommerce('removeFromCart', data)\n\n return\n }\n\n case 'vtex:orderPlaced': {\n const order = e.data\n\n const ecommerce = {\n purchase: {\n actionField: getPurchaseObjectData(order),\n products: order.transactionProducts.map((product: ProductOrder) =>\n getProductObjectData(product)\n ),\n },\n }\n\n const data = {\n // @ts-ignore\n event: 'orderPlaced',\n ...order,\n // The name ecommerceV2 was introduced as a fix, so it is possible that some clients\n // were using this as it was called before (ecommerce). For that reason,\n // it will also be sent as ecommerce to the dataLayer.\n ecommerce,\n // This variable is called ecommerceV2 so it matches the variable name present on the checkout\n // This way, users can have one single tag for checkout and orderPlaced events\n ecommerceV2: {\n ecommerce,\n },\n }\n\n purchase(order)\n updateEcommerce('orderPlaced', data)\n\n return\n }\n\n case 'vtex:productImpression': {\n const { currency, list, impressions } = e.data\n\n const parsedImpressions = (impressions || []).map(\n getProductImpressionObjectData(list)\n )\n\n const data = {\n event: 'productImpression',\n ecommerce: {\n currencyCode: currency,\n impressions: parsedImpressions,\n },\n }\n\n viewItemList(e.data)\n updateEcommerce('productImpression', data)\n\n return\n }\n\n case 'vtex:cartLoaded': {\n const { orderForm } = e.data\n\n const data = {\n event: 'checkout',\n ecommerce: {\n checkout: {\n actionField: {\n step: 1,\n },\n products: orderForm.items.map(getCheckoutProductObjectData),\n },\n },\n }\n\n updateEcommerce('checkout', data)\n\n break\n }\n\n case 'vtex:promoView': {\n const { promotions } = e.data\n\n const data = {\n event: 'promoView',\n ecommerce: {\n promoView: {\n promotions,\n },\n },\n }\n\n viewPromotion(e.data)\n updateEcommerce('promoView', data)\n\n break\n }\n\n case 'vtex:promotionClick': {\n const { promotions } = e.data\n\n const data = {\n event: 'promotionClick',\n ecommerce: {\n promoClick: {\n promotions,\n },\n },\n }\n\n selectPromotion(e.data)\n updateEcommerce('promotionClick', data)\n\n break\n }\n\n case 'vtex:addPaymentInfo': {\n addPaymentInfo(e.data)\n\n break\n }\n\n case 'vtex:beginCheckout': {\n beginCheckout(e.data)\n\n break\n }\n\n case 'vtex:addShippingInfo': {\n addShippingInfo(e.data)\n\n break\n }\n\n case 'vtex:viewCart': {\n viewCart(e.data)\n\n break\n }\n\n case 'vtex:login': {\n login(e.data)\n\n break\n }\n\n case 'vtex:signUp': {\n signUp(e.data)\n\n break\n }\n\n case 'vtex:refund': {\n refund(e.data)\n\n break\n }\n\n case 'vtex:addToWishlist': {\n addToWishlist(e.data)\n\n break\n }\n\n case 'vtex:search': {\n search(e.data)\n\n break\n }\n\n case 'vtex:share': {\n share(e.data)\n\n break\n }\n\n default: {\n break\n }\n }\n}\n\nfunction getProductObjectData(product: ProductOrder) {\n const productName = getProductNameWithoutVariant(\n product.name,\n product.skuName\n )\n\n return {\n brand: product.brand,\n category: product.categoryTree?.join('/'),\n id: product.id, // Product id\n variant: product.sku, // SKU id\n name: productName, // Product name\n price: product.price,\n quantity: product.quantity,\n dimension1: product.productRefId ?? '',\n dimension2: product.skuRefId ?? '',\n dimension3: product.skuName, // SKU name (only variant)\n }\n}\n\nfunction getProductImpressionObjectData(list: string) {\n return ({ product, position }: Impression) => ({\n brand: product.brand,\n category: getCategory(product.categories),\n id: product.productId, // Product id\n variant: product.sku.itemId, // SKU id\n list,\n name: product.productName,\n position,\n price: `${product.sku.seller.commertialOffer.Price}`,\n dimension1: product.productReference ?? '',\n dimension2: product.sku.referenceId?.Value ?? '',\n dimension3: product.sku.name, // SKU name (variation only)\n })\n}\n\nfunction getCheckoutProductObjectData(\n item: CartItem\n): AnalyticsEcommerceProduct {\n const productName = getProductNameWithoutVariant(item.name, item.skuName)\n\n return {\n id: item.productId, // Product id\n variant: item.id, // SKU id\n name: productName, // Product name without variant\n category: Object.keys(item.productCategories ?? {}).reduce(\n (categories, category) =>\n categories ? `${categories}/${category}` : category,\n ''\n ),\n brand: item.additionalInfo?.brandName ?? '',\n price: item.sellingPrice / 100,\n quantity: item.quantity,\n dimension1: item.productRefId ?? '',\n dimension2: item.referenceId ?? '', // SKU reference id\n dimension3: item.skuName,\n }\n}\n\n```"
}
] |
code_speedy-gtm_18ccc407
|
[
{
"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 speedy-gtm/react/modules/legacyEvents.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport push from './push'\nimport { PixelMessage, SearchPageInfoData } from '../typings/events'\n\nexport async function sendLegacyEvents(e: PixelMessage) {\n switch (e.data.eventName) {\n case 'vtex:pageInfo': {\n const { eventType } = e.data\n\n switch (eventType) {\n case 'homeView': {\n push({\n event: 'homeView',\n })\n break\n }\n\n case 'categoryView': {\n const data = e.data as SearchPageInfoData\n\n push({\n event: 'categoryView',\n departmentId: data.department?.id,\n departmentName: data.department?.name,\n categoryId: data.category?.id,\n categoryName: data.category?.name,\n })\n break\n }\n\n case 'departmentView': {\n const data = e.data as SearchPageInfoData\n\n push({\n event: 'departmentView',\n departmentId: data.department?.id,\n departmentName: data.department?.name,\n })\n break\n }\n\n case 'emptySearchView':\n\n // eslint-disable-next-line no-fallthrough\n case 'internalSiteSearchView': {\n const data = e.data as SearchPageInfoData\n\n push({\n event: 'internalSiteSearchView',\n siteSearchTerm: data.search?.term,\n siteSearchForm: window.location.href,\n siteSearchCategory: data.search?.category?.id,\n siteSearchResults: data.search?.results,\n })\n\n break\n }\n\n case 'productView': {\n push({\n event: 'productView',\n })\n break\n }\n\n default: {\n push({\n event: 'otherView',\n })\n break\n }\n }\n\n break\n }\n\n default: {\n break\n }\n }\n}\n\n```"
}
] |
code_speedy-gtm_6536282e
|
[
{
"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 speedy-gtm/react/modules/utils.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n CartItem,\n Impression,\n Order,\n ProductOrder,\n Seller,\n} from '../typings/events'\nimport { customDimensions } from './customDimensions'\n\nexport function getSeller(sellers: Seller[]) {\n const defaultSeller = sellers.find(seller => seller.sellerDefault)\n\n if (!defaultSeller) {\n return sellers[0]\n }\n\n return defaultSeller\n}\n\nexport function getPrice(seller: Seller) {\n let price\n\n try {\n price = seller.commertialOffer.Price\n } catch {\n price = undefined\n }\n\n return price\n}\n\nfunction formatCategoriesHierarchy(\n categories: { [key: string]: string },\n value: string,\n index: number\n) {\n const categoryHierarchyNumber = index + 1\n const isFirstCategory = categoryHierarchyNumber === 1\n const key = `item_category${isFirstCategory ? '' : categoryHierarchyNumber}`\n\n categories[key] = value\n}\n\nexport function getCategoriesWithHierarchy(categoriesArray: string[]) {\n if (!categoriesArray || !categoriesArray.length) return\n\n const categoryString = getCategory(categoriesArray)\n const categories = splitIntoCategories(categoryString)\n\n if (!categories || !categoryString) return {}\n\n const categoriesFormatted: { [key: string]: string } = {}\n\n if (!categories || !categories.length) {\n formatCategoriesHierarchy(categoriesFormatted, categoryString, 0)\n } else {\n categories.forEach((category, index) => {\n formatCategoriesHierarchy(categoriesFormatted, category, index)\n })\n }\n\n return categoriesFormatted\n}\n\nfunction getCategoriesHierarchyByKey(\n categories: Record<string, string> | null,\n keysArray?: string[]\n) {\n if (!keysArray || !keysArray.length || !categories) return []\n const categoriesFormatted: string[] = []\n const categoriesHierarchyFormatted = {}\n\n keysArray.forEach(key => {\n if (key) categoriesFormatted.push(categories[key])\n })\n\n categoriesFormatted.forEach((category, index) => {\n formatCategoriesHierarchy(categoriesHierarchyFormatted, category, index)\n })\n\n return categoriesHierarchyFormatted\n}\n\nexport function getQuantity(seller: Seller) {\n const isAvailable = seller.commertialOffer.AvailableQuantity > 0\n\n return isAvailable ? 1 : 0\n}\n\nexport function getImpressions(impressions: Impression[]) {\n if (!impressions || !impressions.length) return []\n\n const formattedImpressions = impressions.map(impression => {\n const { product, position } = impression\n const {\n productName,\n productId,\n productReference,\n sku,\n brand,\n categories,\n } = product\n\n const { itemId, seller, referenceId, name } = sku\n\n const price = getPrice(seller)\n const discount = getDiscount(seller)\n const quantity = getQuantity(seller)\n\n const categoriesHierarchy = getCategoriesWithHierarchy(categories)\n\n return {\n item_id: productId,\n item_name: productName,\n item_variant: itemId,\n item_brand: brand,\n index: position,\n discount,\n price,\n quantity,\n ...categoriesHierarchy,\n ...customDimensions({\n productReference,\n skuReference: referenceId?.Value,\n skuName: name,\n quantity,\n }),\n }\n })\n\n return formattedImpressions\n}\n\nexport function getDiscount(seller: Seller) {\n if (!seller.commertialOffer.PriceWithoutDiscount) return 0\n\n const { commertialOffer } = seller\n const { Price, PriceWithoutDiscount } = commertialOffer\n\n if (PriceWithoutDiscount <= Price) return 0\n\n let price\n\n try {\n price = PriceWithoutDiscount - Price\n } catch {\n price = 0\n }\n\n return price\n}\n\nexport function getCategory(rawCategories: string[]) {\n if (!rawCategories || !rawCategories.length) {\n return\n }\n\n return removeStartAndEndSlash(rawCategories[0])\n}\n\n// Transform this: \"/Apparel & Accessories/Clothing/Tops/\"\n// To this: \"Apparel & Accessories/Clothing/Tops\"\nfunction removeStartAndEndSlash(category?: string) {\n return category?.replace(/^\\/|\\/$/g, '')\n}\n\nfunction splitIntoCategories(category?: string) {\n if (!category) return\n\n const splitted = category.split('/')\n\n return splitted\n}\n\nexport function getPurchaseObjectData(order: Order) {\n return {\n affiliation: order.transactionAffiliation,\n coupon: order.coupon ? order.coupon : null,\n id: order.orderGroup,\n revenue: order.transactionTotal,\n shipping: order.transactionShipping,\n tax: order.transactionTax,\n }\n}\n\nexport function getProductNameWithoutVariant(\n productNameWithVariant: string,\n variant: string\n) {\n const indexOfVariant = productNameWithVariant.lastIndexOf(variant)\n\n if (indexOfVariant === -1 || indexOfVariant === 0) {\n return productNameWithVariant\n }\n\n return productNameWithVariant.substring(0, indexOfVariant - 1) // Removes the variant and the whitespace\n}\n\nfunction formatPurchaseProduct(product: ProductOrder) {\n const {\n name,\n skuName,\n id,\n brand,\n sku,\n price,\n quantity,\n categoryTree,\n productRefId,\n skuRefId,\n } = product\n\n const productName = getProductNameWithoutVariant(name, skuName)\n\n const item = {\n item_id: id,\n item_name: productName,\n item_brand: brand,\n item_variant: sku,\n price,\n quantity,\n ...getCategoriesWithHierarchy([categoryTree.join('/')]),\n ...customDimensions({\n productReference: productRefId,\n skuReference: skuRefId,\n skuName,\n quantity,\n }),\n }\n\n return item\n}\n\nexport function formatCartItemsAndValue(\n cartItems: CartItem[],\n options?: {\n dividePrice: boolean\n }\n) {\n let totalValue = 0.0\n\n if (!cartItems.length) return { items: [], totalValue }\n\n const items = cartItems.map((item: CartItem) => {\n const productName = getProductNameWithoutVariant(item.name, item.skuName)\n\n const shouldFormatPrice = item.priceIsInt ?? options?.dividePrice\n\n const formattedPrice = shouldFormatPrice ? item.price / 100 : item.price\n\n const itemBrand = item.brand ? item.brand : item.additionalInfo?.brandName\n\n const categoryIds = splitIntoCategories(item.productCategoryIds)\n const formattedCategories = item.category\n ? getCategoriesWithHierarchy([item.category])\n : getCategoriesHierarchyByKey(item.productCategories, categoryIds)\n\n totalValue += formattedPrice * item.quantity\n\n return {\n item_id: item.productId,\n item_brand: itemBrand,\n item_name: productName,\n item_variant: item.skuId,\n quantity: item.quantity,\n price: formattedPrice,\n ...formattedCategories,\n ...customDimensions({\n productReference: item.productRefId,\n skuReference: item.referenceId,\n skuName: item.variant,\n quantity: item.quantity,\n }),\n }\n })\n\n return { items, totalValue }\n}\n\nexport function getPurchaseItems(orderProducts: ProductOrder[]) {\n return orderProducts.map(formatPurchaseProduct)\n}\n\n```"
}
] |
code_speedy-gtm_417bfcc0
|
[
{
"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 speedy-gtm/react/modules/extraEvents.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport push from './push'\nimport { PixelMessage } from '../typings/events'\n\n\nasync function emailToHash(email:string) {\n const msgUint8 = new TextEncoder().encode(email); \n const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n return hashHex;\n}\n\nexport async function sendExtraEvents(e: PixelMessage) {\n\n switch (e.data.eventName) {\n case 'vtex:pageView': {\n push({\n event: 'pageView',\n location: e.data.pageUrl,\n page: e.data.pageUrl.replace(e.origin, ''),\n referrer: e.data.referrer,\n ...(e.data.pageTitle && {\n title: e.data.pageTitle,\n }),\n })\n\n return\n }\n\n case 'vtex:userData': {\n const { data } = e\n\n if (!data.isAuthenticated) {\n return\n }\n\n const emailHash = data.email ? await emailToHash(data.email) : undefined\n\n push({\n event: 'userData',\n userId: data.id,\n emailHash: emailHash \n })\n\n break\n }\n\n default: {\n break\n }\n }\n}\n\n```"
}
] |
code_speedy-gtm_e019484c
|
[
{
"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 speedy-gtm/react/modules/gaEvents.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n AddToCartData,\n RemoveFromCartData,\n PromoViewData,\n OrderPlacedData,\n AddPaymentInfoData,\n ProductClickData,\n ProductViewData,\n ProductImpressionData,\n BeginCheckoutData,\n AddShippingInfoData,\n ViewCartData,\n SearchData,\n LoginData,\n RefundData,\n AddToWishlistData,\n SignUpData,\n ShareData,\n PromotionClickData,\n} from '../typings/events'\nimport updateEcommerce from './updateEcommerce'\nimport {\n getPrice,\n getSeller,\n getCategoriesWithHierarchy,\n getQuantity,\n getImpressions,\n getDiscount,\n getPurchaseObjectData,\n getPurchaseItems,\n formatCartItemsAndValue,\n} from './utils'\nimport { customDimensions, productViewSkuReference } from './customDimensions'\nimport shouldSendGA4Events from './utils/shouldSendGA4Events'\n\nexport function viewItem(eventData: ProductViewData) {\n if (!shouldSendGA4Events()) return\n\n const eventName = 'view_item'\n\n const { currency, product, list } = eventData\n\n const {\n selectedSku,\n productName,\n productId,\n productReference,\n categories,\n brand,\n } = product\n\n const { itemId: variant } = selectedSku\n\n const seller = getSeller(selectedSku.sellers)\n const value = getPrice(seller)\n const categoriesHierarchy = getCategoriesWithHierarchy(categories)\n const discount = getDiscount(seller)\n const quantity = getQuantity(seller)\n\n const item = {\n item_id: productId,\n item_name: productName,\n item_list_name: list,\n item_brand: brand,\n item_variant: variant,\n discount,\n quantity,\n price: value,\n ...categoriesHierarchy,\n ...customDimensions({\n productReference,\n skuReference: productViewSkuReference(product),\n skuName: selectedSku.name,\n quantity,\n }),\n }\n\n const data = {\n currency,\n value,\n items: [item],\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function viewItemList(eventData: ProductImpressionData) {\n if (!shouldSendGA4Events()) return\n\n const eventName = 'view_item_list'\n\n const { list, impressions } = eventData\n\n const items = getImpressions(impressions)\n\n const data = {\n item_list_name: list,\n items,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function selectItem(eventData: ProductClickData) {\n if (!shouldSendGA4Events()) return\n\n const eventName = 'select_item'\n\n const { product, list, position } = eventData\n\n const {\n sku,\n productName,\n productId,\n productReference,\n categories,\n brand,\n } = product\n\n const { itemId: variant, referenceId, name } = sku\n\n const seller = getSeller(sku.sellers)\n const price = getPrice(seller)\n const categoriesHierarchy = getCategoriesWithHierarchy(categories)\n const discount = getDiscount(seller)\n const quantity = getQuantity(seller)\n\n const item = {\n item_id: productId,\n item_name: productName,\n item_list_name: list,\n item_brand: brand,\n item_variant: variant,\n index: position,\n price,\n quantity,\n discount,\n ...categoriesHierarchy,\n ...customDimensions({\n productReference,\n skuReference: referenceId?.Value,\n skuName: name,\n quantity,\n }),\n }\n\n const data = {\n item_list_name: list,\n items: [item],\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function selectPromotion(eventData: PromotionClickData) {\n if (!shouldSendGA4Events()) return\n\n const eventName = 'select_promotion'\n const [promotion] = eventData.promotions\n\n const data = {\n creative_name: promotion.creative,\n creative_slot: promotion.position,\n promotion_id: promotion.id,\n promotion_name: promotion.name,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function viewPromotion(eventData: PromoViewData) {\n if (!shouldSendGA4Events()) return\n\n const eventName = 'view_promotion'\n\n const {\n promotions: [{ creative, position, id, name, products }],\n } = eventData\n\n let items: Array<{ item_id: string; item_name: string }> = []\n\n if (products?.length) {\n items = products.map(product => ({\n item_id: product.productId,\n item_name: product.productName,\n }))\n }\n\n const data = {\n creative_name: creative,\n creative_slot: position,\n promotion_id: id,\n promotion_name: name,\n items,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function addToCart(eventData: AddToCartData) {\n if (!shouldSendGA4Events()) return\n\n const eventName = 'add_to_cart'\n\n const { items: eventDataItems, currency } = eventData\n\n const { items, totalValue } = formatCartItemsAndValue(eventDataItems)\n\n const data = {\n items,\n currency,\n value: totalValue,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function removeFromCart(eventData: RemoveFromCartData) {\n if (!shouldSendGA4Events()) return\n\n const eventName = 'remove_from_cart'\n\n const { items: eventDataItems, currency } = eventData\n\n const { items, totalValue } = formatCartItemsAndValue(eventDataItems)\n\n const data = {\n items,\n currency,\n value: totalValue,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function purchase(eventData: OrderPlacedData) {\n if (!shouldSendGA4Events()) return\n\n const eventName = 'purchase'\n\n const { id, revenue, tax, shipping, coupon } = getPurchaseObjectData(\n eventData\n )\n\n const { transactionProducts, currency } = eventData\n\n const items = getPurchaseItems(transactionProducts)\n\n const data = {\n transaction_id: id,\n value: revenue,\n tax,\n shipping,\n coupon,\n items,\n currency,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function addPaymentInfo(eventData: AddPaymentInfoData) {\n const eventName = 'add_payment_info'\n\n const { currency, payment, items: eventDataItems } = eventData\n const { value, group } = payment\n\n const { items } = formatCartItemsAndValue(eventDataItems)\n\n const formattedValue = value / 100\n\n const data = {\n currency,\n value: formattedValue,\n payment_type: group,\n items,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function beginCheckout(eventData: BeginCheckoutData) {\n const eventName = 'begin_checkout'\n\n const { currency, items: eventDataItems } = eventData\n\n const { items, totalValue } = formatCartItemsAndValue(eventDataItems)\n\n const data = {\n currency,\n value: totalValue,\n items,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function addShippingInfo(eventData: AddShippingInfoData) {\n const eventName = 'add_shipping_info'\n\n const { currency, items: eventDataItems, shippingTier, value } = eventData\n\n const { items } = formatCartItemsAndValue(eventDataItems)\n\n const data = {\n currency,\n value,\n items,\n shipping_tier: shippingTier,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function viewCart(eventData: ViewCartData) {\n const eventName = 'view_cart'\n\n const { currency, items: eventDataItems } = eventData\n\n const { items, totalValue } = formatCartItemsAndValue(eventDataItems, {\n dividePrice: true,\n })\n\n const data = {\n currency,\n value: totalValue,\n items,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function addToWishlist(eventData: AddToWishlistData) {\n const eventName = 'add_to_wishlist'\n\n const { currency, items, list } = eventData\n\n const { product } = items\n\n const {\n sku,\n productName,\n productId,\n categories,\n brand,\n productReference,\n } = product\n\n const variant = sku ? sku.itemId : items.selectedItem.itemId\n\n const seller = getSeller(sku ? sku.sellers : items.selectedItem.sellers)\n const value = getPrice(seller)\n const categoriesHierarchy = getCategoriesWithHierarchy(categories)\n const discount = getDiscount(seller)\n const quantity = getQuantity(seller)\n\n const item = {\n item_id: productId,\n item_name: productName,\n item_list_name: list,\n item_brand: brand,\n item_variant: variant,\n discount,\n quantity,\n price: value,\n ...categoriesHierarchy,\n ...customDimensions({\n productReference,\n skuReference: sku ? sku.referenceId.Value : items.selectedItem.referenceId,\n skuName: sku ? sku.name : items.selectedItem.name,\n quantity,\n }),\n }\n\n const data = {\n currency,\n value,\n items: [item],\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function refund(eventData: RefundData) {\n const eventName = 'refund'\n\n const { currency } = eventData\n\n const {\n tax,\n shipping,\n value,\n transactionId,\n items: orderItems,\n } = eventData.order\n\n const items = getPurchaseItems(orderItems)\n\n const data = {\n transaction_id: transactionId,\n value,\n tax,\n shipping,\n items,\n currency,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function login(eventData: LoginData) {\n const eventName = 'login'\n\n const { method } = eventData\n\n const data = {\n method,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function signUp(eventData: SignUpData) {\n const eventName = 'sign_up'\n\n const { method } = eventData\n\n const data = {\n method,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function search(eventData: SearchData) {\n const eventName = 'search'\n\n const { term } = eventData\n\n const data = {\n search_term: term,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\nexport function share(eventData: ShareData) {\n const eventName = 'share'\n\n const { method, contentType, itemId } = eventData\n\n const data = {\n method,\n content_type: contentType,\n item_id: itemId,\n }\n\n updateEcommerce(eventName, { ecommerce: data })\n}\n\n```"
}
] |
code_speedy-gtm_af968f76
|
[
{
"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 speedy-gtm/react/modules/customDimensions.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ProductViewData, ProductViewReferenceId } from '../typings/events'\n\ntype CustomDimensionSkuAvailability = 'available' | 'unavailable'\n\ninterface CustomDimensions {\n /** Product reference */\n dimension1: string\n /** SKU reference */\n dimension2: string\n /** SKU name */\n dimension3: string\n /** SKU availability */\n dimension4: CustomDimensionSkuAvailability\n}\n\ninterface CustomDimensionParams {\n productReference?: string\n skuReference?: string\n skuName?: string\n quantity: number\n}\n\nexport function customDimensions(\n params: CustomDimensionParams\n): CustomDimensions {\n return {\n dimension1: params.productReference ?? '',\n dimension2: params.skuReference ?? '',\n dimension3: params.skuName ?? '',\n dimension4: customDimensionSkuAvailability(params.quantity),\n }\n}\n\nexport function customDimensionSkuAvailability(\n quantity: number\n): CustomDimensionSkuAvailability {\n return quantity ? 'available' : 'unavailable'\n}\n\nexport function productViewSkuReference(\n product: ProductViewData['product']\n): string {\n const defaultReference = { Value: '' }\n\n // The `vtex:productView` is the only event where the\n // `product.selectedSku.referenceId` is different between its type and actual\n // data. Type `Item` (for `selectedSku`) specifies `referenceId` as a single\n // `{ Key: string; Value: string }` object type. However, in this event,\n // `referenceId` comes as an array of that object.\n //\n // This type conversion is needed because vtex.store does not normalize the\n // SKU Reference ID. Doing that there could possibly break some apps or\n // stores, so it's better doing it here.\n const skuReferenceId = (\n ((product.selectedSku\n .referenceId as unknown) as ProductViewReferenceId)?.[0] ??\n defaultReference\n ).Value\n\n return skuReferenceId ?? ''\n}\n\n```"
}
] |
code_speedy-gtm_4d000500
|
[
{
"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 speedy-gtm/react/modules/utils/shouldSendGA4Events.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport default function shouldSendGA4Events() {\n return Boolean(window?.__gtm__?.sendGA4Events)\n}\n\n```"
}
] |
code_speedy-gtm_f2dc8495
|
[
{
"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 speedy-gtm/react/modules/analytics/utils.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n// Almost all of the logic of expiration and campaign invalidation is based on this official GA article https://support.google.com/analytics/answer/2731565\n\nexport interface AnalyticsData {\n location: string\n referrer: string\n expires: number\n}\n\nexport interface AnalyticsDataWithOrigin extends AnalyticsData {\n origin: 'storage' | 'fresh'\n}\n\nexport const UTM_SOURCE_PARAM = 'utm_source'\nexport const UTM_MEDIUM_PARAM = 'utm_medium'\n\n// All of these parameters trigger a new session storage of the url\n// This list was inspired by Simo Ahava's list used on his cookie implementation of this feature\n// https://www.simoahava.com/analytics/persist-campaign-data-landing-page/#setup-the-persist-campaign-data-tag\nexport const analyticsURLParams = [\n UTM_SOURCE_PARAM,\n UTM_MEDIUM_PARAM,\n 'utm_campaign',\n 'gclid',\n 'utm_term',\n 'utm_content',\n 'utm_id',\n] as const\n\nexport function shouldInvalidateCurrentCampaign(\n location: Location,\n referrer: string,\n storageReferrer: string\n) {\n const referrerURL = referrer ? new URL(referrer) : null\n\n // if user comes from a referring website\n if (\n referrerURL &&\n referrer !== storageReferrer &&\n referrerURL.host !== location.host\n ) {\n return true\n }\n\n // the slice removes the initial \"?\" character\n const individualLocationParams = location.search.slice(1).split('&')\n\n return individualLocationParams.some(locationParam => {\n return analyticsURLParams.some(campaignParam =>\n locationParam.startsWith(`${campaignParam}=`)\n )\n })\n}\n\nconst STORAGE_KEY_ANALYTICS_DATA = 'analytics:session'\n\nexport function getAnalyticsFromStorage(): AnalyticsData | null {\n let analyticsData = null\n\n try {\n const rawAnalyticsData = window.localStorage.getItem(\n STORAGE_KEY_ANALYTICS_DATA\n )\n\n analyticsData = rawAnalyticsData ? JSON.parse(rawAnalyticsData) : null\n } catch (e) {\n console.error(\n 'Error while fetching original browser location from localStorage storage'\n )\n }\n\n return analyticsData\n}\n\nexport async function saveAnalyticsOnStorage(analyticsData: AnalyticsData) {\n try {\n window.localStorage.setItem(\n STORAGE_KEY_ANALYTICS_DATA,\n JSON.stringify(analyticsData)\n )\n } catch (e) {\n console.error(\n 'Error while saving original browser location on localStorage storage'\n )\n }\n}\n\nexport function currentDateInSeconds() {\n return Math.floor(Date.now() / 1000)\n}\n\nexport const THIRTY_MIN_IN_SECONDS = 30 * 60\n\nexport function isStorageExpired(expiresIn: number, now: number) {\n return now - expiresIn > 0\n}\n\nexport function renewExpirationDate() {\n return currentDateInSeconds() + THIRTY_MIN_IN_SECONDS\n}\n\n```"
}
] |
code_speedy-gtm_f8778de0
|
[
{
"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 speedy-gtm/react/modules/analytics/index.ts from the speedy-gtm VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n AnalyticsData,\n AnalyticsDataWithOrigin,\n currentDateInSeconds,\n getAnalyticsFromStorage,\n isStorageExpired,\n renewExpirationDate,\n saveAnalyticsOnStorage,\n shouldInvalidateCurrentCampaign,\n} from './utils'\n\nexport function createOrGetAnalyticsData(): AnalyticsDataWithOrigin {\n let analyticsData = getAnalyticsData()\n let origin: AnalyticsDataWithOrigin['origin'] = 'storage'\n\n if (!analyticsData) {\n analyticsData = createAnalyticsData()\n origin = 'fresh'\n }\n\n saveAnalyticsOnStorage(analyticsData)\n\n return { ...analyticsData, origin }\n}\n\nfunction getAnalyticsData(): AnalyticsData | null {\n const analyticsFromStorage = getAnalyticsFromStorage()\n\n if (\n !analyticsFromStorage ||\n isStorageExpired(analyticsFromStorage.expires, currentDateInSeconds()) ||\n shouldInvalidateCurrentCampaign(\n window.location,\n document.referrer,\n analyticsFromStorage.referrer\n )\n ) {\n return null\n }\n\n return {\n ...analyticsFromStorage,\n expires: renewExpirationDate(),\n }\n}\n\nfunction createAnalyticsData(): AnalyticsData {\n return {\n location: window.location.href,\n referrer: document.referrer,\n expires: renewExpirationDate(),\n }\n}\n\n```"
}
] |
code_training-week-demo_80be8afd
|
[
{
"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 training-week-demo/admin-app/README.md from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Admin App\n\n## Objetivo\n\nDesenvolver componente com experiência parecida ao apresentado na Demo. O app deve expor uma rota no Admin que possua um botão de upload que abre um modal com uma área de input de arquivo. Ao receber um arquivo CSV com o formato que você determinar, ele deve fechar o modal e popular uma tabela com os dados. O App deve possuir tratamentos para formatos inesperados, tanto de arquivo quanto para colunas no CSV. O App deve possuir uma funcionalidade adicional de popular a tabela com dados do Master Data, da entidade CL.\n\n## Etapas\n\n- [ ] Linkar o `admin-app`;\n- [ ] Adicionar o app `vtex.styleguide` nas dependências;\n- [ ] Alterar a `section` em `navigate.json` para `customer`;\n- [ ] Alterar a rota do App para `/admin/training-week/users` em `navigation.json`;\n- [ ] Alterar a rota do App para `/admin/app/training-week/users` em `routes.json`;\n- [ ] Adicionar lógica de abertura do `Modal` com base no clique do botão;\n- [ ] Adicionar mensagem informando o tipo de arquivo aceito no `Dropzone` e outras instruções;\n- [ ] Adicionar `handlers` de upload de arquivo (`onDropAccepted`) e cancelamento (`onDropReject`) no `Dropzone`;\n- [ ] Adicionar botão que iniciar o processo de população da tabela, isto é, transforme o arquivo CSV em um array de objetos. Para esta transformação, podemos utilizar uma lib como por exemplo [csvtojson](https://www.npmjs.com/package/csvtojson) (não é o melhor, mas é simples o suficiente para a tarefa). Não esqueça de rodar a instalação do pacote na pasta correta (`react`);\n- [ ] Implementar `Table`;\n- [ ] Popular tabela com dados anteriores;\n- [ ] Implementar alertas ao usuário para erros de operação (arquivo inválido, erros desconhecidos, etc);\n- [ ] Alterar as `labels` das mensagens em `messages/pt.json` (deve ter notado que elas estão bem estranhas);\n- [ ] Implementar query para requisição de dados da entidade CL. Dica: o app que implementa é o `vtex.store-graphql`;\n- [ ] Adicionar botão que efetua a query e popula a tabela. Dica: lembrar do `useQuery` e `useLazyQuery`;\n\n## Links úteis\n\n- https://github.com/vtex-apps/admin-example#readme\n- https://styleguide.vtex.com/\n- https://github.com/vtex-apps/render-runtime#readme\n- https://learn.vtex.com/docs/course-admin-lang-en\n- https://www.apollographql.com/docs/react/data/queries/#executing-a-query\n- https://www.apollographql.com/docs/react/data/queries/#manual-execution-with-uselazyquery\n- https://tachyons.io/docs/\n\n```"
}
] |
code_training-week-demo_f12fa56b
|
[
{
"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 training-week-demo/admin-app/package.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"admin-example\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"lint\": \"eslint --ext js,jsx,ts,tsx .\",\n \"format\": \"prettier --write \\\"**/*.{ts,tsx,js,jsx,json}\\\"\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"lint-staged\": {\n \"*.{ts,js,tsx,jsx}\": [\n \"eslint --fix\",\n \"prettier --write\"\n ],\n \"*.{json,graphql,gql}\": [\n \"prettier --write\"\n ]\n },\n \"devDependencies\": {\n \"@types/node\": \"^12.12.21\",\n \"@vtex/prettier-config\": \"^0.2.0\",\n \"eslint\": \"^6.8.0\",\n \"eslint-config-vtex\": \"^12.4.0\",\n \"eslint-config-vtex-react\": \"^6.4.0\",\n \"husky\": \"^4.2.5\",\n \"lint-staged\": \"^10.2.2\",\n \"prettier\": \"^2.0.5\",\n \"typescript\": \"^3.8.3\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.131.0/public/@types/vtex.render-runtime\"\n },\n \"dependencies\": {\n \"react-apollo\": \"^3.1.5\"\n }\n}\n\n```"
}
] |
code_training-week-demo_7b676d2d
|
[
{
"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 training-week-demo/admin-app/manifest.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"admin-app\",\n \"vendor\": \"trainingweekdev21\",\n \"version\": \"0.1.0\",\n \"title\": \"Example Admin App\",\n \"description\": \"\",\n \"mustUpdateAt\": \"2022-08-28\",\n \"scripts\": {\n \"postreleasy\": \"vtex publish\"\n },\n \"dependencies\": {\n\n },\n \"builders\": {\n \"react\": \"3.x\",\n \"admin\": \"0.x\",\n \"messages\": \"1.x\"\n },\n \"policies\": [\n {\n \"name\": \"outbound-access\",\n \"attrs\": {\n \"host\": \"portal.vtexcommercestable.com.br\",\n \"path\": \"/api/license-manager/*\"\n }\n }\n ],\n \"$schema\": \"https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema\"\n}\n\n```"
}
] |
code_training-week-demo_7abea6a6
|
[
{
"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 training-week-demo/store-theme/manifest.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"vendor\": \"trainingweekdev21\",\n \"name\": \"store-theme\",\n \"version\": \"4.4.2\",\n \"builders\": {\n \"styles\": \"2.x\",\n \"store\": \"0.x\",\n \"docs\": \"0.x\"\n },\n \"mustUpdateAt\": \"2018-09-05\",\n \"scripts\": {\n \"postreleasy\": \"vtex publish --verbose\"\n },\n \"dependencies\": {\n \"vtex.store\": \"2.x\",\n \"vtex.store-header\": \"2.x\",\n \"vtex.product-summary\": \"2.x\",\n \"vtex.store-footer\": \"2.x\",\n \"vtex.store-components\": \"3.x\",\n \"vtex.styleguide\": \"9.x\",\n \"vtex.slider\": \"0.x\",\n \"vtex.carousel\": \"2.x\",\n \"vtex.shelf\": \"1.x\",\n \"vtex.menu\": \"2.x\",\n \"vtex.minicart\": \"2.x\",\n \"vtex.product-details\": \"1.x\",\n \"vtex.product-kit\": \"1.x\",\n \"vtex.search-result\": \"3.x\",\n \"vtex.login\": \"2.x\",\n \"vtex.my-account\": \"1.x\",\n \"vtex.flex-layout\": \"0.x\",\n \"vtex.rich-text\": \"0.x\",\n \"vtex.store-drawer\": \"0.x\",\n \"vtex.locale-switcher\": \"0.x\",\n \"vtex.product-quantity\": \"1.x\",\n \"vtex.product-identifier\": \"0.x\",\n \"vtex.breadcrumb\": \"1.x\",\n \"vtex.sticky-layout\": \"0.x\",\n \"vtex.product-customizer\": \"2.x\",\n \"vtex.stack-layout\": \"0.x\",\n \"vtex.product-specification-badges\": \"0.x\",\n \"vtex.product-review-interfaces\": \"1.x\",\n \"vtex.telemarketing\": \"2.x\",\n \"vtex.order-placed\": \"2.x\",\n \"vtex.checkout-summary\": \"0.x\",\n \"vtex.product-list\": \"0.x\",\n \"vtex.add-to-cart-button\": \"0.x\",\n \"vtex.product-bookmark-interfaces\": \"1.x\",\n \"vtex.responsive-layout\": \"0.x\",\n \"vtex.slider-layout\": \"0.x\",\n \"vtex.store-image\": \"0.x\",\n \"vtex.store-icons\": \"0.x\",\n \"vtex.modal-layout\": \"0.x\",\n \"vtex.store-link\": \"0.x\",\n \"vtex.store-video\": \"1.x\",\n \"vtex.product-gifts\": \"0.x\",\n \"vtex.product-price\": \"1.x\",\n \"vtex.disclosure-layout\": \"1.x\",\n \"vtex.store-form\": \"0.x\",\n \"vtex.product-highlights\": \"2.x\",\n \"vtex.product-specifications\": \"1.x\",\n \"vtex.tab-layout\": \"0.x\",\n \"vtex.condition-layout\": \"2.x\",\n \"vtex.css-handles\": \"1.x\"\n },\n \"peerDependencies\": {\n \"vtex.reviews-and-ratings\": \"2.x\"\n },\n \"$schema\": \"https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema\"\n}\n\n```"
}
] |
code_training-week-demo_758aa171
|
[
{
"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 training-week-demo/storefront-app/dangerfile.js from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n// dangerfile.js\nconst { verify } = require('@vtex/danger')\n\nconst config = {\n // Set to true to enforce keepachangelog rules.\n keepachangelog: {\n changeVersion: false,\n },\n rules: {\n description: ['fail', { minLength: 20 }],\n assignee: 'fail',\n reviewers: 'fail',\n pr_size: ['warn', { additionLimit: 800, deletionLimit: -1 }],\n lock_file: 'warn',\n no_ignored_test: ['fail', { pattern: /test|spec/i }],\n no_debugger: ['fail', { pattern: /\\.[tj]sx?$/i }],\n enforce_graphql_provider: 'off',\n },\n}\n\nverify(config)\n\n```"
}
] |
code_training-week-demo_05476d75
|
[
{
"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 training-week-demo/storefront-app/README.md from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Storefront App\n\n## Objetivo\n\nReplicar os componentes apresentados na Demo: `product-draw` e `drawn-badge`. O componente `product-draw` deve receber uma lista de IDs de produto via `props` ou Site Editor e, ao clicar em um botão, sortear um produto e apresentar pelo menos o nome e imagem do produto, que ao clicar, redireciona para a página de produto do mesmo. O `drawn-badge` deve aparecer na página do último produto sorteado somente, para os demais não deve aparecer.\n\n## Etapas\n\n- [ ] Linkar o `storefront-app` e em seguida o `store-theme`;\n- [ ] Adicionar o app `trainingweekdev21.storefront-app` como dependência no `store-theme`. Somente haverá essa manipulação no `manifest` da `store-theme`, as demais serão no `storefront-app`;\n- [ ] Posicionar o componente `product-draw` no bloco `store.home`\n- [ ] Criar query GraphQL para requisição de produtos via `productId`. Utilize o GraphiQL IDE;\n- [ ] Adicionar o app `vtex.search-graphql` nas dependências;\n- [ ] Implementar componente React. Não esqueça de adicionar as dependências no `manifest.json` caso utilize `vtex.render-runtime`, `vtex.store-image`, entre outros (use sua imaginação);\n- [ ] Implementar lógica de sorteio de `productId` dado uma lista;\n- [ ] Usar o `useQuery` ou o `useLazyQuery` para executar a query criada, utilizando como variável o `productId` sorteado;\n- [ ] Adicionar `prop` para receber a lista de produtos via `blocks` e preenchê-la via `blocks`;\n- [ ] Adicionar interface Site Editor para o input de `props`;\n- [ ] Persistir o `productId` sorteado. Sugerimos o `localStorage`, dica: ele só existe no `client-side`;\n- [ ] Posicionar o componente `product-draw` no block `store.product`;\n- [ ] Implementar componente React;\n- [ ] Adicionar o app `vtex.product-context` como dependência e utilizar o hook `useProduct` para capturar os dados do produto da página;\n- [ ] Adicionar lógica de exibição do componente caso seja o último produto sorteado;\n\n## Links úteis\n\n- https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-3-creating-the-new-app\n- https://github.com/vtex-apps/render-runtime#readme\n- https://github.com/vtex-apps/store-image#readme\n- https://www.apollographql.com/docs/react/data/queries/#executing-a-query\n- https://www.apollographql.com/docs/react/data/queries/#manual-execution-with-uselazyquery\n- https://github.com/vtex-apps/product-context#product-context\n- https://tachyons.io/docs/\n\n```"
}
] |
code_training-week-demo_55388de3
|
[
{
"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 training-week-demo/storefront-app/package.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"CHANGE_ME\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"lint\": \"eslint --ext js,jsx,ts,tsx .\",\n \"format\": \"prettier --write \\\"**/*.{ts,tsx,js,jsx,json}\\\"\",\n \"lint:locales\": \"intl-equalizer\",\n \"test\": \"cd ./react && yarn test\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"lint-staged\": {\n \"*.{ts,js,tsx,jsx}\": [\n \"eslint --fix\",\n \"prettier --write\"\n ],\n \"*.{json,graphql,gql}\": [\n \"prettier --write\"\n ],\n \"*.json\": [\n \"prettier --write\"\n ],\n \"messages/*.json\": [\n \"yarn lint:locales\"\n ]\n },\n \"devDependencies\": {\n \"@vtex/intl-equalizer\": \"^2.5.0\",\n \"@vtex/prettier-config\": \"^0.3.5\",\n \"eslint\": \"^7.14.0\",\n \"eslint-config-vtex\": \"^12.8.11\",\n \"eslint-config-vtex-react\": \"^6.8.3\",\n \"husky\": \"^4.3.0\",\n \"lint-staged\": \"^10.5.1\",\n \"prettier\": \"^2.2.0\",\n \"typescript\": \"^3.9.6\",\n \"@vtex/danger\": \"^0.2.7\"\n },\n \"version\": \"0.0.0\",\n \"intl-equalizer\": {\n \"referenceLocale\": \"en\",\n \"localeDirectory\": \"messages\"\n }\n}\n```"
}
] |
code_training-week-demo_e9dc5094
|
[
{
"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 training-week-demo/storefront-app/manifest.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"vendor\": \"trainingweekdev21\",\n \"name\": \"storefront-app\",\n \"version\": \"0.1.0\",\n \"title\": \"Taining week component\",\n \"description\": \"Training week component example\",\n \"builders\": {\n \"react\": \"3.x\",\n \"store\": \"0.x\",\n \"messages\": \"1.x\"\n },\n \"dependencies\": {\n\n },\n \"registries\": [\n \"smartcheckout\"\n ],\n \"policies\": [],\n \"$schema\": \"https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema\"\n}\n\n```"
}
] |
code_training-week-demo_fddc8b2e
|
[
{
"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 training-week-demo/service-app/dangerfile.js from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n// dangerfile.js\nconst { verify } = require('@vtex/danger')\n\nconst config = {\n // Set to true to enforce keepachangelog rules.\n keepachangelog: {\n changeVersion: false,\n },\n rules: {\n description: ['fail', { minLength: 20 }],\n assignee: 'fail',\n reviewers: 'fail',\n pr_size: ['warn', { additionLimit: 800, deletionLimit: -1 }],\n lock_file: 'warn',\n no_ignored_test: ['fail', { pattern: /test|spec/i }],\n no_debugger: ['fail', { pattern: /\\.[tj]sx?$/i }],\n enforce_graphql_provider: 'off',\n },\n}\n\nverify(config)\n\n```"
}
] |
code_training-week-demo_d3d06b6f
|
[
{
"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 training-week-demo/service-app/README.md from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Service App\n\n## Objetivo\n\nReplicar as rotas e queries apresentadas na Demo. O app deve possuir duas rotas: `/_v/jsonplaceholder/users` e `/_v/jsonplaceholder/users/:userId`. A primeira deve responder para os métodos `GET`, que responde como um proxy para `https://jsonplaceholder.typicode.com/users/`, e `POST`, que deve receber um `body` e subir um erro caso não seja um `JSON` com a propriedade `id`. Para as queries, devem existir pelo menos duas: uma para os `users` da API do `jsonplaceholder` e outra para os clientes da entidade CL do Master Data;\n\n## Etapas\n\n- [ ] Linkar o `storefront-service`;\n- [ ] Adicionar a rota `/_v/jsonplaceholder/users` no arquivo `service.json`;\n- [ ] No objeto `export default` do arquivo `node/index.ts`, adicionar a rota anterior dentro de `routes`;\n- [ ] Criar middleware para `GET` na rota anterior e configurá-lo no mesmo lugar mencionado anteriormente;\n- [ ] Implementar o `client` para o JsonPlaceholder e adicioná-lo no arquivo `node/clients/index.ts`;\n- [ ] Adicionar policy de `outbound-access` no `manifest` para o host `jsonplaceholder.typicode.com` e path `/*`;\n- [ ] Aprimorar middleware anterior para consumir o `client` implementado;\n- [ ] Implementar middleware para `POST` na rota anterior, com a lógica de encontrar o `user` para o `userId` passado;\n- [ ] Adicionar os `schemas` das queries e typagem no arquivo `graphql/schema.graphql`;\n- [ ] Adicionar configuração das queries no objeto `export default` do arquivo `node/index.ts` dentro da propriedade `graphql` > `resolvers`;\n- [ ] Implementar resolver para a query;\n- [ ] Implementar `client` para o Master Data utilizando o `ExternalClient`;\n- [ ] Adicionar policy de `outbound-access` no `manifest` para o host `{{account}}.vtexcommercestable.com.br` e path `/*`;\n- [ ] Adicionar policy de `POWER_USER_DS` no `manifest` para permitir nosso `client` utilizar o `authToken` para chamadas ao Master Data;\n- [ ] Implementar resolver para a query, utilizando o `client` anterior;\n\n## Links úteis\n\n- https://developers.vtex.com/vtex-developer-docs/docs/how-to-use-and-create-clients-on-vtex-io\n- https://github.com/vtex-apps/service-example#readme\n- https://github.com/vtex-apps/graphql-example#readme\n- https://developers.vtex.com/vtex-rest-api/reference/master-data-api-v1-overview\n- https://koajs.com/\n\n```"
}
] |
code_training-week-demo_59acd18c
|
[
{
"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 training-week-demo/service-app/package.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"CHANGE_ME\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"lint\": \"eslint --ext js,jsx,ts,tsx .\",\n \"format\": \"prettier --write \\\"**/*.{ts,tsx,js,jsx,json}\\\"\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"lint-staged\": {\n \"*.{ts,js,tsx,jsx}\": [\n \"eslint --fix\",\n \"prettier --write\"\n ],\n \"*.{json,graphql,gql}\": [\n \"prettier --write\"\n ]\n },\n \"devDependencies\": {\n \"@types/node\": \"^12.12.21\",\n \"@vtex/danger\": \"^0.2.7\",\n \"@vtex/prettier-config\": \"^0.3.1\",\n \"eslint\": \"^6.8.0\",\n \"eslint-config-vtex\": \"^12.7.0\",\n \"husky\": \"^4.2.0\",\n \"lint-staged\": \"^10.0.2\",\n \"prettier\": \"^2.0.5\",\n \"typescript\": \"^3.9.6\"\n }\n}\n\n```"
}
] |
code_training-week-demo_5f74dd46
|
[
{
"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 training-week-demo/service-app/manifest.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"service-app\",\n \"vendor\": \"trainingweekdev21\",\n \"version\": \"0.1.0\",\n \"title\": \"GraphQL Example\",\n \"description\": \"Reference app for VTEX IO GraphQL Services\",\n \"mustUpdateAt\": \"2022-01-04\",\n \"categories\": [],\n \"dependencies\": {},\n \"builders\": {\n \"docs\": \"0.x\",\n \"graphql\": \"1.x\",\n \"node\": \"6.x\"\n },\n \"scripts\": {\n \"prereleasy\": \"bash lint.sh\"\n },\n \"credentialType\": \"absolute\",\n \"policies\": [\n {\n \"name\": \"colossus-fire-event\"\n },\n {\n \"name\": \"colossus-write-logs\"\n },\n {\n \"name\": \"graphql-query\"\n },\n {\n \"name\": \"outbound-access\",\n \"attrs\": {\n \"host\": \"api.vtex.com\",\n \"path\": \"/dataentities/*\"\n }\n }\n ],\n \"$schema\": \"https://raw.githubusercontent.com/vtex/node-vtex-api/master/gen/manifest.schema\"\n}\n\n```"
}
] |
code_training-week-demo_13fe171f
|
[
{
"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 training-week-demo/admin-app/messages/pt.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin-trainingweek.navigation.label-group\": \"I'm not right\",\n \"admin-trainingweek.navigation.label-users\": \"Me neither\",\n \"admin-trainingweek.navigation.search.kws\": \"teste, mock, fake\",\n \"admin-trainingweek.navigation.details.search.kws\": \"detalhe, mock, test, oi\",\n \"admin-trainingweek.navigation.table.search.kws\": \"tabela, mock, test, tchau\",\n \"admin-trainingweek.users-title\": \"I think I'm not right too\"\n}\n\n```"
}
] |
code_training-week-demo_bdbbc16e
|
[
{
"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 training-week-demo/admin-app/admin/navigation.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"section\": \"order\",\n \"titleId\": \"admin-trainingweek.navigation.label-group\",\n \"searchKeyWordsHelpers\": \"admin-trainingweek.navigation.search.kws\",\n \"subSectionItems\": [\n {\n \"labelId\": \"admin-trainingweek.navigation.label-users\",\n \"path\": \"/admin/change-me/\",\n \"searchKeyWordsHelpers\": \"admin-trainingweek.navigation.table.search.kws\"\n }\n ]\n}\n\n```"
}
] |
code_training-week-demo_5a484bff
|
[
{
"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 training-week-demo/admin-app/admin/routes.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin.app.users\": {\n \"component\": \"UsersContainer\",\n \"path\": \"/admin/app/change-me\"\n }\n}\n\n```"
}
] |
code_training-week-demo_e25e3ad9
|
[
{
"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 training-week-demo/admin-app/react/package.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.admin-example\",\n \"version\": \"0.0.12\",\n \"devDependencies\": {\n \"@types/node\": \"^11.12.1\",\n \"@types/react\": \"^16.8.10\",\n \"@types/react-intl\": \"^2.3.17\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-client\": \"^2.4.7\",\n \"graphql\": \"^14.0.2\",\n \"prop-types\": \"^15.7.2\",\n \"react\": \"^16.8.6\",\n \"react-dom\": \"^16.8.6\",\n \"react-intl\": \"^2.7.2\",\n \"trainingweekdev21.admin-app\": \"https://brunomoreira--trainingweekdev21.myvtex.com/_v/private/typings/linked/v1/trainingweekdev21.admin-app@0.1.0+build1632880086/public/@types/trainingweekdev21.admin-app\",\n \"typescript\": \"3.9.7\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.1/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.0/public/@types/vtex.styleguide\"\n },\n \"dependencies\": {\n \"@types/faker\": \"^4.1.5\",\n \"faker\": \"^4.1.0\"\n }\n}\n\n```"
}
] |
code_training-week-demo_cd1d459f
|
[
{
"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 training-week-demo/admin-app/react/styles.global.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\nhtml,\nbody,\n#render-container,\n#render-provider,\n.render-container,\n.render-provider {\n height: 100%;\n}\n\n```"
}
] |
code_training-week-demo_248f0af7
|
[
{
"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 training-week-demo/admin-app/react/UsersContainer.tsx from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { Layout, PageBlock, PageHeader } from 'vtex.styleguide'\nimport UsersPage from './pages/UsersPage'\n\nimport './styles.global.css'\n\nconst UsersContainer: FC = () => {\n return (\n <Layout\n pageHeader={\n <PageHeader\n title={<FormattedMessage id=\"admin-trainingweek.users-title\" />}\n />\n }\n >\n <PageBlock variation=\"full\">\n <UsersPage />\n </PageBlock>\n </Layout>\n )\n}\n\nexport default UsersContainer\n\n```"
}
] |
code_training-week-demo_53a9c08a
|
[
{
"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 training-week-demo/admin-app/react/graphql/crazyQuery.graphql from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation MyCrazyQuery($someVariable: String) {\n aQuery(prop: $someVariable)\n}\n\n```"
}
] |
code_training-week-demo_2aae2a5e
|
[
{
"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 training-week-demo/admin-app/react/pages/UsersPage.tsx from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState } from 'react'\nimport { Button, /** IconUpload, */ Modal, Dropzone, /** Table */ } from 'vtex.styleguide'\n// import csv from 'csvtojson'\n// import { useQuery, useMutation } from 'react-apollo'\n\nconst UsersPage = () => {\n const [isModalOpen, /** setModalOpen */] = useState(false)\n\n return (\n <>\n <Modal centered isOpen={isModalOpen} onClose={() => alert('close')}>\n <div className=\"flex flex-column dark-gray\">\n <Dropzone\n onDropAccepted={() => alert('accepted')}\n onDropReject={() => alert('rejected')}\n isLoading={false}\n ></Dropzone>\n </div>\n </Modal>\n <div className=\"flex justify-center\">\n <div className=\"mb4\">\n <Button variation=\"primary\" onClick={() => alert('clicked')}></Button>\n </div>\n </div>\n </>\n )\n}\n\nexport default UsersPage\n\n```"
}
] |
code_training-week-demo_2e610547
|
[
{
"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 training-week-demo/store-theme/docs/README.md from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Store theme\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\nOur boilerplate theme to create stores in the VTEX IO platform.\n\n## Preview\n\n\n## Tutorial\nTo understand how things work check our tutorial [Build a store using VTEX IO](https://vtex.io/docs/getting-started/build-stores-with-store-framework/1/)\n\n## Dependencies\nAll store components that you see on this document are open source too. Production ready, you can found those apps in this GitHub organization.\n\nStore framework is the baseline to create any store using _VTEX IO Web Framework_.\n- [Store](https://github.com/vtex-apps/store/blob/master/README.md)\n\nStore GraphQL is a middleware to access all VTEX APIs.\n- [Store GraphQL](https://github.com/vtex-apps/store-graphql/blob/master/docs/README.md)\n\n### Store Component Apps\n- [Header](https://github.com/vtex-apps/store-header/blob/master/docs/README.md)\n- [Footer](https://github.com/vtex-apps/store-footer/blob/master/docs/README.md)\n- [Slider Layout](https://github.com/vtex-apps/slider-layout/blob/master/docs/README.md)\n- [Shelf](https://github.com/vtex-apps/shelf/blob/master/docs/README.md)\n- [Telemarketing](https://github.com/vtex-apps/telemarketing/blob/master/docs/README.md)\n- [Menu](https://github.com/vtex-apps/menu/blob/master/docs/README.md)\n- [Login](https://github.com/vtex-apps/login/blob/master/docs/README.md)\n- [Minicart](https://github.com/vtex-apps/minicart/blob/master/docs/README.md)\n- [Category Menu](https://github.com/vtex-apps/category-menu/blob/master/docs/README.md)\n- [Product Summary](https://github.com/vtex-apps/product-summary/blob/master/docs/README.md)\n- [Breadcrumb](https://github.com/vtex-apps/breadcrumb/blob/master/docs/README.md)\n- [Search Result](https://github.com/vtex-apps/search-result/blob/master/docs/README.md)\n- [Product Details](https://github.com/vtex-apps/product-details/blob/master/docs/README.md)\n- [Store Components](https://github.com/vtex-apps/store-components/blob/master/docs/README.md)\n- [Order Placed](https://github.com/vtex-apps/order-placed/blob/master/docs/README.md) \n\n### Store Pixel Apps\n\n - [Facebook Pixel](https://github.com/vtex-apps/facebook-pixel/blob/master/docs/README.md)\n - [Google Tag Manager](https://github.com/vtex-apps/google-tag-manager/blob/master/docs/README.md)\n\n## Contributing\n\nCheck it out [how to contribute](https://github.com/vtex-apps/awesome-io#contributing) with this project.\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<table>\n <tr>\n <td align=\"center\"><a href=\"http://www.hugoccosta.com\"><img src=\"https://avatars2.githubusercontent.com/u/20212776?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Hugo Costa</b></sub></a><br /><a href=\"https://github.com/vtex-apps/store-theme/commits?author=hugocostadev\" title=\"Documentation\">📖</a></td>\n </tr>\n</table>\n\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\n```"
}
] |
code_training-week-demo_8adec6e5
|
[
{
"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 training-week-demo/store-theme/docs/contact-schema.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"title\": \"Contact\",\n \"type\": \"object\",\n \"properties\": {\n \"title\": {\n \"type\": \"string\",\n \"title\": \"Title\"\n },\n \"name\": {\n \"type\": \"string\",\n \"title\": \"Name\"\n },\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"title\": \"Email address\"\n },\n \"message\": {\n \"type\": \"string\",\n \"title\": \"Message\"\n }\n },\n \"required\": [\"email\", \"message\"],\n \"v-security\": {\n \"publicJsonSchema\": true\n }\n}\n\n```"
}
] |
code_training-week-demo_3afd7d57
|
[
{
"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 training-week-demo/store-theme/store/blocks.jsonc from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n/* Blocks can be defined both on the store/blocks.json file, and in any number of json\n * files inside the store/blocks directory, with any arbitrary directory structure.\n *\n * Additionally, all blocks files can support comments, such as this one, if given the\n * .jsonc file extension.\n *\n * The store/blocks.json file is intended for backwards compatibility, for miscellaneous\n * blocks, or if the app is simple enough that it doesn't warrant splitting the file.\n */\n{\n \"store.orderplaced\": {\n \"blocks\": [\"order-placed\"]\n },\n\n \"store.account\": {\n \"blocks\": [\"my-account\"],\n \"parent\": {\n \"challenge\": \"challenge.profile\"\n }\n },\n\n \"store.login\": {\n \"blocks\": [\"login-content#default\"]\n },\n\n \"login-content#default\": {\n \"props\": {\n \"isInitialScreenOptionOnly\": false,\n \"defaultOption\": 1,\n \"showPasswordVerificationIntoTooltip\": true\n }\n },\n\n \"store.product-review-form\": {\n \"blocks\": [\"product-review-form\"]\n },\n\n \"store.not-found#product\": {\n \"blocks\": [\"rich-text#not-found\"]\n },\n\n \"store.not-found#search\": {\n \"blocks\": [\"rich-text#not-found\"]\n },\n\n \"rich-text#not-found\": {\n \"props\": {\n \"textAlignment\": \"CENTER\",\n \"textPosition\": \"CENTER\",\n \"text\": \"**PAGE NOT FOUND**\",\n \"font\": \"t-heading-1\"\n }\n }\n}\n\n```"
}
] |
code_training-week-demo_c1abc288
|
[
{
"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 training-week-demo/store-theme/store/routes.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.custom#about-us\": {\n \"path\": \"/about-us\"\n },\n \"store.custom#faq\": {\n \"path\": \"/faq\"\n },\n \"store.custom#contact-us\": {\n \"path\": \"/contact-us\"\n }\n}\n\n```"
}
] |
code_training-week-demo_f9a409a2
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.store-video.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.videoContainer {\n width: 100%;\n height: 300px;\n margin-top: 2%;\n}\n\n@media only screen and (min-width: 640px) {\n .videoContainer {\n height: 700px;\n }\n}\n\n```"
}
] |
code_training-week-demo_7c094f85
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.product-price.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.listPrice {\n color: #727273;\n margin-bottom: .25rem;\n font-size: 1rem;\n}\n\n.sellingPrice {\n color: #3f3f40;\n font-size: 1.25rem;\n}\n\n.sellingPriceValue {\n font-size: 2.25rem;\n font-weight: 700;\n}\n\n.installments {\n color: #727273;\n margin-bottom: 1rem;\n}\n\n.savings {\n font-weight: 500;\n color: #79B03A;\n}\n\n.sellingPriceValue--summary {\n font-size: 1.25rem;\n font-weight: 600;\n color: #2E2E2E;\n}\n\n.savings--summary {\n background: #8BC34A;\n border-radius: 1000px;\n align-items: center;\n display: flex;\n\n padding-left: 0.5rem;\n padding-right: 0.5rem;\n font-size: 0.875rem;\n font-weight: 600;\n vertical-align: baseline;\n color: #FFFFFF;\n}\n\n.savings-discount--summary {\n font-size: 0.875rem;\n font-weight: 600;\n vertical-align: baseline;\n color: #FFFFFF;\n padding-left: 0.5rem;\n padding-right: 0.5rem;\n}\n\n.listPrice--summary {\n margin-bottom: 0.25rem;\n font-size: .875rem;\n}\n\n.installments--summary {\n margin-bottom: 2rem;\n font-size: 0.875rem;\n}\n\n.savings--summaryPercentage {\n background: #0f3e99;\n border-radius: 1000px;\n align-items: center;\n display: flex;\n}\n\n.savingsPercentage--summaryPercentage {\n font-size: 0.875rem;\n font-weight: 600;\n vertical-align: baseline;\n color: #FFFFFF;\n padding: 0.25rem 0.5rem 0.25rem 0.5rem;\n}\n\n```"
}
] |
code_training-week-demo_e583a804
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.rich-text.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.container--deals {\n color: #ffffff;\n text-align: center;\n justify-content: center;\n}\n\n.container--shelfTitle {\n color: #727273;\n justify-content: center;\n text-align: center;\n}\n\n.headingLevel2--shelfTitle {\n font-weight: 200;\n}\n\n.container--deals .paragraph {\n margin: 0;\n}\n\n.container--link {\n justify-content: center;\n}\n\n.container--question {\n justify-content: center;\n}\n\n.container--question .paragraph {\n text-align: center;\n max-width: 540px;\n margin: 0 16px;\n padding-top: 120px;\n color: #03034E;\n}\n\n.container--question .strong {\n font-size: 32px;\n line-height: 2rem;\n font-weight: 700;\n}\n\n.container--link .paragraph {\n text-align: center;\n max-width: 540px;\n padding-top: 36px;\n padding-bottom: 84px;\n color: #03034E;\n}\n\n.container--link .strong {\n font-size: 16px;\n font-weight: 700;\n text-transform: uppercase;\n}\n\n.container--link .link {\n text-decoration: none;\n font-size: 36px;\n font-weight: 300;\n color: #03034E;\n}\n\n.container--title {\n color: #03034E;\n font-size: 28px;\n font-weight: 700;\n}\n\n@media only screen and (min-width: 640px) {\n .container--question .strong {\n font-size: 40px;\n line-height: 3rem;\n }\n\n .container--about {\n max-width: 85%;\n }\n\n .container--title {\n color: #03034E;\n font-size: 40px;\n font-weight: 700;\n max-width: 60%;\n }\n\n .container--title .paragraph {\n line-height: 1.3em;\n }\n}\n\n```"
}
] |
code_training-week-demo_c1cd7b9b
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.product-summary.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.skuSelectorContainer--quickview .skuSelectorItemImage .frameAround, .skuSelectorContainer--quickview .skuSelectorItemImage .skuSelectorInternalBox {\n border-radius: 50%;\n}\n\n.container :global(.vtex-modal-layout-0-x-triggerContainer) {\n opacity: 0;\n transition: opacity 200ms ease-in-out;\n}\n\n.container:hover :global(.vtex-modal-layout-0-x-triggerContainer) {\n opacity: 1;\n}\n\n@media screen and (max-width: 40em) {\n .container :global(.vtex-modal-layout-0-x-triggerContainer) {\n display: none;\n }\n}\n\n.nameContainer {\n justify-content: start;\n padding-top: 1rem;\n padding-bottom: 1rem;\n}\n\n.brandName {\n font-weight: 600;\n font-size: 18px;\n color: #2E2E2E;\n}\n\n.container {\n text-align: start;\n}\n\n.imageContainer {\n text-align: center;\n}\n\n.image {\n border-radius: 0.25rem;\n}\n\n```"
}
] |
code_training-week-demo_8b172676
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.modal-layout.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n@media screen and (min-width: 40em) {\n .paper--quickview {\n height: 260px;\n width: 580px;\n }\n\n .actionsContainer--quickview {\n padding: 0 2rem 2rem 2rem;\n }\n}\n\n@media screen and (min-width: 50em) {\n .paper--quickview {\n height: 450px;\n width: 900px;\n }\n}\n\n\n@media screen and (min-width: 75em) {\n .paper--quickview {\n width: calc(100% - 4rem);\n height: auto;\n }\n}\n\n@media screen and (min-width: 82em) {\n .actionsContainer--quickview {\n padding: 0 2.5rem 2.5rem 2.5rem;\n }\n}\n\n.paper--quickview {\n min-width: 320px;\n max-width: 96rem;\n}\n\n.headerContainer--quickview {\n border: none;\n position: absolute;\n right: 0;\n}\n\n.actionsContainer--quickview {\n height: 100%;\n width: 100%;\n transition: box-shadow 150ms ease-in-out, border-top 150ms ease-in-out;\n border-top-style: solid;\n border-top-width: 1px;\n border-top-color: transparent;\n box-shadow: -4px 0px 27px -12px transparent;\n}\n\n.actionsContentWrapper {\n border-top-width: 1px;\n border-top-style: solid;\n border-top-color: #aaa;\n padding-top: 1.5rem;\n}\n\n.contentContainer--quickviewContent {\n padding: 2.5rem 0 2.5rem 2rem;\n overflow-x: hidden;\n}\n\n.triggerContainer--quickview {\n padding: .75rem;\n}\n\n.triggerContainer {\n outline: none;\n}\n\n.actionsContainer--quickview:not(.actionsContainerEndOfContent--quickview) {\n border-top-color: rgb(238, 238, 238);\n box-shadow: -4px 0px 27px -12px rgba(0,0,0,0.64);\n}\n\n.actionsContainer--quickview:not(.actionsContainerEndOfContent--quickview) .actionsContentWrapper {\n border-top-color: transparent;\n}\n\n.closeButton {\n padding-right: 1rem;\n}\n\n.paper--product-gifts {\n padding: 1.5rem;\n}\n\n```"
}
] |
code_training-week-demo_e672ef58
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.store-header.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/* add transitions */\n:global(.vtex-sticky-layout-0-x-container)\n :global(.vtex-store-components-3-x-logoLink),\n:global(.vtex-sticky-layout-0-x-container)\n :global(.vtex-minicart-2-x-openIconContainer),\n:global(.vtex-sticky-layout-0-x-container)\n :global(.vtex-store-components-3-x-searchBarContainer) {\n transition: all 0.3s ease;\n display: block;\n}\n\n/* desktop/mobile main header padding and background transitions */\n:global(.vtex-flex-layout-0-x-flexRowContent--main-header),\n:global(.vtex-flex-layout-0-x-flexRowContent--main-header-mobile) {\n transition: background 0.3s ease;\n will-change: padding, background;\n}\n\n/* main header desktop has a bigger padding when not stuck */\n:global(.vtex-flex-layout-0-x-flexRowContent--main-header) {\n padding-top: 0.5rem;\n padding-bottom: 0.5rem;\n}\n\n/* add a box-shadow to desktop/mobile header when stuck */\n:global(.vtex-sticky-layout-0-x-wrapper--stuck)\n :global(.vtex-flex-layout-0-x-flexRowContent--main-header),\n:global(.vtex-sticky-layout-0-x-wrapper--stuck)\n :global(.vtex-flex-layout-0-x-flexRowContent--main-header-mobile) {\n box-shadow: 0 4px 5px rgba(0, 0, 0, 0.1);\n}\n\n/*\n * remove the extra padding when stuck from the desktop header\n * we add a transition only when \"stuck\" for the \"unstick\" step seem faster\n */\n:global(.vtex-sticky-layout-0-x-wrapper--stuck)\n :global(.vtex-flex-layout-0-x-flexRowContent--main-header) {\n transition: padding 0.3s ease, background 0.3s ease;\n padding-top: 0;\n padding-bottom: 0;\n}\n\n/* if supported add some translucency to the desktop/mobile header background */\n@supports (backdrop-filter: blur(5px)) {\n :global(.vtex-sticky-layout-0-x-wrapper--stuck)\n :global(.vtex-flex-layout-0-x-flexRowContent--main-header),\n :global(.vtex-sticky-layout-0-x-wrapper--stuck)\n :global(.vtex-flex-layout-0-x-flexRowContent--main-header-mobile) {\n backdrop-filter: blur(8px);\n }\n\n /* header background when stuck and not hovered */\n :global(.vtex-sticky-layout-0-x-wrapper--stuck):not(:hover)\n :global(.vtex-flex-layout-0-x-flexRowContent--main-header),\n :global(.vtex-sticky-layout-0-x-wrapper--stuck):not(:hover)\n :global(.vtex-flex-layout-0-x-flexRowContent--main-header-mobile) {\n background: rgba(240, 240, 240, 0.8);\n }\n}\n\n/* stick wrapper with the same color as the desktop/mobile header */\n:global(.vtex-sticky-layout-0-x-wrapper--sticky-header) {\n background-color: #f0f0f0;\n}\n\n/* resize the logo for neat effect */\n:global(.vtex-sticky-layout-0-x-wrapper--stuck)\n :global(.vtex-store-components-3-x-logoLink) {\n transform: scale(0.85);\n}\n\n@media (prefers-reduced-motion: reduce) {\n :global(.vtex-sticky-layout-0-x-container)\n :global(.vtex-store-components-3-x-logoLink),\n :global(.vtex-sticky-layout-0-x-container)\n :global(.vtex-minicart-2-x-openIconContainer),\n :global(.vtex-sticky-layout-0-x-container)\n :global(.vtex-store-components-3-x-searchBarContainer),\n :global(.vtex-sticky-layout-0-x-wrapper--stuck)\n :global(.vtex-flex-layout-0-x-flexRowContent--main-header) {\n transition: none;\n }\n}\n\n```"
}
] |
code_training-week-demo_1c54c5ba
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.store-components.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.notificationBarContainer {\n background-color: #e6f1e6;\n color: #03034e;\n font-weight: 700;\n font-size: 12px;\n text-decoration: underline;\n}\n\n.infoCardContainer--info-card-home {\n max-width: 1520px;\n margin: 0 auto;\n background-color: #e6f1e6;\n padding: 0px;\n}\n\n.newsletter {\n background-color: #03054e;\n max-width: 1528px;\n margin: 0 auto;\n}\n\n.newsletter .container {\n padding: 60px 10px;\n}\n\n.label {\n color: #fff;\n font-size: 26px;\n}\n\n.inputGroup {\n padding-bottom: 4px;\n display: flex;\n color: #fff;\n}\n\n.inputGroup :global(.vtex-styleguide-9-x-hideDecorators) {\n background-color: transparent;\n color: #fff;\n border: none;\n}\n\n.inputGroup :global(.vtex-styleguide-9-x-hideDecorators)::placeholder {\n color: #fff;\n font-size: 16px;\n}\n\n.inputGroup :global(.vtex-button) {\n background-color: transparent;\n color: #fff;\n border: none;\n margin-right: -24px;\n}\n\n.buttonContainer {\n padding-top: 0px;\n}\n\n.imageElement--storePrint {\n max-height: 300px;\n margin-bottom: 20px;\n}\n\n.skuSelectorContainer {\n margin: 1rem 0;\n}\n\n@media only screen and (min-width: 640px) {\n .newsletter .container {\n padding: 140px;\n }\n\n .label {\n font-size: 40px;\n }\n\n .infoCardContainer--info-card-home .infoCardTextContainer {\n width: 30%;\n }\n\n .infoCardContainer--info-card-home .infoCardImageContainer {\n width: 70%;\n }\n\n .imageElement--storePrint {\n margin-bottom: 0px;\n max-height: 600px;\n }\n}\n\n.productImagesContainer--quickview .carouselContainer {\n justify-content: flex-start;\n}\n\n.productImagesContainer--quickview .productImageTag {\n object-fit: cover !important;\n}\n\n.productImagesContainer--quickview .carouselGaleryThumbs {\n display: none;\n}\n\n.productImagesContainer--quickview .carouselGaleryCursor {\n margin: 0;\n padding: 0;\n width: 100%;\n}\n\n.productNameContainer {\n color: #3f3f40;\n font-weight: bold;\n font-size: 30px;\n}\n\n```"
}
] |
code_training-week-demo_d112c396
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.store-footer.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.row--menu-row {\n padding-right: 24px;\n}\n\n.row--menu-row .rowContainer {\n align-items: flex-start;\n}\n\n.row--payment-methods {\n padding-top: 16px;\n}\n\n```"
}
] |
code_training-week-demo_c4607986
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.product-identifier.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.product-identifier--productReference {\n margin-bottom: 1rem;\n}\n\n```"
}
] |
code_training-week-demo_f4fdc97e
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.reviews-and-ratings.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.container {\n max-width: 96rem;\n padding-left: .5rem;\n padding-right: .5rem;\n}\n\n.inlineContainer {\n margin-left: 0rem;\n}\n\n.star--filled {\n color: #FFB100;\n}\n\n.star--empty {\n color: #FFB100;\n}\n\n```"
}
] |
code_training-week-demo_48f8d05f
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.product-highlights.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.productHighlightWrapper--collection {\n position: absolute;\n top: 10px;\n left: 5px;\n width: 200px;\n}\n\n.productHighlightText {\n background: antiquewhite;\n border-radius: 20px;\n padding: 5px 10px;\n}\n\n```"
}
] |
code_training-week-demo_f8b1d5c4
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.flex-layout.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.flexRowContent--menu-link,\n.flexRowContent--main-header {\n padding: 0 0.5rem;\n}\n\n@media screen and (min-width: 40em) {\n .flexRowContent--menu-link,\n .flexRowContent--main-header {\n padding: 0 1rem;\n }\n}\n@media screen and (min-width: 80rem) {\n .flexRowContent--menu-link,\n .flexRowContent--main-header {\n padding: 0 0.25rem;\n }\n}\n\n.flexRowContent--menu-link {\n background-color: #03044e;\n color: #fff;\n}\n\n.flexRowContent--main-header {\n background-color: #f0f0f0;\n}\n\n.flexRowContent--main-header-mobile {\n align-items: center;\n padding: 0.625rem 0.5rem;\n background-color: #f0f0f0;\n}\n\n.flexRowContent--menu-link :global(.vtex-menu-2-x-styledLink) {\n color: #ffffff;\n font-size: 14px;\n}\n\n.flexRowContent--main-header :global(.vtex-menu-2-x-styledLink) {\n color: #727273;\n font-size: 14px;\n}\n.flexRow--deals {\n background-color: #a7afbd;\n padding: 14px 0px;\n}\n\n.flexRow--deals .stretchChildrenWidth {\n align-items: center;\n}\n\n.flexRow--deals .flexCol {\n align-items: center;\n}\n\n.flexCol--filterCol {\n max-width: 500px;\n min-width: 230px;\n}\n\n.flexCol--productCountCol {\n align-items: flex-start;\n}\n\n.flexCol--orderByCol {\n align-items: flex-end;\n}\n\n.flexCol--orderByMobileCol {\n width: 42%;\n}\n\n.flexCol--filterMobileCol {\n width: 38%;\n}\n\n.flexRow--quickviewMainRow {\n display: flex;\n max-height: 100%;\n}\n\n.flexColChild--quickviewDetails:first-child {\n overflow-y: auto;\n height: 66% !important;\n overflow-x: hidden;\n}\n\n.flexColChild--quickviewDetails:last-child {\n height: 34% !important;\n}\n\n.flexRow--addToCartRow {\n padding-bottom: 1rem;\n}\n\n```"
}
] |
code_training-week-demo_a5a67014
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.carousel.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.containerImg {\n background-color: #F0F0F0;\n}\n\n.containerImg .img {\n max-width: 1520px;\n}\n\n```"
}
] |
code_training-week-demo_0380ddad
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.search-result.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.galleryLayoutOptionButton {\n background-color: #F0F0F0;\n color: #3F3F40;\n padding: 0.375rem 0.75rem 0.375rem 0.75rem;\n}\n\n.galleryLayoutOptionButton--selected {\n background-color: #3F3F40;\n color: #FFFFFF;\n}\n\n.galleryLayoutSwitcher {\n border-radius: 4px 4px 4px 4px;\n justify-content: center;\n overflow: hidden;\n width: auto !important;\n align-self: center\n}\n\n.galleryItem--list {\n border-bottom: 1px #E7E9EE solid;\n}\n\n```"
}
] |
code_training-week-demo_09552ea6
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.slider-layout.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.sliderLayoutContainer {\n justify-content: center;\n}\n.sliderLayoutContainer--carousel {\n background-color: #F0F0F0;\n}\n\n.sliderTrackContainer {\n max-width: 1520px;\n}\n\n.paginationDotsContainer {\n margin-top: .5rem;\n margin-bottom: .5rem;\n}\n\n.layoutContainer--shelf {\n margin-top: 20px;\n margin-bottom: 20px;\n max-width: 96rem;\n}\n\n.slide--shelf {\n margin-bottom: 25px;\n padding-left: .5rem;\n padding-right: .5rem;\n}\n\n```"
}
] |
code_training-week-demo_09c95403
|
[
{
"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 training-week-demo/store-theme/styles/css/vtex.stack-layout.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.stackItem--product {\n width: 100%;\n}\n\n.stackItem--quickview {\n right: 0;\n top: 0;\n left: auto;\n}\n\n```"
}
] |
code_training-week-demo_663bcfd5
|
[
{
"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 training-week-demo/store-theme/styles/configs/style.json from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"typeScale\": [\n 3, 2.25, 1.5, 1.25, 1, 0.875, 0.75\n ],\n \"spacing\": [0.125, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 8, 16],\n \"customMedia\": [\n { \"s\": 20 },\n { \"ns\": {\n \"value\": 40,\n \"minWidth\": true\n }\n },\n { \"m\": {\n \"value\": 40,\n \"minWidth\": true\n }\n },\n { \"l\": {\n \"value\": 64,\n \"minWidth\": true\n }\n },\n { \"xl\": {\n \"value\": 80,\n \"minWidth\": true\n }\n }\n ],\n \"colors\": {\n \"black-90\": \"rgba(0,0,0,.9)\",\n \"black-80\": \"rgba(0,0,0,.8)\",\n \"black-70\": \"rgba(0,0,0,.7)\",\n \"black-60\": \"rgba(0,0,0,.6)\",\n \"black-50\": \"rgba(0,0,0,.5)\",\n \"black-40\": \"rgba(0,0,0,.4)\",\n \"black-30\": \"rgba(0,0,0,.3)\",\n \"black-20\": \"rgba(0,0,0,.2)\",\n \"black-10\": \"rgba(0,0,0,.1)\",\n \"black-05\": \"rgba(0,0,0,.05)\",\n \"black-025\": \"rgba(0,0,0,.025)\",\n \"black-0125\": \"rgba(0,0,0,.0125)\",\n\n \"white-90\": \"rgba(255,255,255,.9)\",\n \"white-80\": \"rgba(255,255,255,.8)\",\n \"white-70\": \"rgba(255,255,255,.7)\",\n \"white-60\": \"rgba(255,255,255,.6)\",\n \"white-50\": \"rgba(255,255,255,.5)\",\n \"white-40\": \"rgba(255,255,255,.4)\",\n \"white-30\": \"rgba(255,255,255,.3)\",\n \"white-20\": \"rgba(255,255,255,.2)\",\n \"white-10\": \"rgba(255,255,255,.1)\",\n \"white-05\": \"rgba(255,255,255,.05)\",\n \"white-025\": \"rgba(255,255,255,.025)\",\n \"white-0125\": \"rgba(255,255,255,.0125)\"\n },\n \"semanticColors\": {\n \"background\": {\n \"base\": \"#ffffff\",\n \"base--inverted\": \"#03044e\",\n \"action-primary\": \"#0F3E99\",\n \"action-secondary\": \"#eef3f7\",\n \"emphasis\": \"#f71963\",\n \"disabled\": \"#f2f4f5\",\n \"success\": \"#8bc34a\",\n \"success--faded\": \"#eafce3\",\n \"danger\": \"#ff4c4c\",\n \"danger--faded\": \"#ffe6e6\",\n \"warning\": \"#ffb100\",\n \"warning--faded\": \"#fff6e0\",\n \"muted-1\": \"#727273\",\n \"muted-2\": \"#979899\",\n \"muted-3\": \"#cacbcc\",\n \"muted-4\": \"#e3e4e6\",\n \"muted-5\": \"#f2f4f5\"\n },\n \"hover-background\": {\n \"action-primary\": \"#072c75\",\n \"action-secondary\": \"#dbe9fd\",\n \"emphasis\": \"#dd1659\",\n \"success\": \"#8bc34a\",\n \"success--faded\": \"#eafce3\",\n \"danger\": \"#e13232\",\n \"danger--faded\": \"#ffe6e6\",\n \"warning\": \"#ffb100\",\n \"warning--faded\": \"#fff6e0\",\n \"muted-1\": \"#727273\",\n \"muted-2\": \"#979899\",\n \"muted-3\": \"#cacbcc\",\n \"muted-4\": \"#e3e4e6\",\n \"muted-5\": \"#f2f4f5\"\n },\n \"active-background\": {\n \"action-primary\": \"#0c389f\",\n \"action-secondary\": \"#d2defc\",\n \"emphasis\": \"#dd1659\",\n \"success\": \"#8bc34a\",\n \"success--faded\": \"#eafce3\",\n \"danger\": \"#ff4c4c\",\n \"danger--faded\": \"#ffe6e6\",\n \"warning\": \"#ffb100\",\n \"warning--faded\": \"#fff6e0\",\n \"muted-1\": \"#727273\",\n \"muted-2\": \"#979899\",\n \"muted-3\": \"#cacbcc\",\n \"muted-4\": \"#e3e4e6\",\n \"muted-5\": \"#f2f4f5\"\n },\n \"text\": {\n \"action-primary\": \"#0F3E99\",\n \"action-secondary\": \"#eef3f7\",\n \"link\": \"#0F3E99\",\n \"emphasis\": \"#f71963\",\n \"disabled\": \"#979899\",\n \"success\": \"#8bc34a\",\n \"success--faded\": \"#eafce3\",\n \"danger\": \"#ff4c4c\",\n \"danger--faded\": \"#ffe6e6\",\n \"warning\": \"#ffb100\",\n \"warning--faded\": \"#fff6e0\",\n \"muted-1\": \"#727273\",\n \"muted-2\": \"#979899\",\n \"muted-3\": \"#cacbcc\",\n \"muted-4\": \"#e3e4e6\",\n \"muted-5\": \"#f2f4f5\"\n },\n \"visited-text\": {\n \"link\": \"#0c389f\"\n },\n \"hover-text\": {\n \"action-primary\": \"#072c75\",\n \"action-secondary\": \"#dbe9fd\",\n \"link\": \"#0c389f\",\n \"emphasis\": \"#dd1659\",\n \"success\": \"#8bc34a\",\n \"success--faded\": \"#eafce3\",\n \"danger\": \"#e13232\",\n \"danger--faded\": \"#ffe6e6\",\n \"warning\": \"#ffb100\",\n \"warning--faded\": \"#fff6e0\"\n },\n \"active-text\": {\n \"link\": \"#0c389f\",\n \"emphasis\": \"#dd1659\",\n \"success\": \"#8bc34a\",\n \"success--faded\": \"#eafce3\",\n \"danger\": \"#ff4c4c\",\n \"danger--faded\": \"#ffe6e6\",\n \"warning\": \"#ffb100\",\n \"warning--faded\": \"#fff6e0\"\n },\n \"border\": {\n \"action-primary\": \"#0F3E99\",\n \"action-secondary\": \"#eef3f7\",\n \"emphasis\": \"#f71963\",\n \"disabled\": \"#e3e4e6\",\n \"success\": \"#8bc34a\",\n \"success--faded\": \"#eafce3\",\n \"danger\": \"#ff4c4c\",\n \"danger--faded\": \"#ffe6e6\",\n \"warning\": \"#ffb100\",\n \"warning--faded\": \"#fff6e0\",\n \"muted-1\": \"#727273\",\n \"muted-2\": \"#979899\",\n \"muted-3\": \"#cacbcc\",\n \"muted-4\": \"#e3e4e6\",\n \"muted-5\": \"#f2f4f5\"\n },\n \"hover-border\": {\n \"action-primary\": \"#072c75\",\n \"action-secondary\": \"#dbe9fd\",\n \"emphasis\": \"#dd1659\",\n \"success\": \"#8bc34a\",\n \"success--faded\": \"#eafce3\",\n \"danger\": \"#e13232\",\n \"danger--faded\": \"#ffe6e6\",\n \"warning\": \"#ffb100\",\n \"warning--faded\": \"#fff6e0\",\n \"muted-1\": \"#727273\",\n \"muted-2\": \"#979899\",\n \"muted-3\": \"#cacbcc\",\n \"muted-4\": \"#e3e4e6\",\n \"muted-5\": \"#f2f4f5\"\n },\n \"active-border\": {\n \"action-primary\": \"#0c389f\",\n \"action-secondary\": \"#d2defc\",\n \"emphasis\": \"#dd1659\",\n \"success\": \"#8bc34a\",\n \"success--faded\": \"#eafce3\",\n \"danger\": \"#ff4c4c\",\n \"danger--faded\": \"#ffe6e6\",\n \"warning\": \"#ffb100\",\n \"warning--faded\": \"#fff6e0\",\n \"muted-1\": \"#727273\",\n \"muted-2\": \"#979899\",\n \"muted-3\": \"#cacbcc\",\n \"muted-4\": \"#e3e4e6\",\n \"muted-5\": \"#f2f4f5\"\n },\n \"on\": {\n \"base\": \"#3f3f40\",\n \"base--inverted\": \"#ffffff\",\n \"action-primary\": \"#ffffff\",\n \"action-secondary\": \"#0F3E99\",\n \"emphasis\": \"#ffffff\",\n \"disabled\": \"#979899\",\n \"success\": \"#ffffff\",\n \"success--faded\": \"#3f3f40\",\n \"danger\": \"#ffffff\",\n \"danger--faded\": \"#3f3f40\",\n \"warning\": \"#ffffff\",\n \"warning--faded\": \"#1a1a1a\",\n \"muted-1\": \"#ffffff\",\n \"muted-2\": \"#ffffff\",\n \"muted-3\": \"#3f3f40\",\n \"muted-4\": \"#3f3f40\",\n \"muted-5\": \"#3f3f40\"\n },\n \"hover-on\": {\n \"action-primary\": \"#ffffff\",\n \"action-secondary\": \"#0F3E99\",\n \"emphasis\": \"#ffffff\",\n \"success\": \"#ffffff\",\n \"success--faded\": \"#3f3f40\",\n \"danger\": \"#ffffff\",\n \"danger--faded\": \"#3f3f40\",\n \"warning\": \"#ffffff\",\n \"warning--faded\": \"#1a1a1a\"\n },\n \"active-on\": {\n \"action-primary\": \"#ffffff\",\n \"action-secondary\": \"#0F3E99\",\n \"emphasis\": \"#ffffff\",\n \"success\": \"#ffffff\",\n \"success--faded\": \"#3f3f40\",\n \"danger\": \"#ffffff\",\n \"danger--faded\": \"#3f3f40\",\n \"warning\": \"#ffffff\",\n \"warning--faded\": \"#1a1a1a\"\n }\n },\n \"borderWidths\": [0, 0.125, 0.25, 0.5, 1, 2],\n \"borderRadius\": [0, 0.125, 0.25, 0.5, 1],\n \"widths\": [1, 2, 4, 8, 16],\n \"maxWidths\": [1, 2, 4, 8, 16, 32, 48, 64, 96],\n \"heights\": [1, 2, 4, 8, 16],\n \"sizes\": [\n {\"name\": \"small\", \"value\": 2},\n {\"name\": \"regular\", \"value\": 2.5},\n {\"name\": \"large\", \"value\": 3}\n ],\n \"typography\":{\n \"measure\": [30, 34, 20],\n \"styles\": {\n \"heading-1\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"700\",\n \"fontSize\": \"3rem\",\n \"textTransform\": \"initial\",\n \"letterSpacing\": \"0\"\n },\n \"heading-2\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"700\",\n \"fontSize\": \"2.25rem\",\n \"textTransform\": \"initial\",\n \"letterSpacing\": \"0\"\n },\n \"heading-3\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"700\",\n \"fontSize\": \"1.75rem\",\n \"textTransform\": \"initial\",\n \"letterSpacing\": \"0\"\n },\n \"heading-4\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"normal\",\n \"fontSize\": \"1.5rem\",\n \"textTransform\": \"initial\",\n \"letterSpacing\": \"0\"\n },\n \"heading-5\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"normal\",\n \"fontSize\": \"1.25rem\",\n \"textTransform\": \"initial\",\n \"letterSpacing\": \"0\"\n },\n \"heading-6\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"normal\",\n \"fontSize\": \"1.25rem\",\n \"textTransform\": \"initial\",\n \"letterSpacing\": \"0\"\n },\n \"body\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"normal\",\n \"fontSize\": \"1rem\",\n \"textTransform\": \"initial\",\n \"letterSpacing\": \"0\"\n },\n \"small\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"normal\",\n \"fontSize\": \"0.875rem\",\n \"textTransform\": \"initial\",\n \"letterSpacing\": \"0\"\n },\n \"mini\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"normal\",\n \"fontSize\": \"0.75rem\",\n \"textTransform\": \"initial\",\n \"letterSpacing\": \"0\"\n },\n \"action\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"500\",\n \"fontSize\": \"1rem\",\n \"textTransform\": \"uppercase\",\n \"letterSpacing\": \"0\"\n },\n \"action--small\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"500\",\n \"fontSize\": \"0.875rem\",\n \"textTransform\": \"uppercase\",\n \"letterSpacing\": \"0\"\n },\n \"action--large\": {\n \"fontFamily\": \"San Francisco, -apple-system, BlinkMacSystemFont, avenir next, avenir, helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif\",\n \"fontWeight\": \"500\",\n \"fontSize\": \"1.25rem\",\n \"textTransform\": \"uppercase\",\n \"letterSpacing\": \"0\"\n },\n \"code\": {\n \"fontFamily\": \"Consolas, monaco, monospace\",\n \"fontWeight\": \"normal\",\n \"fontSize\": \"1rem\",\n \"textTransform\": \"initial\",\n \"letterSpacing\": \"0\"\n }\n }\n },\n \"opacity\": [1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.05, 0.025, 0]\n}\n\n```"
}
] |
code_training-week-demo_7fc44069
|
[
{
"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 training-week-demo/store-theme/styles/css/contact/vtex.flex-layout.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.flexRowContent--contact {\n max-width: 700px;\n margin: auto;\n}\n\n.flexRowContent--contact :global(.vtex-input__label),\n.flexRowContent--contact :global(.vtex-textarea__label) {\n font-size: 1rem;\n color: #3f3f40;\n}\n\n.flexRowContent--contact :global(.vtex-input),\n.flexRowContent--contact :global(.vtex-textarea) {\n display: block;\n margin-bottom: 1rem;\n}\n\n```"
}
] |
code_training-week-demo_c880a87a
|
[
{
"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 training-week-demo/store-theme/styles/css/faq/vtex.flex-layout.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.flexRowContent--faq {\n max-width: 700px;\n margin: auto;\n}\n\n```"
}
] |
code_training-week-demo_ed5436e9
|
[
{
"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 training-week-demo/store-theme/styles/css/faq/vtex.disclosure-layout.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.trigger--question {\n display: flex;\n align-items: center;\n cursor: pointer;\n outline: none;\n}\n\n.trigger--question :global(.vtex-rich-text-0-x-paragraph) {\n font-weight: bold;\n}\n\n.trigger--question:focus,\n.trigger--question:focus :global(.vtex-rich-text-0-x-paragraph) {\n color: #0F3E99;\n}\n\n.trigger :global(.vtex-store-icons-0-x-caretIcon) {\n margin-right: 1rem;\n}\n\n.content--answer {\n transition: opacity 250ms ease-in-out, height 250ms ease-in-out, transform 250ms ease-in-out;\n opacity: 0;\n height: 0;\n transform: translate3d(0, -10%, 0);\n}\n\n.content--answer[data-enter] {\n opacity: 1;\n height: fit-content;\n transform: translate3d(0, 0, 0);\n}\n\n.content--answer[data-leave] {\n height: 0;\n overflow: hidden;\n}\n\n```"
}
] |
code_training-week-demo_ed8c36b3
|
[
{
"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 training-week-demo/store-theme/styles/css/search/vtex.rich-text.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.container--layout-option {\n margin-left: 0.3em;\n}\n\n.paragraph--layout-option {\n margin: 0;\n}\n\n.paragraph--summarySpecificationBullet {\n margin: 0;\n line-height: initial;\n font-size: 1.25rem;\n line-height: 1.15rem;\n}\n\n```"
}
] |
code_training-week-demo_ac490002
|
[
{
"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 training-week-demo/store-theme/styles/css/search/vtex.product-summary.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.nameContainer--summaryListDesktop {\n padding-top: 0.25rem;\n padding-bottom: 0.75rem;\n justify-content: start;\n}\n\n.nameContainer--summaryListMobile {\n padding-top: 0.25rem;\n padding-bottom: 0.5rem;\n justify-content: start;\n}\n\n.brandName--summaryListMobile {\n font-weight: 400;\n font-size: 0.875rem;\n color: black;\n}\n\n.container--listLayout {\n max-width: none !important;\n}\n\n.image--summaryListDesktop {\n width: 180px !important;\n}\n\n.image--summaryListMobile {\n width: 140px !important;\n min-width: 140px;\n height: inherit !important;\n}\n\n```"
}
] |
code_training-week-demo_7961ca0e
|
[
{
"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 training-week-demo/store-theme/styles/css/search/vtex.store-components.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.productBrandName--summaryListDesktop {\n text-decoration: none;\n font-weight: 500;\n color: #0067C7;\n font-size: .875rem;\n}\n\n.productBrandName--summaryListMobile {\n text-decoration: none;\n color: #0067C7;\n font-size: .875rem;\n}\n\n```"
}
] |
code_training-week-demo_24c93cbb
|
[
{
"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 training-week-demo/store-theme/styles/css/search/vtex.flex-layout.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.flexRow--orderByAndSwitcher {\n padding-right: 1.5em;\n}\n\n.flexRowContent--savingsSummaryListDesktop {\n justify-content: flex-start;\n}\n\n.flexCol--summaryRightListDesktop {\n justify-content: space-around;\n}\n\n.flexRow--buyNowButton :global(.vtex-button) {\n background: #eef3f7;\n border-color:#eef3f7;\n color: #0f3e99;\n}\n\n.flexRow--buyNowButton:hover :global(.vtex-button) {\n background: #dbe9fd;\n border-color:#dbe9fd;\n}\n\n.flexCol--productRating {\n margin-bottom: 3rem;\n}\n\n.flexCol--summaryDetailsListMobile {\n justify-content: space-between;\n}\n\n.flexCol--summaryUpDetailsListMobile {\n margin-bottom: 0.25rem\n}\n\n```"
}
] |
code_training-week-demo_dbcf03df
|
[
{
"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 training-week-demo/store-theme/styles/css/product-specification-table/vtex.flex-layout.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.flexRow--productSpecificationGroup:not(:first-child) {\n margin-top: 1.5rem;\n}\n\n.flexRow--productSpecificationGroupName {\n background-color: #eaeaea;\n padding: 0.5rem 1rem;\n}\n\n.flexCol--productSpecificationName {\n padding: 1rem;\n}\n\n.flexCol--productSpecificationValue {\n padding: 1rem 1rem 1rem 0;\n}\n\n.flexRow--productSpecification:nth-child(even) {\n background-color: #f9f9f9;\n}\n\n```"
}
] |
code_training-week-demo_ee0a803f
|
[
{
"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 training-week-demo/store-theme/styles/css/product-specification-table/vtex.product-specifications.css from the training-week-demo VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.groupName {\n font-size: 1.25rem;\n}\n\n.specificationName {\n font-weight: bold;\n}\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.