id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_storefront-permissions_8727ba18
|
[
{
"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 storefront-permissions/node/utils/cookie.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { parse } from 'cookie'\nimport { keys } from 'ramda'\n\nconst isUserLoggedIn = (ctx: Context) => {\n const {\n vtex: { account },\n } = ctx\n\n return !!ctx.cookies.get(`VtexIdclientAutCookie_${account}`)\n}\n\nconst parseCookie = (cookie: string) => {\n const parsed = parse(cookie)\n const [cookieName] = keys(parsed)\n const cookieValue = parsed[cookieName]\n\n const extraOptions = {\n domain: parsed.domain,\n expires: parsed.expires ? new Date(parsed.expires) : undefined,\n path: parsed.path,\n }\n\n return {\n name: cookieName,\n options: extraOptions,\n value: cookieValue,\n }\n}\n\n/** Checkout cookie methods */\nconst CHECKOUT_COOKIE = 'checkout.vtex.com'\n\nconst checkoutCookieFormat = (orderFormId: string) =>\n `${CHECKOUT_COOKIE}=__ofid=${orderFormId};`\n\nconst getOrderFormIdFromCookie = (cookies: Context['cookies']) => {\n const cookie = cookies.get(CHECKOUT_COOKIE)\n\n return cookie && cookie.split('=')[1]\n}\n\nexport {\n isUserLoggedIn,\n CHECKOUT_COOKIE,\n checkoutCookieFormat,\n getOrderFormIdFromCookie,\n parseCookie,\n}\n\n```"
}
] |
code_storefront-permissions_3a7ec59e
|
[
{
"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 storefront-permissions/node/utils/constants.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const CUSTOMER_SCHEMA_NAME = 'CL'\nexport const CUSTOMER_REQUIRED_FIELDS = [\n 'email',\n 'id',\n 'accountId',\n 'accountName',\n 'dataEntityId',\n]\nexport const ROLES_VBASE_ID = 'allRolesVbId'\n\n// License Manager constants\nexport const B2B_ORGANIZATIONS_PRODUCT_ID = 97\nexport const B2B_LM_PRODUCT_CODE = B2B_ORGANIZATIONS_PRODUCT_ID\nexport const BUYER_ORGANIZATION_VIEW_ROLE = 'buyer_organization_view'\nexport const BUYER_ORGANIZATION_EDIT_ROLE = 'buyer_organization_edit'\n\n// License Manager roles object\nexport const LICENSE_MANAGER_ROLES = {\n B2B_ORGANIZATIONS_VIEW: BUYER_ORGANIZATION_VIEW_ROLE,\n B2B_ORGANIZATIONS_EDIT: BUYER_ORGANIZATION_EDIT_ROLE,\n}\n\n// Role constants for GraphQL directives\nexport const B2B_ORGANIZATIONS_EDIT_ROLE_PARAM = 'B2B_ORGANIZATIONS_EDIT'\n\n```"
}
] |
code_storefront-permissions_31643d1c
|
[
{
"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 storefront-permissions/node/utils/GraphQLError.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport default class GraphQLError extends Error {\n public extensions: any\n\n constructor(message: string, details?: any) {\n super(message)\n this.extensions = {\n message,\n ...details,\n exception: {\n ...details?.exception,\n // vtex-node-api checks err?.extensions?.exception?.level before logging\n level: details?.logLevel || 'error',\n },\n }\n }\n}\n\n```"
}
] |
code_storefront-permissions_7c5844c6
|
[
{
"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 storefront-permissions/node/utils/LicenseManager.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nimport { statusToError, toUUID } from './index'\nimport {\n B2B_ORGANIZATIONS_PRODUCT_ID,\n BUYER_ORGANIZATION_VIEW_ROLE,\n BUYER_ORGANIZATION_EDIT_ROLE,\n} from './constants'\n\nexport class LMClient extends ExternalClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(`http://${ctx.account}.vtexcommercestable.com.br/`, ctx, {\n ...options,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n VtexIdclientAutCookie: ctx.authToken,\n },\n })\n }\n\n public getUserIdByEmail = async (email: string) => {\n return this.get(this.routes.userByEmail(email))\n .then((res: any) => {\n return res?.UserId ? toUUID(res.UserId) : null\n })\n .catch(() => {\n return null\n })\n }\n\n public saveUser = async (name: string, email: string) => {\n const data = {\n email,\n name,\n roles: [\n {\n id: 957,\n },\n ],\n }\n\n // Check if the user exists\n const checkUser: any = await this.get(this.routes.userByEmail(email))\n .then((res: any) => {\n return res\n })\n .catch(() => {\n return {}\n })\n\n if (!checkUser?.UserId) {\n // Create with role\n return this.post(this.routes.createUser(), data)\n .then(() => true)\n .catch(() => false)\n }\n\n // Update with role\n return this.put(this.routes.updateUser(checkUser.UserId), [957]).then(\n () => {\n return { userId: checkUser.UserId }\n }\n )\n }\n\n public deleteUser = async (userId: string) => {\n const user = await this.get(this.routes.userById(userId))\n .then(() => {\n return true\n })\n .catch(() => {\n return false\n })\n\n return user ? this.delete(this.routes.deleteUser(userId, '957'), {}) : {}\n }\n\n public getUserAdminPermissions = async (account: string, userId: string) => {\n return this.get(this.routes.getUserAdminPermissions(account, userId)).then(\n (res: any) => {\n return res\n }\n )\n }\n\n public checkUserSpecificRole = async (\n account: string,\n userEmail: string,\n productCode: number,\n resourceCode: string\n ) => {\n return this.get(\n `/api/license-manager/pvt/accounts/${encodeURI(\n account\n )}/products/${productCode}/logins/${encodeURI(\n userEmail\n )}/resources/${encodeURI(resourceCode)}/granted`\n ).then((res: any) => {\n return res\n })\n }\n\n public hasBuyerOrganizationViewRole = async (\n account: string,\n userEmail: string\n ) => {\n try {\n const hasRole = await this.checkUserSpecificRole(\n account,\n userEmail,\n B2B_ORGANIZATIONS_PRODUCT_ID,\n BUYER_ORGANIZATION_VIEW_ROLE\n )\n\n return hasRole\n } catch (error) {\n return false\n }\n }\n\n public hasBuyerOrganizationEditRole = async (\n account: string,\n userEmail: string\n ) => {\n try {\n const hasRole = await this.checkUserSpecificRole(\n account,\n userEmail,\n B2B_ORGANIZATIONS_PRODUCT_ID,\n BUYER_ORGANIZATION_EDIT_ROLE\n )\n\n return hasRole\n } catch (error) {\n return false\n }\n }\n\n protected get = <T>(url: string) => {\n return this.http.get<T>(url).catch(statusToError)\n }\n\n protected post = <T>(url: string, data: any) => {\n return this.http.post<T>(url, data).catch(statusToError)\n }\n\n protected put = <T>(url: string, data: any) => {\n return this.http.put<T>(url, data).catch(statusToError)\n }\n\n protected delete = <T>(url: string, data: any) => {\n return this.http.delete<T>(url, data).catch(statusToError)\n }\n\n private get routes() {\n return {\n addCallcenter: (userId: string) =>\n `api/license-manager/users/${userId}/roles`,\n createRole: () => `api/license-manager/site/pvt/roles`,\n createUser: () => `api/license-manager/site/pvt/logins`,\n deleteUser: (userId: string, roleId: string) =>\n `api/license-manager/users/${userId}/roles/${roleId}`,\n getRoles: () => `api/license-manager/site/pvt/roles/list/paged`,\n updateUser: (userId: string) =>\n `api/license-manager/users/${userId}/roles`,\n userByEmail: (email: string) =>\n `api/license-manager/pvt/users/${encodeURIComponent(email)}`,\n userById: (id: string) => `api/license-manager/pvt/users/${id}`,\n getUserAdminPermissions: (account: string, userId: string) =>\n `/api/license-manager/pvt/accounts/${account}/logins/${userId}/granted`,\n }\n }\n}\n\n```"
}
] |
code_storefront-permissions_dfdeb81b
|
[
{
"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 storefront-permissions/node/utils/ProfileSystem.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext, RequestConfig } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nexport class ProfileSystemClient extends JanusClient {\n private baseUrl = '/api/profile-system/pvt/profiles'\n\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n ...options?.headers,\n VtexIdClientAutCookie: context.authToken,\n },\n timeout: 5000,\n })\n }\n\n public getProfileInfo = (userId: string, customFields?: string) =>\n this.get(`${this.baseUrl}/${userId}/personalData`, {\n metric: 'profile-system-getProfileInfo',\n params: {\n extraFields: customFields,\n },\n })\n\n public async createRegisterOnProfileSystem(email: string, name: string) {\n const value = await this.http.post<{ profileId: string }>(\n `${this.baseUrl}/${email}/PersonalData?extraFields=_all`,\n {\n firstName: name,\n }\n )\n\n return value.profileId\n }\n\n protected get = <T>(url: string, config?: RequestConfig) =>\n this.http.get<T>(url, config)\n}\n\n```"
}
] |
code_storefront-permissions_0edf616d
|
[
{
"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 storefront-permissions/node/utils/index.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport * as crypto from 'crypto'\n\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\nimport type { AxiosError } from 'axios'\nimport slugify from 'slugify'\n\nimport schemas from '../mdSchema'\nimport type { ErrorResponse } from '../resolvers/Routes/utils'\nimport roleNames from '../roleNames'\n\nexport * from './cookie'\n\nexport const toHash = (obj: any) => {\n return crypto.createHash('md5').update(JSON.stringify(obj)).digest('hex')\n}\n\nexport function toUUID(uuid: string) {\n return uuid.indexOf('-') === -1\n ? `${uuid.substring(0, 8)}-${uuid.substring(8, 12)}-${uuid.substring(\n 12,\n 16\n )}-${uuid.substring(16, 20)}-${uuid.substring(20, uuid.length)}`\n : uuid\n}\n\nexport function Slugify(str: any) {\n return slugify(str, { lower: true, remove: /[*+~.()'\"!:@]/g })\n}\n\nexport const currentSchema = (entity: string) => {\n return schemas.find((item: any) => {\n return item.name === entity\n })\n}\n\nexport const currentRoleNames = (locale: any) => {\n return roleNames[locale] ?? roleNames['en-US']\n}\n\nexport function statusToError(error: ErrorResponse) {\n if (!error.response) {\n throw error\n }\n\n const { response } = error as AxiosError\n const { status } = response!\n\n if (status === 401) {\n throw new AuthenticationError(error)\n }\n\n if (status === 403) {\n throw new ForbiddenError(error)\n }\n\n if (status === 400) {\n throw new UserInputError(error)\n }\n\n throw error\n}\n\n```"
}
] |
code_storefront-permissions_60062765
|
[
{
"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 storefront-permissions/node/resolvers/index.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/naming-convention */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { deleteRole, saveRole } from './Mutations/Roles'\nimport { sessionWatcher } from './Mutations/Settings'\nimport {\n addCostCenterToUser,\n addOrganizationToUser,\n addUser,\n deleteUser,\n ignoreB2BSessionData,\n impersonateUser,\n saveUser,\n setActiveUserByOrganization,\n setCurrentOrganization,\n updateUser,\n setCurrentPriceTable,\n} from './Mutations/Users'\nimport { getFeaturesByModule, listFeatures } from './Queries/Features'\nimport { getRole, hasUsers, listRoles } from './Queries/Roles'\nimport { getAppSettings, getSessionWatcher } from './Queries/Settings'\nimport {\n checkCustomerSchema,\n checkImpersonation,\n checkUserPermission,\n getActiveUserByEmail,\n getAllUsersByEmail,\n getB2BUserById,\n getOrganizationsByEmail,\n getOrganizationsPaginatedByEmail,\n getUser,\n getUserByEmail,\n listAllUsers,\n listUsers,\n listUsersPaginated,\n} from './Queries/Users'\nimport { Routes } from './Routes'\n\nexport const resolvers = {\n Mutation: {\n addCostCenterToUser,\n addOrganizationToUser,\n addUser,\n deleteRole,\n deleteUser,\n ignoreB2BSessionData,\n impersonateUser,\n saveRole,\n saveUser,\n sessionWatcher,\n setActiveUserByOrganization,\n setCurrentOrganization,\n updateUser,\n setCurrentPriceTable,\n },\n Query: {\n checkCustomerSchema,\n checkImpersonation,\n checkUserPermission,\n getActiveUserByEmail,\n getAppSettings,\n getB2BUser: getB2BUserById,\n getFeaturesByModule,\n getOrganizationsByEmail,\n getOrganizationsPaginatedByEmail,\n getRole,\n getSessionWatcher,\n getUser,\n getUserByEmail,\n getUsersByEmail: getAllUsersByEmail,\n hasUsers,\n listAllUsers,\n listFeatures,\n listRoles,\n listUsers,\n listUsersPaginated,\n },\n Routes,\n}\n\n```"
}
] |
code_storefront-permissions_c5f524c9
|
[
{
"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 storefront-permissions/node/utils/metrics/changeTeam.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Metric } from '../../clients/metrics'\nimport { B2B_METRIC_NAME, sendMetric } from '../../clients/metrics'\n\ntype ChangeTeamFieldsMetric = {\n date: string\n user_id: string\n user_role: string\n user_email: string\n new_org_id: string\n new_cost_center_id: string\n}\n\nexport class ChangeTeamMetric implements Metric {\n public readonly description: string\n public readonly kind: string\n public readonly account: string\n public readonly fields: ChangeTeamFieldsMetric\n public readonly name = B2B_METRIC_NAME\n\n constructor(account: string, fields: ChangeTeamFieldsMetric) {\n this.account = account\n this.fields = fields\n this.kind = 'change-team-graphql-event'\n this.description = 'User change team/organization - Graphql'\n }\n}\n\nexport type ChangeTeamParams = {\n account: string\n userId: string\n userRole: string\n userEmail: string\n orgId: string\n costCenterId: string\n}\n\nconst buildMetric = (metricParams: ChangeTeamParams): ChangeTeamMetric => {\n return new ChangeTeamMetric(metricParams.account, {\n date: new Date().toISOString(),\n user_id: metricParams.userId,\n user_role: metricParams.userRole,\n user_email: metricParams.userEmail,\n new_org_id: metricParams.orgId,\n new_cost_center_id: metricParams.costCenterId,\n })\n}\n\nexport const sendChangeTeamMetric = async (metricParams: ChangeTeamParams) => {\n try {\n const metric = buildMetric(metricParams)\n\n await sendMetric(metric)\n } catch (error) {\n console.warn('Unable to log metrics', error)\n }\n}\n\n```"
}
] |
code_storefront-permissions_27ee10a8
|
[
{
"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 storefront-permissions/node/resolvers/Mutations/Profiles.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { currentSchema } from '../../utils'\nimport { getProfileByRole } from '../Queries/Profiles'\n\nconst config: any = currentSchema('b2b_profiles')\n\nexport const saveProfile = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n try {\n const { id, roleId, features } = params\n const check: any = getProfileByRole(_, { roleId }, ctx)\n\n if (!check.length) {\n const ret = await masterdata.createOrUpdateEntireDocument({\n dataEntity: config.name,\n fields: { roleId, features },\n id,\n schema: config.version,\n })\n\n return { status: 'success', message: '', id: ret.DocumentId }\n }\n\n return {\n message: `There's a profile already associated to this Role`,\n status: 'error',\n }\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.saveProfile-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const deleteProfile = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n try {\n await masterdata.deleteDocument({ dataEntity: config.name, id: params.id })\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.deleteProfile-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\n```"
}
] |
code_storefront-permissions_af56a435
|
[
{
"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 storefront-permissions/node/resolvers/Mutations/Settings.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { getAppId } from '../Queries/Settings'\n\nexport const sessionWatcher = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n const app: string = getAppId()\n\n const settings: any = await vbase.getJSON('b2b_settings', app).catch(() => {\n return {}\n })\n\n const { active } = params\n\n settings.sessionWatcher = { active }\n\n return vbase\n .saveJSON('b2b_settings', app, settings)\n .then(() => true)\n .catch((error) => {\n logger.error({\n error,\n message: 'sessionWatcher.saveSessionWatcherError',\n })\n\n return false\n })\n}\n\n```"
}
] |
code_storefront-permissions_b3f6ddad
|
[
{
"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 storefront-permissions/node/resolvers/Mutations/Roles.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { currentRoleNames, Slugify, toHash } from '../../utils'\nimport { ROLES_VBASE_ID } from '../../utils/constants'\nimport { groupByRole } from '../Queries/Features'\nimport { searchRoles } from '../Queries/Roles'\n\nexport const saveRole = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n try {\n const { id, name, features } = params\n const locked = params.locked ?? false\n const data: any = { name, features, locked }\n\n if (params.slug) {\n data.slug = params.slug\n } else if (!id && !params.slug) {\n data.slug = Slugify(name)\n }\n\n const roles = await searchRoles(null, ctx)\n const role = roles.find((item) => item.slug === data.slug)\n\n await vbase.saveJSON('b2b_roles', ROLES_VBASE_ID, [\n ...roles.filter((item) => item.slug !== data.slug),\n {\n features,\n id: role?.id ? role.id : data.id ?? data.slug,\n locked,\n name,\n slug: data.slug,\n },\n ])\n\n return { status: 'success', message: '', id: data.slug }\n } catch (error) {\n logger.error({\n error,\n message: 'Roles.saveRole-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nconst onlyModules = (obj: any) => {\n return obj.map(({ module }: any) => {\n return { module }\n })\n}\n\nexport const syncRoles = async (ctx: Context) => {\n const newRoles: any = []\n // Get role names based on the location\n const roleNames = currentRoleNames(ctx.vtex.tenant?.locale)\n // List all features grouped by Role\n const groups = await groupByRole(ctx)\n\n // List all roles from VB\n const roles: any = await searchRoles(null, ctx)\n\n groups?.forEach((role: any) => {\n const [slug] = Object.getOwnPropertyNames(role)\n\n let currRole: any = {}\n const roleIndex = roles.findIndex((o: any) => o.slug === slug)\n\n if (roleIndex === -1) {\n currRole = {\n features: role[slug],\n locked: true,\n name: roleNames[slug],\n slug,\n }\n } else if (\n toHash(onlyModules(role[slug])) !==\n toHash(onlyModules(roles[roleIndex].features))\n ) {\n // Compare features\n const currModules: any = roles[roleIndex].features\n\n const newModules = role[slug].filter((m: any) => {\n return (\n roles[roleIndex].features.findIndex(\n (i: any) => i.module === m.module\n ) === -1\n )\n })\n\n newModules.forEach((m: any) => {\n currModules.push(m)\n })\n\n currRole = {\n ...roles[roleIndex],\n features: currModules,\n }\n }\n\n if (currRole.name) {\n newRoles.push(currRole)\n }\n })\n\n const oldRoles = roles.filter((old: any) => {\n return newRoles.findIndex((n: any) => n.slug === old.slug) === -1\n })\n\n const mergedRoles = oldRoles.concat(newRoles)\n\n const promise: any = []\n\n mergedRoles.forEach((role: any) => {\n promise.push(saveRole(role.id ?? null, role, ctx))\n })\n\n return Promise.all(promise).then(() => mergedRoles)\n}\n\nexport const deleteRole = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n try {\n const roles = await searchRoles(null, ctx)\n\n await vbase.saveJSON(\n 'b2b_roles',\n ROLES_VBASE_ID,\n roles.filter((item) => item.id !== params.id)\n )\n\n return { status: 'success', message: '', id: params.id }\n } catch (error) {\n logger.error({\n error,\n message: 'Roles.deleteRole-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\n```"
}
] |
code_storefront-permissions_6e27849d
|
[
{
"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 storefront-permissions/node/resolvers/Mutations/Users.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { currentSchema } from '../../utils'\nimport { CUSTOMER_SCHEMA_NAME } from '../../utils/constants'\nimport type { ChangeTeamParams } from '../../utils/metrics/changeTeam'\nimport { sendChangeTeamMetric } from '../../utils/metrics/changeTeam'\nimport {\n getAllUsersByEmail,\n getOrganizationsByEmail,\n getUserByEmailOrgIdAndCostId,\n} from '../Queries/Users'\n\nconst config: any = currentSchema('b2b_users')\n\nconst MAX_RETRY = 5\nconst RETRY_BACKOFF_FACTOR_MS = 100\nconst MAX_BACKOFF_MS = 1000\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\nconst setChangeSession = async (\n sessionParameters: any,\n countRetry = 0\n): Promise<void> => {\n const {\n context: {\n clients: { session },\n vtex: { logger },\n },\n publicKey,\n value,\n sessionCookie,\n } = sessionParameters\n\n try {\n await session.updateSession(publicKey, value, [], sessionCookie)\n } catch (error) {\n logger.error({\n error,\n message: 'setChangeSession.error',\n attempt: countRetry,\n })\n\n if (countRetry < MAX_RETRY) {\n countRetry++\n const backoff = Math.min(\n 2 ** (countRetry - 1) * RETRY_BACKOFF_FACTOR_MS,\n MAX_BACKOFF_MS\n )\n\n await delay(backoff)\n\n return setChangeSession(sessionParameters, countRetry)\n }\n }\n}\n\nconst addUserToMasterdata = async ({\n masterdata,\n params: { name, email },\n}: {\n masterdata: any\n params: { name: string; email: string }\n}) => {\n const names = name.split(' ')\n const [firstName] = names\n\n names.shift()\n const lastName = names.length > 0 ? names.join(' ') : firstName // if it gets the lastName empty, it'll repeat the firstName to avoid errors on the checkout\n const { DocumentId } = await masterdata\n .createDocument({\n dataEntity: CUSTOMER_SCHEMA_NAME,\n fields: {\n email,\n firstName,\n lastName,\n },\n })\n .then((response: { DocumentId: string }) => {\n return response\n })\n .catch((error: any) => {\n if (error.response?.data?.Message === 'duplicated entry') {\n return masterdata\n .searchDocuments({\n dataEntity: CUSTOMER_SCHEMA_NAME,\n fields: ['id'],\n pagination: {\n page: 1,\n pageSize: 1,\n },\n where: `email=${email}`,\n })\n .then((res: [{ id: string }]) => {\n return { DocumentId: res[0].id }\n })\n }\n\n throw error\n })\n\n return DocumentId\n}\n\nexport const getUser = async ({\n masterdata,\n params: { email, id, userId },\n}: any) => {\n const where = id || userId ? `id=${id || userId}` : `email=${email}`\n\n return masterdata\n .searchDocuments({\n dataEntity: config.name,\n fields: [\n 'id',\n 'email',\n 'name',\n 'orgId',\n 'clId',\n 'costId',\n 'canImpersonate',\n 'roleId',\n 'userId',\n 'active',\n 'selectedPriceTable',\n ],\n pagination: {\n page: 1,\n pageSize: 1,\n },\n schema: config.version,\n where,\n })\n .then((res: any) => {\n return res.length > 0 ? res[0] : null\n })\n .catch(() => null)\n}\n\nconst updateUserFields = async ({ masterdata, fields, id }: any) => {\n const { DocumentId } = await masterdata\n .createOrUpdateEntireDocument({\n dataEntity: config.name,\n fields,\n id,\n schema: config.version,\n })\n .then((response: { DocumentId: string }) => {\n return response\n })\n .catch((error: any) => {\n if (error.response.status < 400) {\n return {\n DocumentId: id,\n }\n }\n\n throw error\n })\n\n return DocumentId\n}\n\nconst addSelectedPriceTableToB2bUser = async ({\n masterdata,\n fields,\n id,\n}: any) => {\n const { DocumentId } = await masterdata\n .createOrUpdatePartialDocument({\n dataEntity: config.name,\n fields,\n id,\n schema: config.version,\n })\n .then((response: { DocumentId: string }) => {\n return response\n })\n .catch((error: any) => {\n if (error.response.status < 400) {\n return {\n DocumentId: id,\n }\n }\n\n throw error\n })\n\n return DocumentId\n}\n\nconst createPermission = async ({ masterdata, params }: any) => {\n const {\n roleId,\n canImpersonate,\n name,\n email,\n userId,\n clId,\n orgId,\n costId,\n id,\n } = params\n\n await masterdata\n .createOrUpdateEntireDocument({\n dataEntity: config.name,\n fields: {\n canImpersonate,\n clId,\n costId,\n email,\n name,\n orgId,\n roleId,\n userId,\n },\n id,\n schema: config.version,\n })\n .then((response: { DocumentId: string }) => {\n return response\n })\n .catch((error: any) => {\n if (error.response.status < 400) {\n return {\n DocumentId: id,\n }\n }\n\n throw error\n })\n}\n\nexport const addUser = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata, lm },\n vtex: { logger },\n } = ctx\n\n try {\n const costCenter = await ctx.clients.organizations.getCostCenterById(\n params.costId\n )\n\n // before adding an user to a cost center we check if the cost\n // center exists and if it has a valid name, otherwise both\n // login and UI might break.\n if (\n !costCenter?.data?.getCostCenterById?.name ||\n params.orgId !== costCenter?.data?.getCostCenterById?.organization\n ) {\n throw new Error(`Invalid cost center`)\n }\n\n const cId = await addUserToMasterdata({ masterdata, params })\n\n const organizations = await getOrganizationsByEmail(\n _,\n { email: params.email },\n ctx\n )\n\n if (\n organizations &&\n Array.isArray(organizations) &&\n organizations?.find(\n (org: any) => org.orgId === params.orgId && org.costId === params.costId\n )\n ) {\n return {\n message: `Email already exists in the organization and cost center`,\n status: 'duplicated-organization',\n }\n }\n\n await createPermission({\n lm,\n masterdata,\n params: {\n ...params,\n clId: cId,\n },\n })\n\n return { status: 'success', message: '', id: cId }\n } catch (error) {\n logger.error({\n error,\n message: 'addUser.error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const updateUser = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata, lm },\n vtex: { logger },\n } = ctx\n\n try {\n // check if new user already exists in CL and create profile if not\n if (!params.clId) {\n params.clId = await addUserToMasterdata({ masterdata, params })\n }\n\n await createPermission({\n lm,\n masterdata,\n params,\n })\n\n return { status: 'success', message: '', id: params.clId }\n } catch (error) {\n logger.error({\n error,\n message: 'updateUser.error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const deleteUserProfile = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const { ids } = params\n\n try {\n const users: any = []\n\n ids.forEach((id: string) => {\n users.push(\n masterdata.createOrUpdatePartialDocument({\n dataEntity: config.name,\n fields: { roleId: '' },\n id,\n schema: config.version,\n })\n )\n })\n\n const result = await Promise.all(users)\n .then((response: any) => {\n return response\n })\n .catch((error: any) => {\n if (error.response.status >= 400) {\n throw error\n }\n\n logger.error({\n error,\n message: 'deleteUserProfile.error',\n })\n\n return []\n })\n\n return {\n id: result\n .map((item: { DocumentId: string }) => item.DocumentId)\n .join(','),\n message: '',\n status: result.length > 0 ? 'success' : 'error',\n }\n } catch (error) {\n logger.error({\n error,\n message: 'deleteUserProfile.error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const deleteUser = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const { id } = params\n\n try {\n await masterdata.deleteDocument({\n dataEntity: config.name,\n id,\n })\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'deleteUser.error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const impersonateUser = async (_: any, params: any, ctx: Context) => {\n const {\n vtex: { logger, sessionToken },\n } = ctx\n\n const { userId } = params\n\n try {\n await setChangeSession({\n context: ctx,\n publicKey: 'impersonate',\n value: userId,\n sessionCookie: sessionToken,\n })\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'impersonateUser.error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\n/**\n *\n * Persist the user in the database\n *\n * @deprecated\n *\n * @param _\n * @param params\n * @param ctx\n */\nexport const saveUser = async (_: any, params: any, ctx: Context) => {\n return updateUser(_, params, ctx)\n}\n\nexport const addOrganizationToUser = async (\n _: any,\n params: any,\n ctx: Context\n) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const { userId, orgId, roleId, costId } = params\n\n const user = await getUser({ masterdata, params: { userId } })\n\n if (!user) {\n throw new Error('User not found')\n }\n\n try {\n const {\n canImpersonate,\n clId,\n email,\n name,\n roleId: roleIdUser,\n userId: id,\n } = user\n\n return await addUser(\n _,\n {\n active: false,\n canImpersonate,\n clId,\n costId,\n email,\n name,\n orgId,\n roleId: roleId || roleIdUser,\n userId: id,\n },\n ctx\n )\n } catch (error) {\n logger.error({\n error,\n message: 'addOrganizationToUser.error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const addCostCenterToUser = async (\n _: any,\n params: any,\n ctx: Context\n) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const { userId, costId } = params\n\n const user = await getUser({ masterdata, params: { userId } })\n\n if (!user) {\n throw new Error('User not found')\n }\n\n try {\n const {\n roleId,\n canImpersonate,\n name,\n email,\n userId: id,\n clId,\n orgId,\n } = user\n\n return await addUser(\n _,\n {\n active: false,\n canImpersonate,\n clId,\n costId,\n email,\n name,\n orgId,\n roleId,\n userId: id,\n },\n ctx\n )\n } catch (error) {\n logger.error({\n error,\n message: 'addCostCenterToUser.error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const setActiveUserByOrganization = async (\n _: any,\n params: any,\n ctx: Context\n) => {\n const {\n clients: { masterdata, session },\n vtex: { logger, adminUserAuthToken, sessionToken },\n } = ctx\n\n let userId = null\n\n if (adminUserAuthToken) {\n userId = params.userId\n } else {\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 currentUserEmail =\n sessionData?.namespaces?.profile?.email?.value ?? params.email\n\n const userByEmail = (await getUserByEmailOrgIdAndCostId(\n masterdata,\n {\n email: currentUserEmail,\n costId: params.costId,\n orgId: params.orgId,\n },\n ctx\n )) as any\n\n userId = userByEmail\n ? userByEmail.id\n : sessionData?.namespaces?.['storefront-permissions']?.userId?.value\n }\n\n const user = await getUser({ masterdata, params: { userId } })\n\n if (!user) {\n throw new Error('User not found')\n }\n\n await updateUserFields({\n fields: { ...user, active: true },\n id: userId,\n masterdata,\n })\n\n const users = await getAllUsersByEmail(_, { email: user.email }, ctx)\n\n try {\n const promises = users.map(async (userSecondary: any) => {\n if (userSecondary.id !== user.id) {\n await updateUserFields({\n fields: {\n ...userSecondary,\n active: false,\n },\n id: userSecondary.id,\n masterdata,\n })\n }\n })\n\n await Promise.all(promises)\n } catch (error) {\n logger.error({\n error,\n message: 'setActiveUserById.error',\n })\n }\n}\n\nexport const setCurrentOrganization = async (\n _: any,\n params: any,\n ctx: Context\n) => {\n const {\n vtex: { logger },\n cookies,\n request,\n } = ctx\n\n const sessionCookie =\n cookies.get('vtex_session') ?? request.header?.sessiontoken\n\n const { sessionData } = ctx.vtex as any\n\n const { orgId, costId } = params\n\n const {\n email: { value: email },\n } = sessionData.namespaces.profile\n\n const user = await getUserByEmailOrgIdAndCostId(\n _,\n { email, orgId, costId },\n ctx\n )\n\n if (!user) {\n const error =\n 'This organization/cost center is not allowed to this current user'\n\n logger.error({\n error,\n message: 'updateCurrentOrganization.error',\n })\n\n return { status: 'error', message: error }\n }\n\n try {\n await setActiveUserByOrganization(\n _,\n {\n orgId: user.orgId,\n costId: user.costId,\n userId: user.id,\n },\n ctx\n )\n\n const metricParams: ChangeTeamParams = {\n account: sessionData?.namespaces?.account?.accountName.value,\n userId: user.id,\n userEmail: email,\n orgId,\n costCenterId: costId,\n userRole: user.roleId,\n }\n\n sendChangeTeamMetric(metricParams)\n\n await setChangeSession({\n context: ctx,\n publicKey: 'b2bCurrentCostCenter',\n value: costId,\n sessionCookie,\n })\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'updateCurrentOrganization.error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const setCurrentPriceTable = async (\n _: any,\n params: { priceTable: string | null },\n ctx: Context\n) => {\n const {\n vtex: { logger },\n clients: { masterdata },\n } = ctx\n\n const { sessionData } = ctx.vtex as any\n\n try {\n let { priceTable } = params\n\n // allow setting user priceTable back to null\n if (priceTable === undefined) priceTable = null\n\n // Get current user's organization\n const {\n 'storefront-permissions': {\n organization: { value: orgId },\n userId: { value: userId },\n },\n } = sessionData.namespaces\n\n if (!orgId || !userId) {\n const error = 'User not properly authenticated with organization context'\n\n logger.error({\n error,\n message: 'setCurrentPriceTable.error.noOrgContext',\n })\n\n return { status: 'error', message: error }\n }\n\n // Get organization data to validate price table\n const organization = await ctx.clients.masterDataExtended.getDocumentById(\n 'organizations',\n orgId,\n ['priceTables']\n )\n\n if (\n priceTable != null &&\n !organization?.priceTables?.includes(priceTable)\n ) {\n const error = 'Price table not allowed for this organization'\n\n logger.error({\n error,\n message: 'setCurrentPriceTable.error.invalidPriceTable',\n priceTable,\n orgId,\n })\n\n return { status: 'error', message: error }\n }\n\n // Update user's selected price table\n await addSelectedPriceTableToB2bUser({\n masterdata,\n fields: { selectedPriceTable: priceTable },\n id: userId,\n })\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'setCurrentPriceTable.error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const ignoreB2BSessionData = async (\n _: void,\n { enabled }: { enabled: boolean },\n ctx: Context\n) => {\n const {\n cookies,\n request,\n vtex: { logger },\n } = ctx\n\n const sessionCookie =\n cookies.get('vtex_session') ?? request.header?.sessiontoken\n\n try {\n await setChangeSession({\n context: ctx,\n publicKey: 'removeB2B',\n value: enabled,\n sessionCookie,\n })\n\n return { status: 'success', message: '' }\n } catch (error) {\n logger.error({\n error,\n message: 'removeB2BSessionData.error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\n```"
}
] |
code_storefront-permissions_bce31248
|
[
{
"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 storefront-permissions/node/resolvers/Queries/Profiles.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { currentSchema } from '../../utils'\nimport { listRoles } from './Roles'\n\nconst config: any = currentSchema('b2b_profiles')\n\nexport const getProfile = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n try {\n const { id } = params\n\n return await masterdata.getDocument({\n dataEntity: config.name,\n fields: ['id', 'roleId', 'features'],\n id,\n })\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.getProfile-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const getProfileByRole = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const { roleId } = params\n\n try {\n const [profile] = await masterdata.searchDocuments({\n dataEntity: config.name,\n fields: ['id', 'roleId', 'features'],\n pagination: { page: 1, pageSize: 50 },\n schema: config.version,\n where: `roleId=${roleId}`,\n })\n\n return profile\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.getProfileByRole-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const listProfiles = async (_: any, __: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n try {\n const roles: any = await listRoles(_, __, ctx)\n\n const profiles: any = await masterdata.searchDocuments({\n dataEntity: config.name,\n fields: ['id', 'roleId', 'features', 'scoped'],\n pagination: { page: 1, pageSize: 50 },\n schema: config.version,\n })\n\n return profiles.map((profile: any) => {\n return {\n ...profile,\n name: roles.find((role: any) => {\n return role.id === profile.roleId\n })?.name,\n }\n })\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.listProfiles-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\n```"
}
] |
code_storefront-permissions_e04db7f9
|
[
{
"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 storefront-permissions/node/resolvers/Queries/Settings.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport schemas from '../../mdSchema'\nimport { toHash } from '../../utils'\nimport { syncRoles } from '../Mutations/Roles'\nimport type { ErrorResponse } from '../Routes/utils'\n\nexport const getAppId = (): string => {\n const app = process.env.VTEX_APP_ID\n const [appName] = String(app).split('@')\n\n return appName\n}\n\nexport const getAppSettings = async (_: any, __: any, ctx: Context) => {\n const {\n clients: { masterdata, vbase },\n vtex: { logger },\n } = ctx\n\n const app: string = getAppId()\n\n const settings = (await vbase.getJSON('b2b_settings', app).catch(() => {\n return {}\n })) as {\n adminSetup: {\n schemaHash?: string | null\n roles?: string[] | boolean | null\n }\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: Array<Promise<boolean>> = []\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((error: ErrorResponse) => {\n if (error.response.status !== 304) {\n throw error\n }\n\n return true\n })\n )\n })\n\n await Promise.all(updates)\n .then(() => {\n settings.adminSetup.schemaHash = currHash\n })\n .catch((error) => {\n if (error.response.status !== 304) {\n logger.error({\n error,\n message: 'getAppSettings-error',\n })\n\n throw new Error(error)\n }\n })\n\n await vbase.saveJSON('b2b_settings', app, settings)\n }\n\n const roles: any = await syncRoles(ctx).catch(() => [])\n\n settings.adminSetup.roles = !!roles.length\n\n return settings\n}\n\nexport const getSessionWatcher = async (_: any, __: any, ctx: Context) => {\n const {\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n const app: string = getAppId()\n\n const settings: any = await vbase.getJSON('b2b_settings', app).catch(() => {\n return {}\n })\n\n try {\n return settings?.sessionWatcher?.active ?? true\n } catch (error) {\n logger.error({\n error,\n message: 'getSessionWatcher.getSessionWatcherError',\n })\n\n return { status: 'error', message: error }\n }\n}\n\n```"
}
] |
code_storefront-permissions_30da278d
|
[
{
"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 storefront-permissions/node/resolvers/Queries/Features.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst sanitizeFeatures = (settings: any) => {\n const ret: any = []\n\n settings.forEach((app: any) => {\n const [module] = app.declarer.split('@')\n\n if (app[module]?.features) {\n const { name, features } = app[module]\n\n ret.push({\n features,\n module,\n name,\n })\n }\n })\n\n return ret\n}\n\nexport const getFeaturesByModule = async (\n _: any,\n params: any,\n ctx: Context\n) => {\n const { module } = params\n\n if (ctx.vtex?.settings?.dependenciesSettings) {\n const settingsFiles: any = sanitizeFeatures(\n ctx.vtex.settings.dependenciesSettings\n )\n\n return settingsFiles.find((app: any) => {\n return app.module === module\n })\n }\n\n return null\n}\n\nexport const listFeatures = async (_: any, __: any, ctx: Context) => {\n let result = []\n\n if (ctx.vtex?.settings?.dependenciesSettings) {\n const settingsFiles: any = sanitizeFeatures(\n ctx.vtex.settings.dependenciesSettings\n )\n\n if (settingsFiles?.length) {\n result = settingsFiles\n } else if (Object.getOwnPropertyNames(settingsFiles).length) {\n result = [settingsFiles]\n }\n }\n\n return result\n}\n\nconst extractRoles = (settings: any) => {\n const roles: any = {}\n\n const apps = settings.length ? settings : [settings]\n\n apps.forEach((app: any) => {\n app.features?.forEach((feature: any) => {\n feature.roles?.forEach((role: string) => {\n roles[role] = true\n })\n })\n })\n\n return Object.getOwnPropertyNames(roles)\n}\n\nconst featuresByRole = (settings: any, role: string) => {\n const features: any = []\n const apps = settings.length ? settings : [settings]\n\n apps.forEach((app: any) => {\n app.features?.forEach((feature: any) => {\n feature.roles?.forEach((current: string) => {\n if (current === role) {\n const moduleIndex = features.findIndex((f: any) => {\n return f.module === app.module\n })\n\n if (moduleIndex === -1) {\n features.push({\n features: [feature.value],\n module: app.module,\n })\n } else {\n features[moduleIndex].features.push(feature.value)\n }\n }\n })\n })\n })\n\n return features\n}\n\nexport const groupByRole = async (ctx: Context) => {\n const settings = await listFeatures(null, null, ctx)\n const roles = extractRoles(settings)\n const features: any = []\n\n roles.forEach((role: string) => {\n features.push({ [role]: featuresByRole(settings, role) })\n })\n\n return features\n}\n\n```"
}
] |
code_storefront-permissions_6b93be66
|
[
{
"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 storefront-permissions/node/resolvers/Queries/Roles.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { currentRoleNames, currentSchema } from '../../utils'\nimport { ROLES_VBASE_ID } from '../../utils/constants'\nimport { getUserByRole } from './Users'\n\nconst sorting = (a: any, b: any) => (a.name > b.name ? 1 : -1)\nconst config: any = currentSchema('b2b_roles')\n\nconst getDefaultRoles = (locale: string) => {\n const roleNames = currentRoleNames(locale)\n const values = [] as Array<{\n features: string[]\n id: string\n locked: boolean\n name: string\n slug: string\n }>\n\n Object.keys(roleNames).forEach((slug) => {\n values.push({\n features: [],\n id: slug,\n locked: true,\n name: roleNames[slug],\n slug,\n })\n })\n\n return values.sort(sorting)\n}\n\nexport const searchRoles = async (_: any, ctx: Context) => {\n const {\n clients: { vbase, masterdata },\n } = ctx\n\n try {\n const roles: any[] = await vbase.getJSON('b2b_roles', ROLES_VBASE_ID)\n\n roles.sort(sorting)\n\n return roles\n } catch (error) {\n if (error?.response?.status === 404) {\n const options: any = {\n dataEntity: config.name,\n fields: ['id', 'name', 'features', 'locked', 'slug'],\n pagination: { page: 1, pageSize: 50 },\n schema: config.version,\n }\n\n const roles = await masterdata.searchDocuments(options)\n\n return !roles || roles.length === 0\n ? getDefaultRoles(ctx.vtex.tenant?.locale ?? '')\n : roles\n }\n\n throw new Error(error)\n }\n}\n\nexport const getRole = async (_: any, params: any, ctx: Context) => {\n const {\n vtex: { logger },\n } = ctx\n\n try {\n const { id, slug } = params\n\n const role: any = id\n ? (await searchRoles(null, ctx)).find((item: any) => item.id === id)\n : (await searchRoles(null, ctx)).find((item: any) => item.slug === slug)\n\n return role\n } catch (error) {\n logger.error({\n error,\n message: 'Roles.getRole',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const hasUsers = async (_: any, params: any, ctx: Context) => {\n const role: any = await getRole(\n null,\n { id: params.id, slug: params.slug },\n ctx\n )\n\n if (role?.id) {\n const usersByRole: any = await getUserByRole(_, { id: role.id }, ctx)\n\n return usersByRole.length > 0\n }\n\n return false\n}\n\nexport const listRoles = async (_: any, __: any, ctx: Context) => {\n const {\n vtex: { logger },\n } = ctx\n\n try {\n return await searchRoles(null, ctx)\n } catch (e) {\n logger.error({\n error: e,\n message: 'Roles.listRoles',\n })\n\n return { status: 'error', message: e }\n }\n}\n\n```"
}
] |
code_storefront-permissions_f598bb1d
|
[
{
"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 storefront-permissions/node/resolvers/Queries/Users.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { removeVersionFromAppId } from '@vtex/api'\n\nimport type { GetOrganizationsPaginatedByEmailResponse } from '../../typings/custom'\nimport { currentSchema } from '../../utils'\nimport {\n CUSTOMER_REQUIRED_FIELDS,\n CUSTOMER_SCHEMA_NAME,\n} from '../../utils/constants'\nimport GraphQLError from '../../utils/GraphQLError'\nimport { getRole } from './Roles'\n\nconst config: any = currentSchema('b2b_users')\n\nconst PAGINATION = {\n page: 1,\n pageSize: 50,\n}\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 const where = `email=${email}`\n const resp = await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: config.name,\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: config.version,\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\n return false\n}\n\nasync function processChunks(\n requests: Array<() => Promise<any>>,\n index = 0,\n responses: any[] = [],\n maxConcurrency = 30\n): Promise<any[]> {\n if (index >= requests.length) {\n return responses\n }\n\n const chunk = requests.slice(index, index + maxConcurrency)\n const chunkResponses = await Promise.all(chunk.map((fn) => fn()))\n\n return processChunks(requests, index + maxConcurrency, [\n ...responses,\n ...chunkResponses,\n ])\n}\n\nexport const getAllUsers = async ({\n masterdata,\n logger,\n where,\n}: {\n masterdata: any\n logger: any\n where?: string\n}) => {\n try {\n const initialResp = await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: config.name,\n fields: ['id'],\n pagination: { page: 1, pageSize: PAGINATION.pageSize },\n schema: config.version,\n ...(where ? { where } : {}),\n })\n\n const totalItems = initialResp.pagination.total\n const totalPages = Math.ceil(totalItems / PAGINATION.pageSize)\n\n const requests = Array.from(\n { length: totalPages },\n (_, i) => async () =>\n masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: config.name,\n fields: [\n 'id',\n 'roleId',\n 'clId',\n 'email',\n 'name',\n 'orgId',\n 'costId',\n 'userId',\n 'canImpersonate',\n 'active',\n ],\n pagination: { page: i + 1, pageSize: PAGINATION.pageSize },\n schema: config.version,\n sort: 'id asc',\n ...(where ? { where } : {}),\n })\n )\n\n const responses = await processChunks(requests)\n\n const users = responses.reduce((acc: any[], resp: { data: any }) => {\n acc.push(...resp.data)\n\n return acc\n }, [])\n\n return users\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.getAllUsersByEmail-error',\n })\n throw new Error(error)\n }\n}\n\nexport const getAllUsersByEmail = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const { email, orgId, costId } = params\n\n let where = `email=${email}`\n\n if (orgId) {\n where += ` AND orgId=${orgId}`\n }\n\n if (costId) {\n where += ` AND costId=${costId}`\n }\n\n return getAllUsers({ masterdata, logger, where })\n}\n\nexport const getActiveUserByEmail = async (\n _: any,\n params: any,\n ctx: Context\n) => {\n const {\n vtex: { logger },\n } = ctx\n\n try {\n const users = await getAllUsersByEmail(null, params, ctx)\n const activeUser = users.find((user: any) => user.active)\n\n const userFound = activeUser || users[0]\n\n if (!userFound) {\n logger.warn({\n email: params.email,\n message: `getActiveUserByEmail-userNotFound`,\n })\n }\n\n return {\n ...userFound,\n email: userFound?.email || '',\n name: userFound?.name || '',\n }\n } catch (error) {\n logger.error({\n error,\n message: `getActiveUserByEmail-error`,\n })\n\n return { message: error, status: 'error' }\n }\n}\n\n/**\n * @deprecated\n * @param _\n * @param params\n * @param ctx\n */\nexport const getUserByEmail = async (_: any, params: any, ctx: Context) => {\n const user = await getActiveUserByEmail(_, params, ctx)\n\n return [user]\n}\n\nexport const getUserById = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterDataExtended },\n vtex: { logger },\n } = ctx\n\n try {\n const { id } = params\n\n const cl: any = await masterDataExtended.getDocumentById(\n CUSTOMER_SCHEMA_NAME,\n id,\n [\n 'email',\n 'firstName',\n 'lastName',\n 'document',\n 'documentType',\n 'phone',\n 'homePhone',\n 'corporateName',\n 'tradeName',\n 'corporateDocument',\n 'stateInscription',\n 'corporatePhone',\n 'isCorporate',\n ]\n )\n\n return cl ?? null\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.getUserById-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const checkCustomerSchema = async (_: any, __: any, ctx: Context) => {\n const {\n clients: { schema },\n } = ctx\n\n const latestSchema = await schema.getLatestSchema(CUSTOMER_SCHEMA_NAME)\n\n if (!latestSchema) {\n return { status: 'error', message: 'Schema not found' }\n }\n\n const {\n schema: { required },\n } = latestSchema\n\n const diff = required.filter(\n (value: any) => !CUSTOMER_REQUIRED_FIELDS.includes(value)\n )\n\n return diff.length <= 0\n}\n\nexport const getB2BUserById = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n try {\n const { id } = params\n\n const user = await masterdata.getDocument({\n dataEntity: config.name,\n fields: [\n 'id',\n 'roleId',\n 'name',\n 'email',\n 'clId',\n 'orgId',\n 'costId',\n 'userId',\n 'canImpersonate',\n 'selectedPriceTable',\n ],\n id,\n })\n\n return user\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.getUserById-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const getUser = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n try {\n const { id } = params\n\n const cl: any = await masterdata.getDocument({\n dataEntity: CUSTOMER_SCHEMA_NAME,\n fields: ['firstName', 'lastName', 'email', 'userId'],\n id,\n })\n\n if (!cl) {\n return null\n }\n\n const user: any = await masterdata.searchDocuments({\n dataEntity: config.name,\n fields: [\n 'id',\n 'roleId',\n 'clId',\n 'orgId',\n 'costId',\n 'userId',\n 'canImpersonate',\n ],\n pagination: { page: 1, pageSize: 90 },\n schema: config.version,\n where: `clId=${id}`,\n })\n\n return user.length\n ? {\n ...user[0],\n email: cl.email,\n name: `${cl.firstName} ${cl.lastName}`,\n }\n : {\n canImpersonate: false,\n clId: id,\n email: cl.email,\n name: `${cl.firstName} ${cl.lastName}`,\n roleId: null,\n userId: cl.userId,\n }\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.getUser-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const getUserByRole = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const { id } = params\n\n try {\n return await masterdata.searchDocuments({\n dataEntity: config.name,\n fields: [\n 'id',\n 'roleId',\n 'userId',\n 'orgId',\n 'costId',\n 'name',\n 'email',\n 'canImpersonate',\n ],\n pagination: { page: 1, pageSize: 90 },\n schema: config.version,\n where: `roleId=${id}`,\n })\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.getUserByRole-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const listAllUsers = async (_: any, __: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n return getAllUsers({ masterdata, logger })\n}\n\nexport const listUsers = async (\n _: any,\n {\n organizationId = '',\n costCenterId = '',\n roleId = '',\n }: { organizationId: string; costCenterId: string; roleId: string },\n ctx: Context\n) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n let res: any = []\n\n const whereArray: string[] = []\n\n if (organizationId) {\n whereArray.push(`orgId=${organizationId}`)\n }\n\n if (costCenterId) {\n whereArray.push(`costId=${costCenterId}`)\n }\n\n if (roleId) {\n whereArray.push(`roleId=${roleId}`)\n }\n\n const where = whereArray.join(' AND ')\n\n try {\n res = await masterdata.searchDocuments({\n dataEntity: config.name,\n fields: [\n 'id',\n 'roleId',\n 'userId',\n 'clId',\n 'orgId',\n 'costId',\n 'name',\n 'email',\n 'canImpersonate',\n ],\n pagination: { page: 1, pageSize: 50 },\n schema: config.version,\n ...(where && { where }),\n })\n\n return res\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.listUsers-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const listUsersPaginated = async (\n _: any,\n {\n organizationId = '',\n costCenterId = '',\n roleId = '',\n page = 1,\n pageSize = 25,\n search = '',\n sortOrder = 'asc',\n sortedBy = 'email',\n }: {\n organizationId: string\n costCenterId: string\n roleId: string\n page: number\n pageSize: number\n search: string\n sortOrder: string\n sortedBy: string\n },\n ctx: Context\n) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const whereArray: string[] = []\n\n if (organizationId) {\n whereArray.push(`orgId=${organizationId}`)\n }\n\n if (costCenterId) {\n whereArray.push(`costId=${costCenterId}`)\n }\n\n if (roleId) {\n whereArray.push(`roleId=${roleId}`)\n }\n\n let whereSearchFields: any[] = []\n\n if (search && search.length > 0) {\n const fields = ['email']\n\n whereSearchFields = fields.map((field) => `${field}=\"*${search}*\"`)\n }\n\n let where = `${whereArray.join(' AND ')}`\n\n if (whereSearchFields.length > 0) {\n if (where.length > 0) {\n where += ' AND '\n }\n\n where += `(${whereSearchFields.join(' OR ')})`\n }\n\n try {\n return await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: config.name,\n fields: [\n 'id',\n 'roleId',\n 'userId',\n 'clId',\n 'orgId',\n 'costId',\n 'name',\n 'email',\n 'canImpersonate',\n ],\n pagination: { page, pageSize },\n schema: config.version,\n sort: `${sortedBy} ${sortOrder}`,\n ...(where && { where }),\n })\n } catch (error) {\n logger.error({\n error,\n message: 'Profiles.listUsersPaginated-error',\n })\n\n return { status: 'error', message: error }\n }\n}\n\nconst getRoleAndPermissionsByEmail = async ({\n email,\n module,\n skipError = false,\n ctx,\n}: {\n email: string\n module: string\n skipError: boolean\n ctx: Context\n}) => {\n const {\n vtex: { logger },\n } = ctx\n\n const defaultResponse = {\n permissions: [],\n role: {\n id: '',\n name: '',\n slug: '',\n },\n }\n\n if (!email) {\n return defaultResponse\n }\n\n const userData: any = await getUserByEmail(null, { email }, ctx)\n\n if (!userData.length && !skipError) {\n logger.warn({\n email,\n message: `getRoleAndPermissionsByEmail-userNotFound`,\n })\n throw new Error('User not found')\n }\n\n if (!userData.length) {\n return defaultResponse\n }\n\n const userRole: any = await getRole(null, { id: userData[0].roleId }, ctx)\n\n if (!userRole && !skipError) {\n logger.warn({\n message: `getRoleAndPermissionsByEmail-roleNotFound`,\n roleId: userData[0].roleId,\n })\n\n throw new Error('Role not found')\n }\n\n if (!userRole) {\n return defaultResponse\n }\n\n const currentModule = userRole.features?.find((feature: any) => {\n return feature.module === module\n })\n\n return {\n permissions: currentModule?.features || [],\n role: {\n id: userRole.id,\n name: userRole.name,\n slug: userRole.slug,\n },\n }\n}\n\nexport const checkUserPermission = async (\n _: any,\n params: any,\n ctx: Context\n) => {\n const {\n vtex: { logger },\n } = ctx\n\n const { sessionData, sender }: any = ctx.vtex\n\n const skipError = params?.skipError ?? false\n\n if (!sessionData?.namespaces && !skipError) {\n logger.warn({\n message: `checkUserPermission-userNotAuthenticated`,\n })\n throw new GraphQLError(\n 'User not authenticated, make sure the query is private',\n {\n logLevel: 'warn',\n }\n )\n }\n\n if (!sender && !skipError) {\n logger.warn({\n message: `checkUserPermission-senderNotFound`,\n })\n throw new GraphQLError(\n 'Sender not available, make sure the query is private',\n {\n logLevel: 'warn',\n }\n )\n }\n\n const authEmail =\n sessionData?.namespaces?.authentication?.storeUserEmail?.value\n\n const profileEmail = sessionData?.namespaces?.profile?.email?.value\n\n const defaultResponse = {\n permissions: [],\n role: {\n id: '',\n name: '',\n slug: '',\n },\n }\n\n if (!sender) {\n return defaultResponse\n }\n\n const module = removeVersionFromAppId(sender)\n\n const authPermissions = await getRoleAndPermissionsByEmail({\n ctx,\n email: authEmail,\n module,\n skipError: true,\n })\n\n const profilePermissions =\n profileEmail && authEmail !== profileEmail\n ? await getRoleAndPermissionsByEmail({\n ctx,\n email: profileEmail,\n module,\n skipError: true,\n })\n : defaultResponse\n\n return {\n permissions: [\n ...new Set([\n ...authPermissions.permissions,\n ...profilePermissions.permissions,\n ]),\n ],\n role: authPermissions.role.id\n ? authPermissions.role\n : profilePermissions.role,\n }\n}\n\nexport const checkImpersonation = async (_: any, __: any, ctx: Context) => {\n const {\n clients: { profileSystem, fullSessions },\n vtex: { logger },\n } = ctx\n\n const { sessionData }: any = ctx.vtex\n const { request }: any = ctx\n\n if (!sessionData?.namespaces) {\n logger.warn({\n message: `checkImpersonation-userNotAuthenticated`,\n })\n throw new Error('User not authenticated, make sure the query is private')\n }\n\n const profile = sessionData?.namespaces?.profile\n const sfp = sessionData?.namespaces['storefront-permissions']\n\n const allSessions = await fullSessions.getSessions({\n headers: {\n cookie: `VtexIdclientAutCookie=${request.headers.vtexidclientautcookie};vtex_session=${request.headers['x-vtex-session']}`,\n },\n })\n\n const authEmail =\n allSessions?.namespaces?.authentication?.storeUserEmail?.value ??\n allSessions?.namespaces?.authentication?.adminUserEmail?.value\n\n let response = null\n\n if (\n authEmail &&\n profile?.email?.value !== authEmail &&\n sfp?.storeUserId?.value &&\n profile?.id?.value &&\n sfp?.storeUserId?.value === profile?.id?.value\n ) {\n const userData: any = await profileSystem\n .getProfileInfo(profile.id.value)\n .catch(() => null)\n\n if (!userData) {\n response = { error: 'User not found' }\n } else {\n response = {\n email: userData.email,\n firstName: userData.firstName,\n lastName: userData.lastName,\n userId: userData.userId,\n }\n }\n }\n\n return response\n}\n\n/**\n * @deprecated\n * @param _\n * @param params\n * @param ctx\n */\nexport const getUsersByEmail = async (_: any, params: any, ctx: Context) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const { email } = params\n\n try {\n return await masterdata.searchDocuments({\n dataEntity: config.name,\n fields: [\n 'id',\n 'roleId',\n 'clId',\n 'email',\n 'name',\n 'orgId',\n 'costId',\n 'userId',\n 'canImpersonate',\n 'active',\n ],\n pagination: { page: 1, pageSize: 50 },\n schema: config.version,\n where: `email = \"${email}\"`,\n })\n } catch (error) {\n logger.error({\n error,\n message: `getUsersByEmail-error`,\n })\n throw new Error(error)\n }\n}\n\nexport const getOrganizationsByEmail = async (\n _: any,\n params: any,\n ctx: Context\n) => {\n const {\n vtex: { logger },\n } = ctx\n\n const { email } = params\n\n try {\n return (await getAllUsersByEmail(null, { email }, ctx)).map(\n (user: any) => ({\n clId: user.clId,\n costId: user.costId,\n id: user.id,\n orgId: user.orgId,\n roleId: user.roleId,\n })\n )\n } catch (error) {\n logger.error({\n error,\n message: `getOrganizationsByEmail-error`,\n })\n\n return { status: 'error', message: error }\n }\n}\n\nexport const getOrganizationsPaginatedByEmail = async (\n _: any,\n {\n email = '',\n page = 1,\n pageSize = 25,\n }: {\n email: string\n page: number\n pageSize: number\n },\n ctx: Context\n) => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n try {\n const data: GetOrganizationsPaginatedByEmailResponse =\n await masterdata.searchDocumentsWithPaginationInfo({\n dataEntity: config.name,\n fields: ['clId', 'costId', 'id', 'orgId', 'roleId'],\n pagination: { page, pageSize },\n schema: config.version,\n where: `email = \"${email}\"`,\n })\n\n return data\n } catch (error) {\n logger.error({\n error,\n message: 'getOrganizationsPaginatedByEmail-error',\n })\n\n throw new Error(error)\n }\n}\n\ntype UserByEmail = {\n id: string\n roleId: string\n clId: string | null\n email: string | null\n name: string | null\n orgId: string | null\n costId: string | null\n userId: string | null\n canImpersonate: boolean\n active: boolean\n}\n\nexport const getUserByEmailOrgIdAndCostId = async (\n _: any,\n params: any,\n ctx: Context\n): Promise<UserByEmail | null> => {\n const {\n clients: { masterdata },\n vtex: { logger },\n } = ctx\n\n const { email, costId, orgId } = params\n\n try {\n const user = await masterdata.searchDocuments({\n dataEntity: config.name,\n fields: [\n 'id',\n 'roleId',\n 'clId',\n 'email',\n 'name',\n 'orgId',\n 'costId',\n 'userId',\n 'canImpersonate',\n 'active',\n ],\n pagination: { page: 1, pageSize: 50 },\n schema: config.version,\n where: `email = \"${email}\" AND costId = \"${costId}\" AND orgId = \"${orgId}\"`,\n })\n\n return (user[0] as UserByEmail) || null\n } catch (error) {\n logger.error({\n error,\n message: `getUsersByEmail-error`,\n })\n throw new Error(error)\n }\n}\n\n```"
}
] |
code_storefront-permissions_0f7825b6
|
[
{
"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 storefront-permissions/node/resolvers/Routes/index.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ForbiddenError } from '@vtex/api'\nimport { json } from 'co-body'\n\nimport { getRole } from '../Queries/Roles'\nimport { getSessionWatcher } from '../Queries/Settings'\nimport { generateClUser, getUserOrganizationsData } from './utils'\nimport {\n getActiveUserByEmail,\n getUserByEmail,\n getB2BUserById,\n} from '../Queries/Users'\nimport { getUser, setActiveUserByOrganization } from '../Mutations/Users'\nimport { toHash } from '../../utils'\n\nexport const Routes = {\n PROFILE_DOCUMENT_TYPE: 'cpf',\n appSettings: async (ctx: Context) => {\n const appId = process.env.VTEX_APP_ID ? process.env.VTEX_APP_ID : ''\n const { disableSellersNameFacets, disablePrivateSellersFacets } =\n await ctx.clients.apps.getAppSettings(appId)\n\n return { disableSellersNameFacets, disablePrivateSellersFacets }\n },\n checkPermissions: async (ctx: Context) => {\n const {\n vtex: { logger },\n } = ctx\n\n ctx.set('Content-Type', 'application/json')\n\n const params: any = await json(ctx.req)\n\n let response\n\n if (!params?.app) {\n logger.warn({\n message: `checkPermissions-appNotDefined`,\n params,\n })\n\n throw new Error('App not defined')\n }\n\n if (!params?.email) {\n logger.warn({\n message: `checkPermissions-emailNotDefined`,\n params,\n })\n\n throw new Error('Email not defined')\n }\n\n const userData: any = await getUserByEmail(\n null,\n { email: params.email },\n ctx\n )\n\n if (!userData.length) {\n logger.warn({\n email: params.email,\n message: `checkPermissions-userNotFound`,\n })\n\n throw new Error('User not found')\n }\n\n if (userData.length) {\n const userRole: any = await getRole(null, { id: userData[0].roleId }, ctx)\n\n if (!userRole) {\n logger.warn({\n message: `checkPermissions-roleNotFound`,\n roleId: userData[0].roleId,\n })\n throw new Error('Role not found')\n }\n\n if (userRole) {\n const currentModule = userRole.features.find((feature: any) => {\n return feature.module === params.app\n })\n\n response = {\n permissions: currentModule?.features ?? [],\n role: userRole,\n }\n }\n }\n\n ctx.response.body = response\n ctx.response.status = 200\n },\n\n setProfile: async (ctx: Context) => {\n const {\n clients: {\n organizations,\n masterdata,\n masterDataExtended,\n checkout,\n profileSystem,\n salesChannel: salesChannelClient,\n },\n req,\n vtex: { logger },\n } = ctx\n\n const response: any = {\n public: {\n facets: {\n value: '',\n },\n sc: {\n value: '',\n },\n regionId: {\n value: '',\n },\n },\n 'storefront-permissions': {\n costcenter: {\n value: '',\n },\n organization: {\n value: '',\n },\n priceTables: {\n value: '',\n },\n storeUserEmail: {\n value: '',\n },\n storeUserId: {\n value: '',\n },\n userId: {\n value: '',\n },\n hash: {\n value: '',\n },\n },\n }\n\n ctx.set('Content-Type', 'application/json')\n ctx.set('Cache-Control', 'no-cache, no-store')\n\n const isWatchActive = await getSessionWatcher(null, null, ctx)\n\n if (!isWatchActive) {\n ctx.response.body = response\n ctx.response.status = 200\n\n return\n }\n\n const promises = [] as Array<Promise<any>>\n const body: any = await json(req)\n\n const b2bImpersonate = body?.public?.impersonate?.value\n const telemarketingImpersonate = body?.impersonate?.storeUserId?.value\n const orderFormId = body?.checkout?.orderFormId?.value\n const isCorporate = true\n\n let email = body?.authentication?.storeUserEmail?.value\n let businessName = null\n let businessDocument = null\n let documentType = null\n let phoneNumber = null\n let tradeName = null\n let stateRegistration = null\n let user = null\n\n const ignoreB2B = body?.public?.removeB2B?.value\n\n if (ignoreB2B) {\n ctx.response.body = response\n ctx.response.status = 200\n\n return\n }\n\n if (email && b2bImpersonate) {\n try {\n user = (await getUser({\n masterdata,\n params: { userId: b2bImpersonate },\n })) as {\n orgId: string\n costId: string\n clId: string\n id: string\n email: string\n userId: string\n name: string\n }\n email = user.email\n let { userId } = user\n\n if (!userId) {\n userId = await profileSystem.createRegisterOnProfileSystem(\n email,\n user.name\n )\n }\n\n response['storefront-permissions'].storeUserId.value = userId\n response['storefront-permissions'].storeUserEmail.value = user.email\n } catch (error) {\n logger.error({ message: 'setProfile.getUserError', error })\n }\n } else if (telemarketingImpersonate) {\n const telemarketingEmail = body?.impersonate?.storeUserEmail?.value\n\n response['storefront-permissions'].storeUserId.value =\n telemarketingImpersonate\n response['storefront-permissions'].storeUserEmail.value =\n telemarketingEmail\n email = telemarketingEmail\n }\n\n if (!email) {\n ctx.response.body = response\n ctx.response.status = 200\n\n return\n }\n\n if (user === null) {\n user = (await getActiveUserByEmail(null, { email }, ctx).catch(\n (error) => {\n logger.warn({ message: 'setProfile.getUserByEmailError', error })\n }\n )) as {\n orgId: string\n costId: string\n clId: string\n id: string\n }\n }\n\n response['storefront-permissions'].userId.value = user?.id\n\n if (!user?.orgId || !user?.costId) {\n ctx.response.body = response\n ctx.response.status = 200\n\n return\n }\n\n response['storefront-permissions'].organization.value = user.orgId\n\n const getOrganization = async (orgId: any): Promise<any> => {\n return masterDataExtended\n .getDocumentById('organizations', orgId, [\n 'name',\n 'tradeName',\n 'status',\n 'priceTables',\n 'salesChannel',\n 'collections',\n 'sellers',\n ])\n .catch((error) => {\n logger.error({\n error,\n message: 'setProfile.graphqlGetOrganizationById',\n })\n })\n }\n\n const hash = toHash(`${user.orgId}|${user.costId}`)\n const hashChanged = body?.['storefront-permissions']?.hash?.value !== hash\n\n response['storefront-permissions'].hash.value = hash\n\n const [\n organizationResponse,\n costCenterResponse,\n salesChannels,\n marketingTagsResponse,\n b2bSettingsResponse,\n ]: Array<{\n data: any\n }> = await Promise.all([\n getOrganization(user.orgId),\n organizations.getCostCenterById(user.costId),\n salesChannelClient.getSalesChannel(),\n organizations.getMarketingTags(user.costId),\n organizations.getB2BSettings(),\n ])\n\n // Cost center validation is now handled together with organization status below\n\n let organization: any = organizationResponse\n let userOrgsData: any = null\n\n // Check if we need to fetch user organizations (for inactive org or invalid cost center)\n const costCenterInvalid = Object.values(\n costCenterResponse.data.getCostCenterById\n ).every((value) => value === null)\n\n const organizationInactive = organization.status === 'inactive'\n const needsOrgData = organizationInactive || costCenterInvalid\n\n if (needsOrgData) {\n userOrgsData = await getUserOrganizationsData(email, ctx).catch(\n (error) => {\n logger.error({\n error,\n message: 'setProfile.getUserOrganizationsData',\n })\n\n return { validCostCenterId: null, activeOrganization: null }\n }\n )\n }\n\n // Handle invalid cost center first\n if (costCenterInvalid && userOrgsData?.validCostCenterId) {\n user.costId = userOrgsData.validCostCenterId\n }\n\n // Handle inactive organization\n if (organizationInactive) {\n const validOrganization = userOrgsData?.activeOrganization\n\n if (validOrganization) {\n organization = (await getOrganization(validOrganization.id))?.data\n ?.getOrganizationById\n\n await setActiveUserByOrganization(\n null,\n {\n costId: validOrganization.costId,\n email,\n orgId: validOrganization.orgId,\n userId: validOrganization.id,\n },\n ctx\n ).catch((error) => {\n logger.warn({\n error,\n message: 'setProfile.setActiveUserByOrganizationError',\n })\n })\n } else {\n logger.warn({\n message: `setProfile-organizationInactive`,\n organizationData: organization,\n organizationId: user.orgId,\n })\n throw new ForbiddenError('Organization is inactive')\n }\n }\n\n businessName = organization.name\n tradeName = organization.tradeName\n\n if (organization.priceTables?.length) {\n const userWithPriceTable = (await getB2BUserById(\n null,\n { id: user.id },\n ctx\n )) as { selectedPriceTable: string }\n\n const selectedPriceTable = userWithPriceTable?.selectedPriceTable\n ? userWithPriceTable.selectedPriceTable\n : organization.priceTables.join(',')\n\n response[\n 'storefront-permissions'\n ].priceTables.value = `${selectedPriceTable}`\n }\n\n let facets = [] as any\n\n if (organization.collections?.length) {\n const collections = organization.collections.map(\n (collection: any) => `productClusterIds=${collection.id}`\n )\n\n facets = [...facets, ...collections]\n }\n\n if (\n organization.sellers?.length ||\n costCenterResponse?.data?.getCostCenterById?.sellers?.length\n ) {\n const sellersList =\n costCenterResponse?.data?.getCostCenterById?.sellers ??\n organization.sellers\n\n const { disableSellersNameFacets, disablePrivateSellersFacets } =\n await Routes.appSettings(ctx)\n\n if (!disableSellersNameFacets) {\n const sellersName = sellersList.map(\n (seller: any) =>\n `sellername=${seller.name\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '')}`\n )\n\n facets = [...facets, ...sellersName]\n }\n\n if (!disablePrivateSellersFacets) {\n const sellersId = sellersList.map(\n (seller: any) => `private-seller=${seller.id}`\n )\n\n facets = [...facets, ...sellersId]\n }\n }\n\n response.public.facets.value = facets ? `${facets.join(';')};` : null\n\n response['storefront-permissions'].costcenter.value = user.costId\n phoneNumber = costCenterResponse?.data?.getCostCenterById?.phoneNumber\n\n businessDocument =\n costCenterResponse.data.getCostCenterById.businessDocument?.replace(\n /[^a-zA-Z0-9]*/,\n ''\n )\n\n stateRegistration =\n costCenterResponse.data.getCostCenterById.stateRegistration\n\n // Only require CPF if cost center contains an address in Brazil\n // This is a workaround to avoid setting CPF as documentType for countries other than Brazil\n if (\n costCenterResponse?.data?.getCostCenterById?.addresses?.some(\n (address: { country: string }) => address.country === 'BRA'\n )\n ) {\n documentType = Routes.PROFILE_DOCUMENT_TYPE\n }\n\n let { salesChannel } = organization\n\n const validChannels = salesChannels.data.filter(\n (channel: any) => channel.IsActive\n )\n\n if (\n !salesChannel?.length ||\n !validChannels?.find(\n (validSalesChannel: any) =>\n String(validSalesChannel.Id) === salesChannel.toString()\n )\n ) {\n if (validChannels.length) {\n salesChannel = validChannels[0].Id\n }\n }\n\n const salesChannelPromise = []\n\n if (salesChannel) {\n salesChannelPromise.push(\n checkout\n .updateSalesChannel(orderFormId, salesChannel)\n .catch((error) => {\n logger.error({\n error,\n message: 'setProfile.updateSalesChannel',\n })\n })\n )\n response.public.sc.value = salesChannel.toString()\n }\n\n if (hashChanged && orderFormId) {\n try {\n const {\n uiSettings: { clearCart },\n } = b2bSettingsResponse?.data?.getB2BSettings ?? {\n uiSettings: { clearCart: null },\n }\n\n if (clearCart) {\n await Promise.all(salesChannelPromise)\n await checkout.clearCart(orderFormId)\n }\n } catch (error) {\n logger.error({\n error,\n message: 'setProfile.clearCart',\n })\n }\n }\n\n if (\n costCenterResponse?.data?.getCostCenterById?.addresses?.length &&\n orderFormId\n ) {\n const [address] = costCenterResponse.data.getCostCenterById.addresses\n\n const marketingTags: any =\n marketingTagsResponse?.data?.getMarketingTags?.tags\n\n try {\n const [regionId] = await checkout.getRegionId(\n address.country,\n address.postalCode,\n salesChannel.toString(),\n address.geoCoordinates\n )\n\n if (regionId?.id) {\n response.public.regionId = {\n value: regionId.id,\n }\n }\n } catch (error) {\n logger.error({\n error,\n message: 'setProfile.getRegionId',\n })\n }\n\n promises.push(\n checkout\n .updateOrderFormMarketingData(orderFormId, {\n attachmentId: 'marketingData',\n marketingTags: marketingTags || [],\n utmCampaign: user.orgId,\n utmMedium: user.costId,\n })\n .catch((error) => {\n logger.error({\n error,\n message: 'setProfile.updateOrderFormMarketingDataError',\n })\n })\n )\n\n promises.push(\n checkout\n .updateOrderFormShipping(orderFormId, {\n address: {\n ...address,\n geoCoordinates: address.geoCoordinates ?? [],\n isDisposable: true,\n },\n clearAddressIfPostalCodeNotFound: false,\n })\n .catch((error) => {\n logger.error({\n error,\n message: 'setProfile.updateOrderFormShippingError',\n })\n })\n )\n }\n\n const clUser = await generateClUser({\n businessDocument,\n businessName,\n clId: user?.clId,\n ctx,\n phoneNumber,\n stateRegistration,\n tradeName,\n isCorporate,\n })\n\n if (clUser && orderFormId) {\n const phoneNumberFormatted =\n phoneNumber || clUser.phone || clUser.homePhone || `+1${'0'.repeat(10)}`\n\n promises.push(\n checkout\n .updateOrderFormProfile(orderFormId, {\n ...clUser,\n businessDocument: businessDocument || clUser.businessDocument,\n documentType: documentType ?? undefined,\n phone: phoneNumberFormatted,\n stateInscription:\n stateRegistration || clUser.stateInscription || '0'.repeat(9),\n })\n .catch((error) => {\n logger.error({\n error,\n message: 'setProfile.updateOrderFormProfileError',\n })\n })\n )\n }\n\n // Don't await promises, to avoid session timeout\n Promise.all(promises)\n\n logger.info({\n 'setProfile.body': JSON.stringify(body),\n 'setProfile.output': JSON.stringify(response),\n })\n\n ctx.response.body = response\n ctx.response.status = 200\n },\n}\n\n```"
}
] |
code_storefront-permissions_b8ae7b55
|
[
{
"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 storefront-permissions/node/resolvers/Routes/utils/index.ts from the storefront-permissions VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { GetOrganizationByEmailBase } from '../../../typings/custom'\nimport { getUserById } from '../../Queries/Users'\n\n// Simple in-memory cache with TTL\nconst organizationsCache = new Map<string, { data: any; timestamp: number }>()\n\nexport class ErrorResponse extends Error {\n public response: {\n status: number\n } = {\n status: 500,\n }\n}\n\nexport const QUERIES = {\n getB2BSettings: `query Settings {\n getB2BSettings {\n uiSettings {\n clearCart\n }\n }\n }`,\n getCostCenterById: `query Costcenter($id: ID!) {\n getCostCenterById(id: $id) {\n paymentTerms {\n id\n name\n }\n name\n organization\n addresses {\n addressId\n addressType\n addressQuery\n postalCode\n country\n receiverName\n city\n state\n street\n number\n complement\n neighborhood\n geoCoordinates\n reference\n }\n phoneNumber\n businessDocument\n stateRegistration\n sellers {\n id\n name\n }\n }\n }`,\n getMarketingTags: `\n query ($costId: ID!) {\n getMarketingTags(costId: $costId){\n tags\n }\n }\n `,\n getOrganizationById: `query Organization($id: ID!){\n getOrganizationById(id: $id){\n name\n tradeName\n status\n priceTables\n salesChannel\n sellers {\n id\n name\n }\n collections {\n id\n }\n }\n }`,\n getOrganizationsByEmail: `query Organizations($email: String!) {\n getOrganizationsByEmail(email: $email){\n id\n organizationStatus\n costId\n orgId\n costCenterName\n }\n }`,\n getOrganizationsPaginatedByEmail: `query OrganizationsPaginated($email: String!, $page: Int, $pageSize: Int) {\n getOrganizationsPaginatedByEmail(\n email: $email\n page: $page\n pageSize: $pageSize\n ) {\n data {\n id\n organizationStatus\n costId\n orgId\n costCenterName\n }\n pagination {\n page\n pageSize\n total\n }\n }\n }`,\n}\n\nexport const generateClUser = async ({\n clId,\n phoneNumber,\n businessName,\n businessDocument,\n tradeName,\n isCorporate,\n stateRegistration,\n ctx,\n}: {\n clId: string\n phoneNumber: string | null\n businessName: string | null\n businessDocument: string | null\n tradeName: string | null\n isCorporate: boolean\n stateRegistration: string | null\n ctx: Context\n}) => {\n const {\n vtex: { logger },\n } = ctx\n\n if (!clId) {\n return null\n }\n\n const clUser = await getUserById(null, { id: clId }, ctx).catch((error) => {\n logger.error({ message: 'setProfile.getUserByIdError', error })\n })\n\n if (!clUser) {\n return null\n }\n\n if (clUser.isCorporate === null) {\n clUser.isCorporate = false\n }\n\n if (phoneNumber) {\n clUser.phone = phoneNumber\n }\n\n if (isCorporate) {\n clUser.isCorporate = true\n clUser.document = null\n clUser.corporateName = businessName\n clUser.corporateDocument = businessDocument\n clUser.stateInscription = stateRegistration\n if (phoneNumber) {\n clUser.corporatePhone = phoneNumber\n }\n\n if (tradeName) {\n clUser.tradeName = tradeName\n }\n }\n\n return clUser\n}\n\n/**\n * Unified method to get user organizations data with caching.\n * Fetches all organizations for an email and returns relevant data for different validations.\n *\n * @param email - The email associated with the organizations.\n * @param ctx - The request context containing the organization client.\n * @param useCache - Whether to use cache (default: true)\n * @returns Object containing validCostCenterId and activeOrganization, or null values if not found.\n */\nexport const getUserOrganizationsData = async (\n email: string,\n ctx: Context,\n useCache = true\n): Promise<{\n validCostCenterId: string | null\n activeOrganization: GetOrganizationByEmailBase | null\n}> => {\n const CACHE_TTL = 1 * 60 * 1000 // 1 minutes cache\n const cacheKey = `orgs-${email}`\n\n // Check cache first\n if (useCache) {\n const cached = organizationsCache.get(cacheKey)\n\n if (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n const { validCostCenterId, activeOrganization } = cached.data\n\n return { validCostCenterId, activeOrganization }\n }\n }\n\n const { organizations } = ctx.clients\n const {\n vtex: { logger },\n } = ctx\n\n try {\n const firstResponse = await organizations.getOrganizationsPaginatedByEmail(\n email,\n 1,\n 200 // Most users have < 200 orgs, this usually gets everything in one call\n )\n\n const { data: firstPageData, pagination } =\n firstResponse?.data?.getOrganizationsPaginatedByEmail || {}\n\n if (!firstPageData?.length) {\n return { validCostCenterId: null, activeOrganization: null }\n }\n\n const allOrganizations = [...firstPageData]\n\n // Only paginate if there are more pages and we haven't found both values\n const totalPages = Math.ceil((pagination?.total || 0) / 200)\n\n if (totalPages > 1) {\n // Check if we already have what we need from first page\n const hasValidCostCenter = firstPageData.some(\n (org) => org.costCenterName !== null\n )\n\n const hasActiveOrg = firstPageData.some(\n (org) => org.organizationStatus !== 'inactive'\n )\n\n // Only fetch more pages if we're missing data\n if (!hasValidCostCenter || !hasActiveOrg) {\n // Fetch remaining pages in parallel for better performance\n const remainingPages = Array.from(\n { length: Math.min(totalPages - 1, 4) }, // Limit to 5 total pages max\n (_, i) => i + 2\n )\n\n const additionalResponses = await Promise.all(\n remainingPages.map((page) =>\n organizations\n .getOrganizationsPaginatedByEmail(email, page, 200)\n .catch((error) => {\n logger.warn({ error, message: 'Failed to fetch page', page })\n\n return null\n })\n )\n )\n\n // Combine all results\n for (const response of additionalResponses) {\n if (response?.data?.getOrganizationsPaginatedByEmail?.data) {\n allOrganizations.push(\n ...response.data.getOrganizationsPaginatedByEmail.data\n )\n }\n }\n }\n }\n\n // Find required values from all organizations\n const validCostCenterOrg = allOrganizations.find(\n (org) => org.costCenterName !== null\n )\n\n const activeOrg = allOrganizations.find(\n (org) => org.organizationStatus !== 'inactive'\n )\n\n const result = {\n validCostCenterId: validCostCenterOrg?.costId || null,\n activeOrganization: activeOrg || null,\n }\n\n // Cache the result\n if (useCache) {\n organizationsCache.set(cacheKey, {\n data: result,\n timestamp: Date.now(),\n })\n\n // Clean old cache entries periodically (simple strategy)\n if (organizationsCache.size > 100) {\n const now = Date.now()\n\n for (const [key, value] of organizationsCache.entries()) {\n if (now - value.timestamp > CACHE_TTL) {\n organizationsCache.delete(key)\n }\n }\n }\n }\n\n return result\n } catch (error) {\n logger.error({\n error,\n message: 'getUserOrganizationsData.error',\n email,\n })\n\n return { validCostCenterId: null, activeOrganization: null }\n }\n}\n\n```"
}
] |
code_tawk-to_20e6e160
|
[
{
"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 tawk-to/docs/README.md from the tawk-to VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/tawk-to) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Tawk.to\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nTawk.to first party integration app. The [solution](https://www.tawk.to/) allows you to monitor and chat with the visitors on your website, mobile app or from a free customizable page.\n\n\n\n## Configuration\n\nIt is possible to install in your store either by using App Store or the VTEX IO Toolbelt.\n\n### Using VTEX App Store\n\n1. Access the **Apps** section in your account's admin page and look for the Tawk.to 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 tawk.to's **Property ID**.\n4. Click on **Save**.\n\n### Using VTEX IO Toolbelt\n\n1. In your terminal, [install](https://vtex.io/docs/recipes/development/installing-an-app/) the `vtex.tawk-to@0.x` app. You can confirm that the app has now been installed by running `vtex ls` again.\n2. Access the **Apps** section in your account's admin page and look for the Tawk.to box. Once you find it, click on it.\n3. Fill with your tawk.to's **Property ID**.\n4. Click on **Save**.\n\n<!-- DOCS-IGNORE:start -->\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- 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<!-- DOCS-IGNORE:end -->\n\n```"
}
] |
code_tawk-to_e77ba220
|
[
{
"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 tawk-to/public/metadata/messages/es-AR.json from the tawk-to VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Tawk.to\",\n \"headline\": \"Tawk.to es una aplicación de mensajería gratuita que las empresas utilizan para crear mejores relaciones con sus clientes.\",\n \"overview\": \"Tawk.to está diseñado para aumentar la efectividad en la gestión de la experiencia de participación del cliente en línea, permitiendo que múltiples sitios y agentes en una sola interfaz chateen con los visitantes de su sitio.\\nCompatible con todos los navegadores modernos, tawk.to es un software gratuito de chat en vivo creado a partir de la creciente necesidad de que las empresas respondan en tiempo real, con personas reales.\\n\\nNo existe una versión 'premium', solo una versión rica en funciones para todos.\",\n \"features\": [\n \"Monitoreo en tiempo real\",\n \"Disparadores automatizados\",\n \"Widgets personalizables\",\n \"27 idiomas\",\n \"Notificaciónes de e-mail\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_tawk-to_34882096
|
[
{
"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 tawk-to/public/metadata/messages/pt-BR.json from the tawk-to VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Tawk.to\",\n \"headline\": \"Tawk.to é um app de mensagens gratuito que as empresas usam para criar melhores relacionamentos com seus clientes.\",\n \"overview\": \"Este aplicativo permite a integração com o serviço gratuito oferecido pelo Google de coleta de avaliações e comentários dos clientes que compraram na sua loja.\\nAs informações coletadas podem ser úteis para monitorar, por meio do Google Merchant Center, como estão sendo as experiências dos clientes, também para anúncios do Google AdWords e para apresentação de produtos no Google Shopping.\",\n \"features\": [\n \"Monitoramento em tempo real\",\n \"Gatilhos automatizados\",\n \"Widgets personalizáveis\",\n \"27 idiomas\",\n \"Notificações por e-mail\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_tawk-to_ce9300aa
|
[
{
"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 tawk-to/public/metadata/messages/en-US.json from the tawk-to VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Tawk.to\",\n \"headline\": \"Tawk.to is a free messaging app that businesses use to build better relationships with their customers.\",\n \"overview\": \"Tawk.to is designed to increase the effectiveness in managing the online customer engagement experience, enabling multiple websites and agents in a single dashboard interface to chat with the visitors on your website.\\nCompatible with all modern browsers, tawk.to is a free live chat software created out of the growing need for businesses to respond in real time, with real people.\\n\\nThere is no 'premium' version, just one feature packed version for everyone.\",\n \"features\": [\n \"Real Time Monitoring\",\n \"Automated Triggers\",\n \"Customizable Widgets\",\n \"27 Languages\",\n \"Mail Notifications\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_mycheckout-payments-service_3abd9311
|
[
{
"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 mycheckout-payments-service/test/app.e2e-spec.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { TestingModule } from '@nestjs/testing'\nimport { Test } from '@nestjs/testing'\nimport type { INestApplication } from '@nestjs/common'\nimport * as request from 'supertest'\n\nimport { AppModule } from '../src/app.module'\n\ndescribe('AppController (e2e)', () => {\n let app: INestApplication\n\n beforeEach(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile()\n\n app = moduleFixture.createNestApplication()\n await app.init()\n })\n\n it('/ (GET)', () => {\n return request(app.getHttpServer())\n .get('/')\n .expect(200)\n .expect('Hello World!')\n })\n})\n\n```"
}
] |
code_mycheckout-payments-service_ebe0a990
|
[
{
"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 mycheckout-payments-service/test/jest-e2e.json from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"moduleFileExtensions\": [\"js\", \"json\", \"ts\"],\n \"rootDir\": \".\",\n \"testEnvironment\": \"node\",\n \"testRegex\": \".e2e-spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n }\n}\n\n```"
}
] |
code_mycheckout-payments-service_d643fbc4
|
[
{
"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 mycheckout-payments-service/src/main.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { NestFactory } from '@nestjs/core'\nimport { ValidationPipe } from '@nestjs/common'\nimport { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'\n\nimport { AppModule } from './app.module'\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule)\n\n const config = new DocumentBuilder()\n .setTitle('API')\n .setDescription('Kuikpay payments')\n .setVersion('1.0')\n .build()\n const document = SwaggerModule.createDocument(app, config)\n SwaggerModule.setup('docs', app, document)\n\n app.useGlobalPipes(\n new ValidationPipe({\n whitelist: true,\n forbidNonWhitelisted: true,\n })\n )\n\n app.setGlobalPrefix('api')\n\n await app.listen(8080)\n}\n\nbootstrap()\n\n```"
}
] |
code_mycheckout-payments-service_66268fab
|
[
{
"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 mycheckout-payments-service/src/app.service.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Inject, Injectable } from '@nestjs/common'\nimport { ConfigType } from '@nestjs/config'\n// import { Db } from 'mongodb'\n\nimport config from './common/config'\n\n@Injectable()\nexport class AppService {\n constructor(\n // @Inject('MONGO') private database: Db,\n @Inject(config.KEY) private configService: ConfigType<typeof config>\n ) {}\n\n getHello(): string {\n return `Hello World!`\n }\n}\n\n```"
}
] |
code_mycheckout-payments-service_8e3bdca7
|
[
{
"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 mycheckout-payments-service/src/app.module.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Module } from '@nestjs/common'\nimport { ConfigModule } from '@nestjs/config'\nimport * as Joi from 'joi'\nimport { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'\n\nimport { AppController } from './app.controller'\nimport { AppService } from './app.service'\nimport { PaymentsModule } from './payments/payments.module'\n// import { DatabaseModule } from './database/database.module'\nimport { environments } from './common/environments'\nimport config from './common/config'\nimport { APP_GUARD } from '@nestjs/core'\n\nexport const isContainer = process.env.CONTAINER == 'docker'\nconsole.log(isContainer)\n\n@Module({\n imports: [\n PaymentsModule,\n // DatabaseModule,\n ConfigModule.forRoot({\n ...(isContainer\n ? {\n envFilePath: ['/config/.env'],\n }\n : {\n envFilePath: '.env.local',\n }),\n load: [config],\n isGlobal: true,\n validationSchema: Joi.object({\n PROXY_SERVICE_TOKEN: Joi.string().required(),\n PROXY_SERVICE_PULL: Joi.string().required(),\n PROXY_SERVICE_AUTHORIZATION: Joi.string().required(),\n PROXY_SERVICE_MERCHANT: Joi.number().required(),\n PROXY_SERVICE_API_KEY: Joi.string().required(),\n }),\n }),\n ThrottlerModule.forRoot({\n ttl: 10,\n limit: 5000,\n }),\n ],\n controllers: [AppController],\n providers: [\n AppService,\n {\n provide: APP_GUARD,\n useClass: ThrottlerGuard,\n },\n ],\n})\nexport class AppModule {}\n\n```"
}
] |
code_mycheckout-payments-service_61d4c34f
|
[
{
"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 mycheckout-payments-service/src/app.controller.spec.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { TestingModule } from '@nestjs/testing'\nimport { Test } from '@nestjs/testing'\n\nimport { AppController } from './app.controller'\nimport { AppService } from './app.service'\n\ndescribe('AppController', () => {\n let appController: AppController\n\n beforeEach(async () => {\n const app: TestingModule = await Test.createTestingModule({\n controllers: [AppController],\n providers: [AppService],\n }).compile()\n\n appController = app.get<AppController>(AppController)\n })\n\n describe('root', () => {\n it('should return \"Hello World!\"', () => {\n expect(appController.getHello()).toBe('Hello World!')\n })\n })\n})\n\n```"
}
] |
code_mycheckout-payments-service_1b0706a8
|
[
{
"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 mycheckout-payments-service/src/app.controller.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Controller, Get } from '@nestjs/common'\n\nimport { AppService } from './app.service'\n\n@Controller()\nexport class AppController {\n constructor(private readonly appService: AppService) {}\n}\n\n```"
}
] |
code_mycheckout-payments-service_9f98e261
|
[
{
"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 mycheckout-payments-service/src/database/database.module.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Module, Global } from '@nestjs/common'\nimport { ConfigType } from '@nestjs/config'\nimport { MongoClient } from 'mongodb'\nimport { MongooseModule } from '@nestjs/mongoose'\n\nimport config from '../common/config'\n\n@Global()\n@Module({\n imports: [\n MongooseModule.forRootAsync({\n useFactory: (configService: ConfigType<typeof config>) => {\n const { connection, user, password, host, port, name } =\n configService.mongo\n return {\n uri: `${connection}://${host}:${port}`,\n user,\n pass: password,\n dbName: name,\n }\n },\n inject: [config.KEY],\n }),\n ],\n providers: [\n {\n provide: 'MONGO',\n useFactory: async (configService: ConfigType<typeof config>) => {\n const { connection, user, password, host, port, name } =\n configService.mongo\n const uri = `${connection}://${user}:${password}@${host}:${port}/?authSource=admin&readPreference=primary&appname=MongoDB%20Compass&ssl=false`\n\n const client = new MongoClient(uri)\n\n await client.connect()\n\n const database = client.db(name)\n\n return database\n },\n inject: [config.KEY],\n },\n ],\n exports: ['MONGO', MongooseModule],\n})\nexport class DatabaseModule {}\n\n```"
}
] |
code_mycheckout-payments-service_3eaa2518
|
[
{
"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 mycheckout-payments-service/src/payments/payments.module.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Module } from '@nestjs/common'\nimport { MongooseModule } from '@nestjs/mongoose'\n\nimport { CardsController } from './controllers/cards.controller'\nimport { CardsService } from './services/cards.service'\nimport { Card, CardSchema } from './entities/card.entity'\nimport { PaymentsController } from './controllers/payments.controller'\nimport { PaymentsService } from './services/payments.service'\nimport { HttpModule } from '@nestjs/axios'\n\n@Module({\n imports: [\n // MongooseModule.forFeature([\n // {\n // name: Card.name,\n // schema: CardSchema,\n // },\n // ]),\n HttpModule,\n ],\n controllers: [PaymentsController],\n providers: [PaymentsService],\n})\nexport class PaymentsModule {}\n\n```"
}
] |
code_mycheckout-payments-service_b7a53a41
|
[
{
"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 mycheckout-payments-service/src/common/environments.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const environments = {\n dev: '.env',\n prod: '.prod.env',\n}\n\n```"
}
] |
code_mycheckout-payments-service_8a9ed12b
|
[
{
"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 mycheckout-payments-service/src/common/utils.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport * as crypto from 'crypto-js'\n\nexport const encryptCard = (card: any) => {\n return crypto.AES.encrypt(JSON.stringify(card), 'secret key 123').toString()\n}\n\nexport const decryptCard = (cipherCard: string) => {\n const bytes = crypto.AES.decrypt(cipherCard, 'secret key 123')\n return JSON.parse(bytes.toString(crypto.enc.Utf8))\n}\n\n```"
}
] |
code_mycheckout-payments-service_b73f972c
|
[
{
"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 mycheckout-payments-service/src/common/config.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { registerAs } from '@nestjs/config'\n\nexport default registerAs('config', () => {\n return {\n mongo: {\n user: process.env.MONGO_INITDB_ROOT_USERNAME,\n password: process.env.MONGO_INITDB_ROOT_PASSWORD,\n name: process.env.MONGO_DB,\n port: parseInt(process.env.MONGO_PORT, 10),\n host: process.env.MONGO_HOST,\n connection: process.env.MONGO_CONNECTION,\n },\n proxy: {\n token: process.env.PROXY_SERVICE_TOKEN,\n pull: process.env.PROXY_SERVICE_PULL,\n authorization: process.env.PROXY_SERVICE_AUTHORIZATION,\n merchant: process.env.PROXY_SERVICE_MERCHANT,\n key: process.env.PROXY_SERVICE_API_KEY,\n },\n }\n})\n\n```"
}
] |
code_mycheckout-payments-service_a17a73d4
|
[
{
"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 mycheckout-payments-service/src/payments/dtos/cards.dtos.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IsString, IsNotEmpty } from 'class-validator'\nimport { PartialType, ApiProperty } from '@nestjs/swagger'\n\nexport class CreateCardDto {\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n readonly token: string\n}\n\nexport class UpdateCardDto extends PartialType(CreateCardDto) {}\n\n```"
}
] |
code_mycheckout-payments-service_22c1efe4
|
[
{
"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 mycheckout-payments-service/src/payments/dtos/payments.dtos.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ApiProperty } from '@nestjs/swagger'\nimport { Type } from 'class-transformer'\nimport {\n IsNotEmpty,\n IsString,\n IsNumber,\n ValidateNested,\n IsOptional,\n} from 'class-validator'\n\nclass ProxyPCI {\n @IsString()\n @IsOptional()\n @ApiProperty()\n transactionId: string\n\n @IsString()\n @IsOptional()\n @ApiProperty()\n aliasCC: string\n\n @IsString()\n @IsOptional()\n @ApiProperty()\n aliasCVV: string\n}\n\nclass Fields {\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n holderName: string\n\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n dueDate: string\n\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n addressId: string\n}\n\nclass Transaction {\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n id: string\n\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n merchantName: string\n}\n\nexport class Payment {\n @IsNumber()\n @IsNotEmpty()\n @ApiProperty()\n paymentSystem: number\n\n @IsNumber()\n @IsNotEmpty()\n @ApiProperty()\n installments: number\n\n @IsNumber()\n @IsNotEmpty()\n @ApiProperty()\n installmentsInterestRate: number\n\n @IsNumber()\n @IsNotEmpty()\n @ApiProperty()\n installmentsValue: number\n\n @IsNumber()\n @IsNotEmpty()\n @ApiProperty()\n value: number\n\n @IsNumber()\n @IsNotEmpty()\n @ApiProperty()\n referenceValue: number\n\n @IsNotEmpty()\n @ApiProperty()\n fields: Fields\n\n @IsNotEmpty()\n @ApiProperty()\n transaction: Transaction\n\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n currencyCode: string\n}\n\nclass Order {\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n accountName: string\n\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n hostname: string\n\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n VtexChkoAuth: string\n\n @IsString()\n @IsNotEmpty()\n @ApiProperty()\n orderGroup: string\n}\n\nclass VTEX {\n @ValidateNested({ each: true })\n @Type(() => Payment)\n @ApiProperty()\n payment: Payment\n\n @ValidateNested({ each: true })\n @Type(() => Order)\n @ApiProperty()\n order: Order\n}\n\nexport class CreatePaymentDto {\n @ValidateNested({ each: true })\n @Type(() => ProxyPCI)\n @ApiProperty()\n proxy: ProxyPCI\n\n @ValidateNested({ each: true })\n @Type(() => VTEX)\n @ApiProperty()\n vtex: VTEX\n}\n\n```"
}
] |
code_mycheckout-payments-service_9443b651
|
[
{
"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 mycheckout-payments-service/src/payments/controllers/cards.controller.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Controller, Post, Delete, Param, Body } from '@nestjs/common'\nimport { ApiTags } from '@nestjs/swagger'\nimport { CardsService } from '../services/cards.service'\nimport { CreateCardDto } from '../dtos/cards.dtos'\n\n@ApiTags('cards')\n@Controller('cards')\nexport class CardsController {\n constructor(private cardsService: CardsService) {}\n\n @Post('')\n create(@Body() payload: CreateCardDto) {\n return this.cardsService.create(payload)\n }\n\n @Delete(':id')\n delete(@Param('id') id: string) {\n return this.cardsService.delete(id)\n }\n}\n\n```"
}
] |
code_mycheckout-payments-service_cb49783e
|
[
{
"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 mycheckout-payments-service/src/payments/controllers/payments.controller.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Body, Controller, Post, Headers } from '@nestjs/common'\nimport { ApiTags } from '@nestjs/swagger'\nimport { CreatePaymentDto } from '../dtos/payments.dtos'\nimport { PaymentsService } from '../services/payments.service'\n\n@ApiTags('payments')\n@Controller('payments')\nexport class PaymentsController {\n constructor(private paymentsService: PaymentsService) {}\n\n @Post('')\n create(@Body() payload: CreatePaymentDto, @Headers() headers: any) {\n return this.paymentsService.create(payload, headers)\n }\n}\n\n```"
}
] |
code_mycheckout-payments-service_2fd4708c
|
[
{
"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 mycheckout-payments-service/src/payments/services/cards.service.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Injectable, NotFoundException } from '@nestjs/common'\nimport { Model } from 'mongoose'\nimport { InjectModel } from '@nestjs/mongoose'\n\nimport { Card } from '../entities/card.entity'\nimport { CreateCardDto } from '../dtos/cards.dtos'\nimport { encryptCard, decryptCard } from 'src/common/utils'\n\n@Injectable()\nexport class CardsService {\n constructor(@InjectModel(Card.name) private cardModel: Model<Card>) {}\n\n create(payload: CreateCardDto) {\n // const newCard = {\n // holderName: 'Brian Carmona',\n // dueDate: '10/20',\n // validationCode: '125',\n // bin: '544151',\n // cardNumber: '5375204437718566',\n // }\n const newCard = decryptCard(payload.token)\n console.log(`=>>>> Desencriptar`, newCard)\n\n const card = encryptCard(newCard)\n console.log(`=>>>> Volver a encriptar`, card)\n\n return newCard\n }\n\n async findOne(id: string) {\n const card = await this.cardModel.findById(id).exec()\n\n if (!card) {\n throw new NotFoundException()\n }\n\n return card\n }\n\n async delete(id: string) {\n const deletedCard = await this.cardModel.findByIdAndDelete(id)\n\n if (!deletedCard) {\n throw new NotFoundException()\n }\n\n return {\n message: 'Registry deleted successfully',\n }\n }\n}\n\n```"
}
] |
code_mycheckout-payments-service_546cbd9c
|
[
{
"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 mycheckout-payments-service/src/payments/services/payments.service.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { HttpService } from '@nestjs/axios'\nimport { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common'\nimport { ConfigType } from '@nestjs/config'\nimport { catchError, map, of } from 'rxjs'\n\nimport { CreatePaymentDto } from '../dtos/payments.dtos'\nimport { Payment, PaymentAdditionalInfo } from '../entities/payment.entity'\nimport config from 'src/common/config'\n\n@Injectable()\nexport class PaymentsService {\n constructor(\n private httpService: HttpService,\n @Inject(config.KEY) private configService: ConfigType<typeof config>\n ) {}\n\n getEncryptedInfo(transactionId: string) {\n return this.httpService\n .get(\n `${this.configService.proxy.token}/upp/services/v1/inline/token?transactionId=${transactionId}`,\n {\n headers: {\n Authorization: `Basic ${this.configService.proxy.authorization}`,\n },\n }\n )\n .pipe(\n map((response) => response.data),\n catchError((e) => {\n throw new HttpException(\n { status: e.response.status, error: e.response.data },\n e.response.status\n )\n })\n )\n .toPromise()\n }\n\n pullProxy(\n paymentInfo: Payment,\n paymentAdditionalInfo: PaymentAdditionalInfo,\n headers: any\n ) {\n const callbackUrl = encodeURIComponent(\n `https://${paymentAdditionalInfo.hostname}/checkout/gatewayCallback/${paymentAdditionalInfo.orderGroup}/{messageCode}`\n )\n\n return this.httpService\n .post(`${this.configService.proxy.pull}/v1/pull`, [paymentInfo], {\n headers: {\n 'x-cc-merchant-id': this.configService.proxy.merchant,\n 'pci-proxy-api-key': this.configService.proxy.key,\n 'x-cc-url': `https://${paymentAdditionalInfo.accountName}.vtexpayments.com.br/api/pub/transactions/${paymentAdditionalInfo.transactionId}/payments?orderId=${paymentAdditionalInfo.orderGroup}&redirect=false&callbackUrl=${callbackUrl}`,\n 'X-VTEX-API-AppKey': headers['x-vtex-api-appkey'],\n 'X-VTEX-API-AppToken': headers['x-vtex-api-apptoken'],\n },\n })\n .pipe(\n map((response) => response.data),\n catchError((e) => {\n throw new HttpException(\n { status: e.response.status, error: e.response.data.error },\n e.response.status\n )\n })\n )\n .toPromise()\n }\n\n gatewayCallback(\n accountName: string,\n orderGroup: string,\n vtexChkoAuth: string,\n headers: any\n ) {\n return this.httpService\n .post(\n `https://${accountName}.vtexcommercestable.com.br/api/checkout/pub/gatewayCallback/${orderGroup}`,\n null,\n {\n headers: {\n Cookie: `Vtex_CHKO_Auth=${vtexChkoAuth}`,\n 'X-VTEX-API-AppKey': headers['x-vtex-api-appkey'],\n 'X-VTEX-API-AppToken': headers['x-vtex-api-apptoken'],\n },\n }\n )\n .pipe(\n map((response) => response.data),\n catchError((e) => {\n if (e.response.status !== HttpStatus.PRECONDITION_REQUIRED) {\n throw new HttpException(\n { status: e.response.status, error: e.response.data },\n e.response.status\n )\n }\n\n return of(e.response.data)\n })\n )\n .toPromise()\n }\n\n async create(payload: CreatePaymentDto, headers: any) {\n const {\n proxy: { transactionId, aliasCC, aliasCVV },\n vtex: { payment, order },\n } = payload\n\n let aliasCCValue = aliasCC\n let aliasCVVValue = aliasCVV\n\n if (transactionId) {\n const { aliasCC, aliasCVV } = await this.getEncryptedInfo(transactionId)\n if (!aliasCCValue) {\n aliasCCValue = aliasCC\n }\n aliasCVVValue = aliasCVV\n }\n\n const paymentInfo = {\n ...payment,\n fields: {\n cardNumber: aliasCCValue,\n validationCode: aliasCVVValue,\n ...payment.fields,\n },\n }\n\n await this.pullProxy(\n paymentInfo,\n {\n accountName: order.accountName,\n hostname: order.hostname,\n orderGroup: order.orderGroup,\n transactionId: payment.transaction.id,\n },\n headers\n )\n\n const respGate = await this.gatewayCallback(\n order.accountName,\n order.orderGroup,\n order.VtexChkoAuth,\n headers\n )\n\n return {\n aliasCC: aliasCCValue,\n aliasCVV: aliasCVVValue,\n gatewayCallbackResponse: respGate,\n }\n }\n}\n\n```"
}
] |
code_mycheckout-payments-service_0c249119
|
[
{
"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 mycheckout-payments-service/src/payments/entities/card.entity.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'\nimport { Document } from 'mongoose'\n\n@Schema()\nexport class Card extends Document {\n @Prop({ required: true })\n token: string\n}\n\nexport const CardSchema = SchemaFactory.createForClass(Card)\n\n```"
}
] |
code_mycheckout-payments-service_b722be3c
|
[
{
"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 mycheckout-payments-service/src/payments/entities/payment.entity.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport class Payment {\n paymentSystem: number\n installments: number\n installmentsInterestRate: number\n installmentsValue: number\n value: number\n referenceValue: number\n fields: {\n holderName: string\n cardNumber: string\n validationCode: string\n dueDate: string\n addressId: string\n }\n transaction: {\n id: string\n merchantName: string\n }\n currencyCode: string\n}\n\nexport class PaymentAdditionalInfo {\n accountName: string\n hostname: string\n orderGroup: string\n transactionId: string\n}\n\n```"
}
] |
code_mycheckout-payments-service_41d9d2c5
|
[
{
"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 mycheckout-payments-service/src/payments/controllers/test/cards.controller.spec.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { CardsController } from '../cards.controller'\n\ndescribe('CardsController', () => {\n let controller: CardsController\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n controllers: [CardsController],\n }).compile()\n\n controller = module.get<CardsController>(CardsController)\n })\n\n it('should be defined', () => {\n expect(controller).toBeDefined()\n })\n})\n\n```"
}
] |
code_mycheckout-payments-service_13c38187
|
[
{
"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 mycheckout-payments-service/src/payments/controllers/test/payments.controller.spec.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { PaymentsController } from '../payments.controller'\n\ndescribe('PaymentsController', () => {\n let controller: PaymentsController\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n controllers: [PaymentsController],\n }).compile()\n\n controller = module.get<PaymentsController>(PaymentsController)\n })\n\n it('should be defined', () => {\n expect(controller).toBeDefined()\n })\n})\n\n```"
}
] |
code_mycheckout-payments-service_7f71c6ed
|
[
{
"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 mycheckout-payments-service/src/payments/services/test/cards.service.spec.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { CardsService } from '../cards.service'\n\ndescribe('CardsService', () => {\n let service: CardsService\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [CardsService],\n }).compile()\n\n service = module.get<CardsService>(CardsService)\n })\n\n it('should be defined', () => {\n expect(service).toBeDefined()\n })\n})\n\n```"
}
] |
code_mycheckout-payments-service_8166cd18
|
[
{
"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 mycheckout-payments-service/src/payments/services/test/payments.service.spec.ts from the mycheckout-payments-service VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { PaymentsService } from '../payments.service'\n\ndescribe('PaymentsService', () => {\n let service: PaymentsService\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [PaymentsService],\n }).compile()\n\n service = module.get<PaymentsService>(PaymentsService)\n })\n\n it('should be defined', () => {\n expect(service).toBeDefined()\n })\n})\n\n```"
}
] |
code_docs-bot_e80a7934
|
[
{
"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 docs-bot/docs/README.md from the docs-bot VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n\n# Docs Bot\n \nA Github bot to enhance documentation tracking and awareness\n\n## Responsibilities \n\nDocs Bot currently has two responsibilities:\n\n1. Checks PRs for any file changes on `docs/` folder and, in case none are present, requests an explanation for not updating the documentation. If no answer is selected, the PR will get a `failed` status. There are three possible answers:\n - **Nothing new:** if the PR is a bugfix or an slight enhancement, might be the case that no extra documentation is needed, Docs Bot will understand that as a success\n - **Do it later:** sometimes the PR is an urgency and the timing for documenting is not good, this will create an issue on the central VTEX IO documentation repository [(IO Documentation)](https://github.com/vtex-apps/io-documentation). Besides that, the Docs Bot will make push the `docs/README.md` file, marking the PR as an **upcoming documentation**.\n - **Just did it:** it might also be the case that the dev forgot the documentation and later on added to the PR in another commit, that's also a success for the Docs Bot \n\n2. Checks weekly all repos in [VTEX Apps Organization](https://github.com/vtex-apps) looking for the ones that didn't implement the [Docs Builder](https://github.com/vtex-apps/io-documentation/blob/master/docs/README.md#what-is-the-docs-builder) and creates an issue for each one of them on [IO Documentation](https://github.com/vtex-apps/io-documentation). \n\n## Troubleshoot\n\n- I updated the `README.md` but the bot tells me no changes on documentation where made\n\n Docs Bot doesn't check root `README.md`, instead it checks the one located in `docs/README.md`, to understand why this is important, please refer to: [IO Documentation](https://github.com/vtex-apps/io-documentation).\n\n- The `vtex-io-docs-bot` message didn't show up when the PR was opened and the merge is blocked\n\n It's possible to force the message by making the following request:\n\n```bash\nprintf >&2 '%s: ' 'Repository Name (e.g. vtex-apps/docs-bot)'; read REPO\nprintf >&2 '%s: ' 'PR Number (e.g. 44)'; read PR_NUMBER\nprintf >&2 '%s: ' 'Commit (e.g. 19aff3cfe9be65e5d4edd326a78255be785b2674)'; read SHA\n\ncurl -X POST 'https://vtex.myvtex.com/app/docsbot/event' \\\n-H 'x-github-event: pull_request' \\\n-H 'Content-Type: application/json' \\\n--data '{\n \"action\": \"opened\",\n \"pull_request\": {\n \"number\": $PR_NUMBER,\n \"head\": {\n \"sha\": $SHA\n }\n },\n \"repository\": {\n \"full_name\": $REPO\n }\n}'\n```\n\n```"
}
] |
code_docs-bot_24ed19e7
|
[
{
"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 docs-bot/node/service.json from the docs-bot VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 2,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"routes\": {\n \"event\": {\n \"path\": \"/app/docsbot/event\",\n \"public\": true\n },\n \"schedule\": {\n \"path\": \"/app/docsbot/schedule\",\n \"public\": true\n }\n }\n}\n\n```"
}
] |
code_docs-bot_2f37064c
|
[
{
"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 docs-bot/node/package.json from the docs-bot VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"jsonwebtoken\": \"^8.5.1\",\n \"ramda\": \"^0.25.0\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"0.0.3\",\n \"@types/jsonwebtoken\": \"^8.3.3\",\n \"@types/node\": \"8.x\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"3.47.2\",\n \"tslint\": \"^5.14.0\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typescript\": \"3.5.2\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'\"\n },\n \"version\": \"0.3.0\"\n}\n\n```"
}
] |
code_docs-bot_108576b3
|
[
{
"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 docs-bot/node/index.ts from the docs-bot VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ClientsConfig, LRUCache, Service, ServiceContext } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { handleEvent } from './handlers/event'\nimport { handleSchedule } from './handlers/schedule'\n\nconst TIMEOUT_MS = 5000\n\n// Create a LRU memory cache for the Status client.\n// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.\nconst memoryCache = new LRUCache<string, any>({max: 5000})\nmetrics.trackCache('status', memoryCache)\n\n// This is the configuration for clients available in `ctx.clients`.\nconst clients: ClientsConfig<Clients> = {\n // We pass our custom implementation of the clients bag, containing the Status client.\n implementation: Clients,\n options: {\n // All IO Clients will be initialized with these options, unless otherwise specified.\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n // This key will be merged with the default options and add this cache to our Status client.\n status: {\n memoryCache,\n },\n },\n}\n\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\n type Context = ServiceContext<Clients, State>\n\n // The shape of our State object found in `ctx.state`. This is used as state bag to communicate between middlewares.\n interface State {\n code: number\n }\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service<Clients, State>({\n clients,\n routes: {\n event: [\n handleEvent,\n ],\n schedule: [\n handleSchedule,\n ],\n },\n})\n\n```"
}
] |
code_docs-bot_3834bd49
|
[
{
"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 docs-bot/node/clients/github.ts from the docs-bot VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n ExternalClient,\n InstanceOptions,\n IOContext\n} from '@vtex/api'\nimport * as jwt from 'jsonwebtoken'\n\nexport default class Github extends ExternalClient {\n private PEM: string = ''\n\n private installationID = 1428901\n private clientID = 38075\n private comitter = {\n 'email': 'docsbot@vtex.com',\n 'name': 'docs-bot',\n }\n\n private routes = {\n contents: (repo: string, filePath: string): string => `${this.routes.repo(repo)}/contents${filePath}`,\n issue: (repo: string, issueNumber: string): string => `${this.routes.issues(repo)}/${issueNumber}`,\n issueComments: (repo: string, issueNumber: string): string => `${this.routes.issue(repo, issueNumber)}/comments`,\n issues: (repo: string): string => `${this.routes.repo(repo)}/issues`,\n orgRepos: (org: string): string => `orgs/${org}/repos`,\n pull: (repo: string, prNumber: string): string => `${this.routes.pulls(repo)}/${prNumber}`,\n pullFiles: (repo: string, prNumber: string): string => `${this.routes.pull(repo, prNumber)}/files`,\n pulls: (repo: string): string => `${this.routes.repo(repo)}/pulls`,\n repo: (repo: string): string => `repos/${repo}`,\n statuses: (repo: string, sha: string): string => `${this.routes.repo(repo)}/statuses/${sha}`,\n }\n constructor(\n context: IOContext,\n options ? : InstanceOptions) {\n super('http://api.github.com/', context, options)\n }\n\n public setAppPEM(pem: string): void {\n this.PEM = pem\n }\n\n public async getOrgRepos (org: string): Promise<any> {\n let repos: any[] = []\n let page = 0\n let last = false\n\n while (!last) {\n const {data: pageRepos, headers} = await this.http.getRaw(this.routes.orgRepos(org), {\n headers: await this.getAuthHeader(),\n metric: 'get-org-repos',\n params: {\n page,\n per_page: 100,\n },\n })\n\n repos = repos.concat(pageRepos)\n page++\n last = !headers.link.includes('next')\n }\n\n return repos\n }\n\n public async getPR(repo: string, prId: string): Promise < any > {\n return this.http.get(this.routes.pull(repo, prId), {\n headers: await this.getAuthHeader(),\n metric: 'get-pr',\n })\n }\n\n public async getPRComments(repo: string, prId: string): Promise < any > {\n return this.http.get(this.routes.issueComments(repo, prId), {\n headers: await this.getAuthHeader(),\n metric: 'get-pr-comments',\n })\n }\n\n public async createCommitStatus(\n repo: string,\n description: string,\n context: string,\n state: 'error' | 'failure' | 'pending' | 'success',\n sha: string\n ): Promise < any > {\n return this.http.post(this.routes.statuses(repo, sha), {\n context,\n description,\n state,\n }, {\n headers: await this.getAuthHeader(),\n metric: 'create-commit-status',\n })\n }\n\n public async writeComment(repo: string, prId: string, body: string): Promise < any > {\n return this.http.post(\n this.routes.issueComments(repo, prId), {\n body,\n }, {\n headers: await this.getAuthHeader(),\n metric: 'write-pr-comments',\n })\n }\n\n public async createNewIssue(repo: string, title: string, body: string, labels ? : [string]): Promise < any> {\n return this.http.post(\n this.routes.issues(repo), {\n body,\n labels,\n title,\n }, {\n headers: await this.getAuthHeader(),\n metric: 'create-issue',\n })\n }\n\n public async getFileContents(repo: string, filePath: string): Promise < any > {\n const {content, sha} = await this.http.get(\n this.routes.contents(repo, filePath),\n {\n headers: await this.getAuthHeader(),\n metric: 'read-file',\n }\n )\n\n return {\n content: Buffer.from(content, 'base64').toString(),\n sha,\n }\n }\n\n public async getPRFileChanges(repo: string, pr: string): Promise <any> {\n return this.http.get(\n this.routes.pullFiles(repo, pr),\n {\n headers: await this.getAuthHeader(),\n metric: 'get-pr-files',\n }\n )\n }\n\n public async updateFileContents(repo: string, filePath: string, commitMessage: string, content:string, sha:string) {\n await this.http.put(\n this.routes.contents(repo, filePath),\n {\n committer: this.comitter,\n content: Buffer.from(content, 'binary').toString('base64'),\n message: commitMessage,\n sha,\n },\n {\n headers: await this.getAuthHeader(),\n metric: 'write-pr-comments',\n }\n )\n }\n\n private async getAccessToken(installation: number): Promise < string > {\n const headers = {\n 'Accept': 'application/vnd.github.machine-man-preview+json',\n 'Authorization': `Bearer ${this.generateJwtToken()}`,\n 'Content-Type': 'application/json',\n 'X-Vtex-Use-Https': 'true',\n }\n\n const {\n token,\n } = await this.http.post(`app/installations/${installation}/access_tokens`, {}, {\n headers,\n metric: 'get-access-token',\n })\n\n return token\n }\n\n private generateJwtToken(): string {\n const currentTime = new Date().getTime()\n\n return jwt.sign({\n exp: Math.floor(currentTime / 1000) + 300,\n iat: Math.floor(currentTime / 1000),\n iss: this.clientID,\n },\n this.PEM, {\n algorithm: 'RS256',\n }\n )\n }\n\n private async getAuthHeader(): Promise <GithubAuthHeader>{\n return {\n 'Authorization': `token ${await this.getAccessToken(this.installationID)}`,\n 'X-Vtex-Use-Https': 'true',\n }\n }\n}\n\n```"
}
] |
code_docs-bot_92cfb664
|
[
{
"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 docs-bot/node/clients/index.ts from the docs-bot VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport Github from './github'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get github() {\n return this.getOrSet('github', Github)\n }\n}\n\n```"
}
] |
code_docs-bot_55849728
|
[
{
"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 docs-bot/node/typings/global.d.ts from the docs-bot VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface GithubAuthHeader {\n Authorization: string,\n 'X-Vtex-Use-Https': string\n}\n\ninterface DocsBotConfigs {\n pem: string,\n reposWithoutReadMe: string[]\n}\n\n```"
}
] |
code_docs-bot_75cc8fe9
|
[
{
"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 docs-bot/node/utils/utils.ts from the docs-bot VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const getAppConfigs = async (ctx: Context): Promise <DocsBotConfigs> => {\n return ctx.clients.vbase.getJSON(\n 'docs-bot', 'configs'\n )\n}\n\nexport const updateConfigs = async (ctx: Context, data: any): Promise <any> => {\n const configs = await getAppConfigs(ctx)\n return ctx.clients.vbase.saveJSON(\n 'docs-bot',\n 'configs',\n {\n ...configs,\n ...data,\n }\n )\n}\n\n```"
}
] |
code_docs-bot_ffbdbfa8
|
[
{
"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 docs-bot/node/handlers/schedule.ts from the docs-bot VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n getAppConfigs,\n updateConfigs\n} from '../utils/utils'\n\nconst VTEX_APPS_ORG = 'vtex-apps'\nlet appPem: string = ''\n\nexport async function handleSchedule(ctx: Context, next: () => Promise < any > ) {\n ctx.set('cache-control', 'no-cache,no-store')\n\n noReadMeAppsJob(ctx)\n\n ctx.status = 200\n ctx.body = {message: 'started checking apps\\' docs'}\n\n await next()\n}\n\nconst noReadMeAppsJob = async (ctx: Context) => {\n const {\n pem,\n reposWithoutReadMe,\n } = await getAppConfigs(ctx)\n const gitHub = ctx.clients.github\n\n if (!appPem) {\n appPem = pem\n }\n\n await gitHub.setAppPEM(appPem)\n\n const repos = await ctx.clients.github.getOrgRepos(VTEX_APPS_ORG)\n\n for (const {full_name: repo, html_url: repoUrl} of repos) {\n try {\n await gitHub.getFileContents(repo, '/docs/README.md')\n } catch (e) {\n if (reposWithoutReadMe.includes(repo)) {\n continue\n }\n\n await gitHub.createNewIssue(\n 'vtex-apps/io-documentation',\n `${repo} has no documentation yet`,\n `[${repo}](${repoUrl}) hasn\\'t created any README file yet or is not using Docs Builder`,\n ['no-documentation']\n )\n\n reposWithoutReadMe.push(repo)\n }\n }\n\n await updateConfigs(ctx, {\n reposWithoutReadMe,\n })\n}\n\n```"
}
] |
code_docs-bot_ec28858e
|
[
{
"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 docs-bot/node/handlers/event.ts from the docs-bot VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n json\n} from 'co-body'\nimport Github from '../clients/github'\nimport { getAppConfigs } from '../utils/utils'\n\nconst ANSWER_LATER_PATTERN = '[x] I\\'ll do it later'\nlet appPem: any = null\n\nexport async function handleEvent(ctx: Context, next: () => Promise < any > ) {\n const {\n header: {\n 'x-github-event': event,\n },\n } = ctx\n\n const body = await json(ctx.req)\n\n const {\n action,\n } = body\n\n if (!appPem) {\n appPem = (await getAppConfigs(ctx)).pem\n }\n\n ctx.set('cache-control', 'no-cache,no-store')\n\n ctx.clients.github.setAppPEM(appPem)\n\n ctx.vtex.logger.info({\n body: {\n action,\n event_type: event,\n },\n subject: 'github event',\n })\n\n if (event === 'pull_request') {\n if (action === 'closed') {\n ctx.vtex.logger.info({subject: 'pr closed', ...body})\n handleClosedPullRequest(body, ctx.clients.github)\n } else if (action === 'opened') {\n ctx.vtex.logger.info({subject: 'pr opened', ...body})\n handleNewPullRequest(body, ctx.clients.github)\n } else if (action === 'synchronize') {\n ctx.vtex.logger.info({subject: 'pr synchronized', ...body})\n handleSyncPullRequest(body, ctx.clients.github)\n }\n } else if (event === 'issue_comment' && action === 'edited') {\n ctx.vtex.logger.info({subject: 'comment edited', ...body})\n handleCommentEdit(body, ctx.clients.github)\n }\n\n ctx.status = 200\n ctx.body = 'ok'\n\n await next()\n}\n\nconst handleSyncPullRequest = async (\n reqBody: any,\n gitClient: Github\n): Promise < void > => {\n const {\n pull_request: {\n number: prNumber,\n head: {\n sha,\n },\n },\n repository: {\n full_name: repoName,\n },\n } = reqBody\n\n const changedDocs = checkDocsChanges(await gitClient.getPRFileChanges(repoName, prNumber))\n\n if (changedDocs) {\n await gitClient.createCommitStatus(\n repoName,\n 'Docs in track',\n 'vtex-io/docs-outdated-select',\n 'success',\n sha\n )\n }\n}\n\nconst handleClosedPullRequest = async (\n reqBody: any,\n gitClient: Github\n): Promise < void > => {\n const {\n number: prNumber,\n pull_request: {\n title: prTitle,\n html_url: prUrl,\n merged,\n user: {\n login: prOwnerLogin,\n },\n },\n repository: {\n full_name: repoName,\n html_url: repoUrl,\n },\n } = reqBody\n\n if (!merged) {\n return\n }\n\n const comments = await gitClient.getPRComments(repoName, prNumber)\n\n for (const comment of comments) {\n const {\n user: {\n login,\n },\n body,\n } = comment\n\n if (login !== 'vtex-io-docs-bot[bot]') {\n continue\n }\n\n if (body.includes(ANSWER_LATER_PATTERN)) {\n await createUpcomingDocumentation(\n prTitle,\n prUrl,\n repoName,\n repoUrl,\n prOwnerLogin,\n prNumber,\n gitClient\n )\n\n return\n }\n }\n}\n\nconst handleNewPullRequest = async (\n reqBody: any,\n gitClient: Github\n): Promise < boolean > => {\n const {\n pull_request: {\n number: prNumber,\n head: {\n sha,\n },\n },\n repository: {\n full_name: repoName,\n },\n } = reqBody\n\n try {\n await gitClient.getFileContents(repoName, '/docs/README.md')\n } catch (e) {\n await gitClient.writeComment(\n repoName,\n prNumber,\n 'Beep boop :robot:\\n\\n' +\n 'I noticed you\\'re not using the Docs Builder properly yet, '+\n 'if you need help to set that up please go to [IO Documentation](https://github.com/vtex-apps/io-documentation)'\n )\n\n return true\n }\n\n const changedDocs = checkDocsChanges(await gitClient.getPRFileChanges(repoName, prNumber))\n\n if (!changedDocs) {\n await gitClient.writeComment(\n repoName,\n prNumber,\n 'Beep boop :robot:\\n\\n' +\n 'I noticed you didn\\'t make any changes at the `docs/` folder\\n' +\n '- [ ] There\\'s nothing new to document :thinking:\\n' +\n '- [ ] I\\'ll do it later :disappointed:\\n' +\n '\\nIn order to keep track, I\\'ll create an issue if you decide now is not a good time\\n\\n' +\n '- [ ] I just updated :tada::tada:')\n\n await gitClient.createCommitStatus(\n repoName,\n 'Forgot to select the reason for not updating docs',\n 'vtex-io/docs-outdated-select',\n 'failure',\n sha\n )\n } else {\n await gitClient.writeComment(\n repoName,\n prNumber,\n 'Beep boop :robot:\\n\\n Thank you so much for keeping our documentation up-to-date :heart:')\n\n await gitClient.createCommitStatus(\n repoName,\n 'Docs in track',\n 'vtex-io/docs-outdated-select',\n 'success',\n sha\n )\n }\n\n return true\n}\n\nconst handleCommentEdit = async (\n reqBody: any,\n gitClient: Github\n): Promise < boolean > => {\n const {\n issue: {\n number: prNumber,\n },\n repository: {\n full_name: repoName,\n },\n comment: {\n user: {\n login: commentOwner,\n },\n body,\n },\n } = reqBody\n\n if (commentOwner !== 'vtex-io-docs-bot[bot]') {\n return true\n }\n\n const {\n head: {\n sha,\n },\n } = await gitClient.getPR(repoName, prNumber)\n\n await gitClient.createCommitStatus(\n repoName,\n 'Justified docs update absence',\n 'vtex-io/docs-outdated-select',\n 'success',\n sha\n )\n\n if (!body.includes(ANSWER_LATER_PATTERN)) {\n return true\n }\n\n return true\n}\n\nconst checkDocsChanges = (fileChanges: any): boolean => {\n for (const {\n filename,\n } of fileChanges) {\n if (filename.includes('docs/')) {\n return true\n }\n }\n return false\n}\n\nconst createUpcomingDocumentation = async (\n issueTitle: string,\n issueUrl: string,\n repoName: string,\n repoUrl: string,\n editor: string,\n prNumber: string,\n gitClient: Github\n): Promise < void > => {\n const issueLinkLabel = `[${issueTitle}](${issueUrl})`\n\n const docIssue = await gitClient.createNewIssue(\n 'vtex-apps/io-documentation',\n `Upcoming docs in ${repoName}`,\n `@${editor} is going to update soon a new feature/enhancement on [${repoName}](${repoUrl})\\n` +\n `For more information go to:\\n` +\n issueLinkLabel,\n ['upcoming-docs'])\n\n await gitClient.writeComment(\n repoName,\n prNumber,\n `Beep boop :robot: That\\'s ok, I created an [issue](${docIssue.html_url}) for this so we don\\'t forget`)\n\n const readme = await gitClient.getFileContents(\n repoName,\n '/docs/README.md'\n )\n\n let updateContent = readme.content\n\n updateContent +=\n `${!updateContent.includes('Upcoming documentation') ? `\\n\\n**Upcoming documentation:**\\n` : ''}` +\n `\\n - ${issueLinkLabel}`\n\n await gitClient.updateFileContents(\n repoName,\n '/docs/README.md',\n 'Upcoming docs',\n updateContent,\n readme.sha\n )\n}\n\n```"
}
] |
code_store-image_47fee55d
|
[
{
"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 store-image/messages/it-IT.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"Mostra un elenco di immagini\",\n \"admin/editor.image-list.height.title\": \"Altezza massima per ciascuna immagine (px)\",\n \"admin/editor.image-list.images.description.title\": \"Descrizione alternativa dell'immagine\",\n \"admin/editor.image-list.images.image.title\": \"Immagine\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"Link nofollow\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"Aprire in una nuova scheda\",\n \"admin/editor.image-list.images.link.title.title\": \"Titolo del link\",\n \"admin/editor.image-list.images.link.url.title\": \"URL del link dell'immagine\",\n \"admin/editor.image-list.images.mobileImage.title\": \"Immagine per dispositivi mobili\",\n \"admin/editor.image-list.images.title.title\": \"Titolo dell'immagine\",\n \"admin/editor.image-list.images.title\": \"Immagini\",\n \"admin/editor.image-list.images.width.description\": \"Larghezza per singola immagine (% o px)\",\n \"admin/editor.image-list.images.height.title\": \"Altezza dell'immagine\",\n \"admin/editor.image-list.images.height.description\": \"Altezza dell'immagine per una singola immagine (px)\",\n \"admin/editor.image-list.images.width.title\": \"Larghezza immagine\",\n \"admin/editor.image-list.title\": \"Elenco di immagini\",\n \"admin/editor.image-slider.description\": \"Slider di immagini\",\n \"admin/editor.image-slider.slider.infinite\": \"Infinito\",\n \"admin/editor.image-slider.slider.showNavigation\": \"Mostra frecce di navigazione\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"Mostra punti di impaginazione\",\n \"admin/editor.image-slider.slider.title\": \"Opzioni dello slider\",\n \"admin/editor.image-slider.slider.usePagination\": \"Utilizza impaginazione\",\n \"admin/editor.image-slider.title\": \"Slider di immagini\",\n \"admin/editor.image.analytics.none\": \"No\",\n \"admin/editor.image.analytics.promotionId\": \"ID della promozione\",\n \"admin/editor.image.analytics.promotionName\": \"Nome della promozione\",\n \"admin/editor.image.analytics.promotionPosition\": \"Posizione creativa\",\n \"admin/editor.image.analytics.promotionProductId\": \"ID del prodotto\",\n \"admin/editor.image.analytics.promotionProductName\": \"Nome del prodotto\",\n \"admin/editor.image.analytics.provide\": \"Sì\",\n \"admin/editor.image.analytics.title\": \"Evento di \\\"Analisi\\\"\",\n \"admin/editor.store-image.alt.title\": \"Descrizione alternativa\",\n \"admin/editor.store-image.fetchpriority.auto\": \"Lascia che il browser decida la priorità\",\n \"admin/editor.store-image.fetchpriority.high\": \"Priorità alta\",\n \"admin/editor.store-image.fetchpriority.low\": \"Priorità bassa\",\n \"admin/editor.store-image.fetchpriority.title\": \"Suggerisci la priorità di caricamento\",\n \"admin/editor.store-image.loading.eager\": \"Durante il caricamento della pagina\",\n \"admin/editor.store-image.loading.lazy\": \"Quando ci si avvicina al riquadro di visualizzazione\",\n \"admin/editor.store-image.loading.title\": \"Strategia di caricamento\",\n \"admin/editor.store-image.src.title\": \"Immagine\",\n \"admin/editor.store-image.title.description\": \"Titolo da mostrare al passaggio del mouse\",\n \"admin/editor.store-image.title.title\": \"Titolo dell'immagine\",\n \"admin/editor.store-image.title\": \"Immagine\"\n}\n```"
}
] |
code_store-image_389efd2a
|
[
{
"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 store-image/messages/th-TH.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"แสดงรายการรูป\",\n \"admin/editor.image-list.height.title\": \"ความสูงมากสุดสำหรับแต่ละรูป (px)\",\n \"admin/editor.image-list.images.description.title\": \"alt text ของรูป\",\n \"admin/editor.image-list.images.image.title\": \"รูป\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"ควรเป็นลิงก์ Nofollow\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"ควรเปิดเป็นแท็บใหม่\",\n \"admin/editor.image-list.images.link.title.title\": \"คำเรียกลิงก์\",\n \"admin/editor.image-list.images.link.url.title\": \"URL ลิงก์รูป\",\n \"admin/editor.image-list.images.mobileImage.title\": \"รูปสำหรับมือถือ\",\n \"admin/editor.image-list.images.title.title\": \"ชื่อรูป\",\n \"admin/editor.image-list.images.title\": \"รูป\",\n \"admin/editor.image-list.images.width.description\": \"ความกว้างรูปสำหรับรูปหนึ่งใบ (% หรือ px)\",\n \"admin/editor.image-list.images.height.title\": \"ความสูงรูปภาพ\",\n \"admin/editor.image-list.images.height.description\": \"ความกว้างรูปสำหรับรูปหนึ่งใบ (px)\",\n \"admin/editor.image-list.images.width.title\": \"ความกว้างรูป\",\n \"admin/editor.image-list.title\": \"รายการรูป\",\n \"admin/editor.image-slider.description\": \"ตัวเลื่อนดูภาพ\",\n \"admin/editor.image-slider.slider.infinite\": \"ไม่จำกัด\",\n \"admin/editor.image-slider.slider.showNavigation\": \"แสดงลูกศรการนำทาง\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"แสดงจุดประการแบ่งหน้า\",\n \"admin/editor.image-slider.slider.title\": \"ทางเลือกตัวเลื่อน\",\n \"admin/editor.image-slider.slider.usePagination\": \"ใช้การแบ่งหน้า\",\n \"admin/editor.image-slider.title\": \"ตัวเลื่อนดูภาพ\",\n \"admin/editor.image.analytics.none\": \"ไม่\",\n \"admin/editor.image.analytics.promotionId\": \"ID โปรโมชัน\",\n \"admin/editor.image.analytics.promotionName\": \"ชื่อโปรโมชัน\",\n \"admin/editor.image.analytics.promotionPosition\": \"ตำแหน่งครีเอทีฟ\",\n \"admin/editor.image.analytics.promotionProductId\": \"รหัสผลิตภัณฑ์\",\n \"admin/editor.image.analytics.promotionProductName\": \"ชื่อผลิตภัณฑ์\",\n \"admin/editor.image.analytics.provide\": \"ใช่\",\n \"admin/editor.image.analytics.title\": \"อีเวนต์การวิเคราะห์\",\n \"admin/editor.store-image.alt.title\": \"ข้อความสำรอง\",\n \"admin/editor.store-image.fetchpriority.auto\": \"ให้เบราว์เซอร์เป็นตัวกำหนดลำดับความสำคัญ\",\n \"admin/editor.store-image.fetchpriority.high\": \"ลำดับความสำคัญสูง\",\n \"admin/editor.store-image.fetchpriority.low\": \"ลำดับความสำคัญต่ำ\",\n \"admin/editor.store-image.fetchpriority.title\": \"แนะนำลำดับความสำคัญ\",\n \"admin/editor.store-image.loading.eager\": \"เมื่อโหลดหน้าเพจ\",\n \"admin/editor.store-image.loading.lazy\": \"เมื่อใกล้เคียงกับขนาด Viewport มากกว่า\",\n \"admin/editor.store-image.loading.title\": \"กลยุทธ์การโหลด\",\n \"admin/editor.store-image.src.title\": \"รูป\",\n \"admin/editor.store-image.title.description\": \"ชื่อที่จะแสดงเมื่อลากเมาส์ผ่าน\",\n \"admin/editor.store-image.title.title\": \"ชื่อรูป\",\n \"admin/editor.store-image.title\": \"รูป\"\n}\n```"
}
] |
code_store-image_82c24726
|
[
{
"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 store-image/messages/ko-KR.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"이미지 목록 표시\",\n \"admin/editor.image-list.height.title\": \"각 이미지의 최대 높이(px)\",\n \"admin/editor.image-list.images.description.title\": \"이미지 alt 텍스트\",\n \"admin/editor.image-list.images.image.title\": \"이미지\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"nofollow 링크여야 함\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"새 탭에서 열어야 함\",\n \"admin/editor.image-list.images.link.title.title\": \"링크 제목\",\n \"admin/editor.image-list.images.link.url.title\": \"이미지 링크 URL\",\n \"admin/editor.image-list.images.mobileImage.title\": \"모바일용 이미지\",\n \"admin/editor.image-list.images.title.title\": \"이미지 제목\",\n \"admin/editor.image-list.images.title\": \"이미지\",\n \"admin/editor.image-list.images.width.description\": \"단일 이미지의 이미지 너비(% 또는 px)\",\n \"admin/editor.image-list.images.height.title\": \"이미지 높이\",\n \"admin/editor.image-list.images.height.description\": \"단일 이미지의 이미지 높이(px)\",\n \"admin/editor.image-list.images.width.title\": \"이미지 너비\",\n \"admin/editor.image-list.title\": \"이미지 목록\",\n \"admin/editor.image-slider.description\": \"이미지 슬라이더\",\n \"admin/editor.image-slider.slider.infinite\": \"무한\",\n \"admin/editor.image-slider.slider.showNavigation\": \"탐색 화살표 표시\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"페이지 번호 점 표시\",\n \"admin/editor.image-slider.slider.title\": \"슬라이더 옵션\",\n \"admin/editor.image-slider.slider.usePagination\": \"페이지 번호 사용\",\n \"admin/editor.image-slider.title\": \"이미지 슬라이더\",\n \"admin/editor.image.analytics.none\": \"아니요\",\n \"admin/editor.image.analytics.promotionId\": \"프로모션 ID\",\n \"admin/editor.image.analytics.promotionName\": \"프로모션 이름\",\n \"admin/editor.image.analytics.promotionPosition\": \"창의적 위치\",\n \"admin/editor.image.analytics.promotionProductId\": \"제품 ID\",\n \"admin/editor.image.analytics.promotionProductName\": \"제품 이름\",\n \"admin/editor.image.analytics.provide\": \"예\",\n \"admin/editor.image.analytics.title\": \"애널리틱스 이벤트\",\n \"admin/editor.store-image.alt.title\": \"대체 텍스트\",\n \"admin/editor.store-image.fetchpriority.auto\": \"브라우저에서 우선순위를 결정하게 하세요\",\n \"admin/editor.store-image.fetchpriority.high\": \"높은 우선순위\",\n \"admin/editor.store-image.fetchpriority.low\": \"낮은 우선순위\",\n \"admin/editor.store-image.fetchpriority.title\": \"우선순위 힌트 가져오기\",\n \"admin/editor.store-image.loading.eager\": \"페이지 로드 시\",\n \"admin/editor.store-image.loading.lazy\": \"뷰포트에 가까워질시\",\n \"admin/editor.store-image.loading.title\": \"로드 전략\",\n \"admin/editor.store-image.src.title\": \"이미지\",\n \"admin/editor.store-image.title.description\": \"가리키면 표시할 제목\",\n \"admin/editor.store-image.title.title\": \"이미지 제목\",\n \"admin/editor.store-image.title\": \"이미지\"\n}\n```"
}
] |
code_store-image_03615e39
|
[
{
"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 store-image/messages/ja-JP.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"画像のリストを表示する\",\n \"admin/editor.image-list.height.title\": \"それぞれの画像の最大高 (px)\",\n \"admin/editor.image-list.images.description.title\": \"画像代替テキスト\",\n \"admin/editor.image-list.images.image.title\": \"画像\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"フォローのないリンクにしてください\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"新しいタブで開いてください\",\n \"admin/editor.image-list.images.link.title.title\": \"リンクのタイトル\",\n \"admin/editor.image-list.images.link.url.title\": \"画像リンク URL\",\n \"admin/editor.image-list.images.mobileImage.title\": \"モバイル用画像\",\n \"admin/editor.image-list.images.title.title\": \"画像のタイトル\",\n \"admin/editor.image-list.images.title\": \"画像\",\n \"admin/editor.image-list.images.width.description\": \"1つの画像に対する画像幅 (% または px)\",\n \"admin/editor.image-list.images.height.title\": \"画像の高さ\",\n \"admin/editor.image-list.images.height.description\": \"1つの画像に対する画像高さ(px)\",\n \"admin/editor.image-list.images.width.title\": \"画像幅\",\n \"admin/editor.image-list.title\": \"画像リスト\",\n \"admin/editor.image-slider.description\": \"画像スライダ\",\n \"admin/editor.image-slider.slider.infinite\": \"上限なし\",\n \"admin/editor.image-slider.slider.showNavigation\": \"方向矢印を表示する\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"ページネーションドットを表示する\",\n \"admin/editor.image-slider.slider.title\": \"スライダオプション\",\n \"admin/editor.image-slider.slider.usePagination\": \"ページネーションを使う\",\n \"admin/editor.image-slider.title\": \"画像スライダ\",\n \"admin/editor.image.analytics.none\": \"いいえ\",\n \"admin/editor.image.analytics.promotionId\": \"プロモーション ID\",\n \"admin/editor.image.analytics.promotionName\": \"プロモーション名\",\n \"admin/editor.image.analytics.promotionPosition\": \"クリエイティブポジション\",\n \"admin/editor.image.analytics.promotionProductId\": \"商品ID\",\n \"admin/editor.image.analytics.promotionProductName\": \"商品名\",\n \"admin/editor.image.analytics.provide\": \"はい\",\n \"admin/editor.image.analytics.title\": \"アナリティクスイベント\",\n \"admin/editor.store-image.alt.title\": \"代替テキスト\",\n \"admin/editor.store-image.fetchpriority.auto\": \"ブラウザに優先順位を決めさせる\",\n \"admin/editor.store-image.fetchpriority.high\": \"高い優先順位\",\n \"admin/editor.store-image.fetchpriority.low\": \"低い優先順位\",\n \"admin/editor.store-image.fetchpriority.title\": \"優先順位のヒントを取得\",\n \"admin/editor.store-image.loading.eager\": \"ページ読み込み時\",\n \"admin/editor.store-image.loading.lazy\": \"ビューポートに近づいた時\",\n \"admin/editor.store-image.loading.title\": \"読み込み戦略\",\n \"admin/editor.store-image.src.title\": \"画像\",\n \"admin/editor.store-image.title.description\": \"重ねて生じされるタイトル\",\n \"admin/editor.store-image.title.title\": \"画像のタイトル\",\n \"admin/editor.store-image.title\": \"画像\"\n}\n```"
}
] |
code_store-image_acaaa2ae
|
[
{
"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 store-image/messages/bg-BG.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"Показва списък с изображения\",\n \"admin/editor.image-list.height.title\": \"Максимална височина за всяко изображение (px)\",\n \"admin/editor.image-list.images.description.title\": \"Алтернативен текст за изображение\",\n \"admin/editor.image-list.images.image.title\": \"Изображение\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"Би трябвало да е nofollow линк\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"Би трябвало да се отваря в нов раздел\",\n \"admin/editor.image-list.images.link.title.title\": \"Заглавие на линка\",\n \"admin/editor.image-list.images.link.url.title\": \"URL адрес с линк за изображението\",\n \"admin/editor.image-list.images.mobileImage.title\": \"Изображение за мобилно устройство\",\n \"admin/editor.image-list.images.title.title\": \"Заглавие на изображение\",\n \"admin/editor.image-list.images.title\": \"Изображения\",\n \"admin/editor.image-list.images.width.description\": \"Широчина на изображението за единично изображение (% или px)\",\n \"admin/editor.image-list.images.height.title\": \"Височина на изображението\",\n \"admin/editor.image-list.images.height.description\": \"Височина на изображението за едно изображение (% или px)\",\n \"admin/editor.image-list.images.width.title\": \"Широчина на изображението\",\n \"admin/editor.image-list.title\": \"Списък с изображения\",\n \"admin/editor.image-slider.description\": \"Слайдер на изображението\",\n \"admin/editor.image-slider.slider.infinite\": \"Безкрайно\",\n \"admin/editor.image-slider.slider.showNavigation\": \"Показване на навигационни стрелки\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"Показване на точки за страниране\",\n \"admin/editor.image-slider.slider.title\": \"Опции на слайдера\",\n \"admin/editor.image-slider.slider.usePagination\": \"Използване на страниране\",\n \"admin/editor.image-slider.title\": \"Слайдер на изображението\",\n \"admin/editor.image.analytics.none\": \"Не\",\n \"admin/editor.image.analytics.promotionId\": \"ИД на промоция\",\n \"admin/editor.image.analytics.promotionName\": \"Име на промоция\",\n \"admin/editor.image.analytics.promotionPosition\": \"Креативно позициониране\",\n \"admin/editor.image.analytics.promotionProductId\": \"ИД на продукт\",\n \"admin/editor.image.analytics.promotionProductName\": \"Име на продукта\",\n \"admin/editor.image.analytics.provide\": \"Да\",\n \"admin/editor.image.analytics.title\": \"Събитие за анализ\",\n \"admin/editor.store-image.alt.title\": \"Алтернативен текст\",\n \"admin/editor.store-image.fetchpriority.auto\": \"Оставете браузъра да определи приоритета\",\n \"admin/editor.store-image.fetchpriority.high\": \"Висок приоритет\",\n \"admin/editor.store-image.fetchpriority.low\": \"Нисък приоритет\",\n \"admin/editor.store-image.fetchpriority.title\": \"Извличане на подсказване за приоритет\",\n \"admin/editor.store-image.loading.eager\": \"При зареждане на страницата\",\n \"admin/editor.store-image.loading.lazy\": \"Когато е по-близо до погледа\",\n \"admin/editor.store-image.loading.title\": \"Стратегия за зареждане\",\n \"admin/editor.store-image.src.title\": \"Изображение\",\n \"admin/editor.store-image.title.description\": \"Заглавието се показва при задържане на мишката\",\n \"admin/editor.store-image.title.title\": \"Заглавие на изображението\",\n \"admin/editor.store-image.title\": \"Изображение\"\n}\n```"
}
] |
code_store-image_7c7e5752
|
[
{
"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 store-image/messages/pt.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"Exibe uma lista de imagens\",\n \"admin/editor.image-list.height.title\": \"Altura máxima de cada imagem (px)\",\n \"admin/editor.image-list.images.description.title\": \"Descrição alternativa para a imagem\",\n \"admin/editor.image-list.images.image.title\": \"Imagem\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"Link nofollow\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"Abrir em uma nova aba\",\n \"admin/editor.image-list.images.link.title.title\": \"Título para o link\",\n \"admin/editor.image-list.images.link.url.title\": \"URL do link da imagem\",\n \"admin/editor.image-list.images.mobileImage.title\": \"Imagem para dispositivos móveis\",\n \"admin/editor.image-list.images.title.title\": \"Título da imagem\",\n \"admin/editor.image-list.images.title\": \"Imagens\",\n \"admin/editor.image-list.images.width.description\": \"Largura de imagem para uma única imagem (% ou px)\",\n \"admin/editor.image-list.images.height.title\": \"Altura da imagem\",\n \"admin/editor.image-list.images.height.description\": \"Altura de imagem para uma única imagem (px)\",\n \"admin/editor.image-list.images.width.title\": \"Largura da imagem\",\n \"admin/editor.image-list.title\": \"Lista de imagens\",\n \"admin/editor.image-slider.description\": \"Slider de imagens\",\n \"admin/editor.image-slider.slider.infinite\": \"Infinito\",\n \"admin/editor.image-slider.slider.showNavigation\": \"Mostrar setas para navegação\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"Mostrar indicadores de paginação\",\n \"admin/editor.image-slider.slider.title\": \"Configurações do slider\",\n \"admin/editor.image-slider.slider.usePagination\": \"Usar paginação\",\n \"admin/editor.image-slider.title\": \"Slider de imagens\",\n \"admin/editor.image.analytics.none\": \"Não\",\n \"admin/editor.image.analytics.promotionId\": \"ID da promoção\",\n \"admin/editor.image.analytics.promotionName\": \"Nome da promoção\",\n \"admin/editor.image.analytics.promotionPosition\": \"Posição do criativo\",\n \"admin/editor.image.analytics.promotionProductId\": \"ID do produto\",\n \"admin/editor.image.analytics.promotionProductName\": \"Nome do produto\",\n \"admin/editor.image.analytics.provide\": \"Sim\",\n \"admin/editor.image.analytics.title\": \"Evento do Analytics\",\n \"admin/editor.store-image.alt.title\": \"Texto alternativo\",\n \"admin/editor.store-image.fetchpriority.auto\": \"Deixar o navegador definir a prioridade\",\n \"admin/editor.store-image.fetchpriority.high\": \"Prioridade alta\",\n \"admin/editor.store-image.fetchpriority.low\": \"Prioridade baixa\",\n \"admin/editor.store-image.fetchpriority.title\": \"Sugestão de prioridade de carga\",\n \"admin/editor.store-image.loading.eager\": \"Ao carregar a página\",\n \"admin/editor.store-image.loading.lazy\": \"Ao se aproximar da janela de visualização\",\n \"admin/editor.store-image.loading.title\": \"Estratégia de carregamento\",\n \"admin/editor.store-image.src.title\": \"Imagem\",\n \"admin/editor.store-image.title.description\": \"Título a ser mostrado ao passar o mouse pela imagem\",\n \"admin/editor.store-image.title.title\": \"Título da imagem\",\n \"admin/editor.store-image.title\": \"Imagem\"\n}\n```"
}
] |
code_store-image_453bdef2
|
[
{
"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 store-image/messages/en.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"Show a list of images\",\n \"admin/editor.image-list.height.title\": \"Maximum height for each image (px)\",\n \"admin/editor.image-list.images.description.title\": \"Image alt text\",\n \"admin/editor.image-list.images.image.title\": \"Image\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"Nofollow link\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"Open in new tab\",\n \"admin/editor.image-list.images.link.title.title\": \"Title for the link\",\n \"admin/editor.image-list.images.link.url.title\": \"Image link URL\",\n \"admin/editor.image-list.images.mobileImage.title\": \"Image for mobile\",\n \"admin/editor.image-list.images.title.title\": \"Image title\",\n \"admin/editor.image-list.images.title\": \"Images\",\n \"admin/editor.image-list.images.width.description\": \"Image width for a single image (% or px)\",\n \"admin/editor.image-list.images.height.title\": \"Image height\",\n \"admin/editor.image-list.images.height.description\": \"Image height for a single image (px)\",\n \"admin/editor.image-list.images.width.title\": \"Image width\",\n \"admin/editor.image-list.title\": \"Image List\",\n \"admin/editor.image-slider.description\": \"Image slider\",\n \"admin/editor.image-slider.slider.infinite\": \"Infinite\",\n \"admin/editor.image-slider.slider.showNavigation\": \"Show navigation arrows\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"Show pagination dots\",\n \"admin/editor.image-slider.slider.title\": \"Slider options\",\n \"admin/editor.image-slider.slider.usePagination\": \"Use pagination\",\n \"admin/editor.image-slider.title\": \"Image Slider\",\n \"admin/editor.image.analytics.none\": \"No\",\n \"admin/editor.image.analytics.promotionId\": \"Promotion ID\",\n \"admin/editor.image.analytics.promotionName\": \"Promotion name\",\n \"admin/editor.image.analytics.promotionPosition\": \"Creative position\",\n \"admin/editor.image.analytics.promotionProductId\": \"Product ID\",\n \"admin/editor.image.analytics.promotionProductName\": \"Product Name\",\n \"admin/editor.image.analytics.provide\": \"Yes\",\n \"admin/editor.image.analytics.title\": \"Analytics event\",\n \"admin/editor.store-image.alt.title\": \"Alternative text\",\n \"admin/editor.store-image.fetchpriority.auto\": \"Let the browser decide the priority\",\n \"admin/editor.store-image.fetchpriority.high\": \"High priority\",\n \"admin/editor.store-image.fetchpriority.low\": \"Low priority\",\n \"admin/editor.store-image.fetchpriority.title\": \"Fetch priority hint\",\n \"admin/editor.store-image.loading.eager\": \"When page loads\",\n \"admin/editor.store-image.loading.lazy\": \"When closer to the viewport\",\n \"admin/editor.store-image.loading.title\": \"Loading strategy\",\n \"admin/editor.store-image.src.title\": \"Image\",\n \"admin/editor.store-image.title.description\": \"Title shown on hover\",\n \"admin/editor.store-image.title.title\": \"Image title\",\n \"admin/editor.store-image.title\": \"Image\"\n}\n```"
}
] |
code_store-image_e4e355c6
|
[
{
"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 store-image/messages/ro-RO.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"Arată o listă de imagini\",\n \"admin/editor.image-list.height.title\": \"Înălțime maximă pentru fiecare imagine (px)\",\n \"admin/editor.image-list.images.description.title\": \"Text imagine alternativă\",\n \"admin/editor.image-list.images.image.title\": \"Imagine\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"Trebuie să fie un link nofollow\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"Trebuie să se deschidă într-o filă nouă\",\n \"admin/editor.image-list.images.link.title.title\": \"Titlul link-ului\",\n \"admin/editor.image-list.images.link.url.title\": \"URL link imagine\",\n \"admin/editor.image-list.images.mobileImage.title\": \"Imagini pentru mobil\",\n \"admin/editor.image-list.images.title.title\": \"Titlu imagine\",\n \"admin/editor.image-list.images.title\": \"Imagini\",\n \"admin/editor.image-list.images.width.description\": \"Lățimea maximă a imaginii pentru o singură imagine (% sau px)\",\n \"admin/editor.image-list.images.height.title\": \"Înălțime imagine\",\n \"admin/editor.image-list.images.height.description\": \"Lățimea imaginii pentru o singură imagine (px)\",\n \"admin/editor.image-list.images.width.title\": \"Lățime imagine\",\n \"admin/editor.image-list.title\": \"Listă imagine\",\n \"admin/editor.image-slider.description\": \"Glisor imagine\",\n \"admin/editor.image-slider.slider.infinite\": \"Infinit\",\n \"admin/editor.image-slider.slider.showNavigation\": \"Arată săgețile de navigare\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"Arată punctele de paginație\",\n \"admin/editor.image-slider.slider.title\": \"Opțiuni glisor\",\n \"admin/editor.image-slider.slider.usePagination\": \"Folosește paginația\",\n \"admin/editor.image-slider.title\": \"Glisor imagine\",\n \"admin/editor.image.analytics.none\": \"Nu\",\n \"admin/editor.image.analytics.promotionId\": \"ID Promoție\",\n \"admin/editor.image.analytics.promotionName\": \"Denumire Promoție\",\n \"admin/editor.image.analytics.promotionPosition\": \"Poziție creativă\",\n \"admin/editor.image.analytics.promotionProductId\": \"ID produs\",\n \"admin/editor.image.analytics.promotionProductName\": \"Denumirea produsului\",\n \"admin/editor.image.analytics.provide\": \"Da\",\n \"admin/editor.image.analytics.title\": \"Eveniment Analytics\",\n \"admin/editor.store-image.alt.title\": \"Text alternativ\",\n \"admin/editor.store-image.fetchpriority.auto\": \"Lasă browserul să decidă prioritatea\",\n \"admin/editor.store-image.fetchpriority.high\": \"Prioritate ridicată\",\n \"admin/editor.store-image.fetchpriority.low\": \"Prioritate scăzută\",\n \"admin/editor.store-image.fetchpriority.title\": \"Indicație cu privire la prioritatea de preluare\",\n \"admin/editor.store-image.loading.eager\": \"La încărcarea paginii\",\n \"admin/editor.store-image.loading.lazy\": \"Când este mai aproape de vizualizare\",\n \"admin/editor.store-image.loading.title\": \"Strategie de încărcare\",\n \"admin/editor.store-image.src.title\": \"Imagine\",\n \"admin/editor.store-image.title.description\": \"Titlul va fi afișat prin trecere\",\n \"admin/editor.store-image.title.title\": \"Titlu imagine\",\n \"admin/editor.store-image.title\": \"Imagine\"\n}\n```"
}
] |
code_store-image_33bbe5cf
|
[
{
"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 store-image/messages/context.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"Show a list of images\",\n \"admin/editor.image-list.height.title\": \"Maximum height for each image (px)\",\n \"admin/editor.image-list.images.description.title\": \"Image alt text\",\n \"admin/editor.image-list.images.image.title\": \"Image\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"Should be a nofollow link\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"Should open on new tab\",\n \"admin/editor.image-list.images.link.title.title\": \"Title for the link\",\n \"admin/editor.image-list.images.link.url.title\": \"Image link URL\",\n \"admin/editor.image-list.images.mobileImage.title\": \"Image for mobile\",\n \"admin/editor.image-list.images.title.title\": \"Image title\",\n \"admin/editor.image-list.images.title\": \"Images\",\n \"admin/editor.image-list.images.width.description\": \"Image width for a single image (% or px)\",\n \"admin/editor.image-list.images.height.title\": \"Image height\",\n \"admin/editor.image-list.images.height.description\": \"Image height for a single image (px)\",\n \"admin/editor.image-list.images.width.title\": \"Image width\",\n \"admin/editor.image-list.title\": \"Image List\",\n \"admin/editor.image-slider.description\": \"Image Slider\",\n \"admin/editor.image-slider.slider.infinite\": \"Infinite\",\n \"admin/editor.image-slider.slider.showNavigation\": \"Show navigation arrows\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"Show pagination dots\",\n \"admin/editor.image-slider.slider.title\": \"Slider options\",\n \"admin/editor.image-slider.slider.usePagination\": \"Use pagination\",\n \"admin/editor.image-slider.title\": \"Image Slider\",\n \"admin/editor.image.analytics.none\": \"No\",\n \"admin/editor.image.analytics.promotionId\": \"Promotion ID\",\n \"admin/editor.image.analytics.promotionName\": \"Promotion Name\",\n \"admin/editor.image.analytics.promotionPosition\": \"Creative position\",\n \"admin/editor.image.analytics.promotionProductId\": \"Product ID\",\n \"admin/editor.image.analytics.promotionProductName\": \"Product Name\",\n \"admin/editor.image.analytics.provide\": \"Yes\",\n \"admin/editor.image.analytics.title\": \"Analytics event\",\n \"admin/editor.store-image.alt.title\": \"Alternative text\",\n \"admin/editor.store-image.fetchpriority.auto\": \"Let the browser decide the priority.\",\n \"admin/editor.store-image.fetchpriority.high\": \"High priority\",\n \"admin/editor.store-image.fetchpriority.low\": \"Low priority\",\n \"admin/editor.store-image.fetchpriority.title\": \"Fetch priority hint\",\n \"admin/editor.store-image.loading.eager\": \"When page loads\",\n \"admin/editor.store-image.loading.lazy\": \"When closer to the viewport\",\n \"admin/editor.store-image.loading.title\": \"Loading strategy\",\n \"admin/editor.store-image.src.title\": \"Image\",\n \"admin/editor.store-image.title.description\": \"Title to be shown on hover\",\n \"admin/editor.store-image.title.title\": \"Image title\",\n \"admin/editor.store-image.title\": \"Image\"\n}\n```"
}
] |
code_store-image_d987e8c0
|
[
{
"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 store-image/messages/de-DE.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"Eine Liste von Bildern anzeigen\",\n \"admin/editor.image-list.height.title\": \"Maximale Höhe für jedes Bild (px)\",\n \"admin/editor.image-list.images.description.title\": \"Bild Alt-Text\",\n \"admin/editor.image-list.images.image.title\": \"Bild\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"Sollte ein Nofollow-Link sein\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"Soll in neuem Tab öffnen\",\n \"admin/editor.image-list.images.link.title.title\": \"Titel für den Link\",\n \"admin/editor.image-list.images.link.url.title\": \"URL des Bild-Links\",\n \"admin/editor.image-list.images.mobileImage.title\": \"Bild für Handy\",\n \"admin/editor.image-list.images.title.title\": \"Bildtitel\",\n \"admin/editor.image-list.images.title\": \"Bilder\",\n \"admin/editor.image-list.images.width.description\": \"Bildbreite für ein einzelnes Bild (% oder px)\",\n \"admin/editor.image-list.images.height.title\": \"Bildhöhe\",\n \"admin/editor.image-list.images.height.description\": \"Bildhöhe für ein einzelnes Bild (px)\",\n \"admin/editor.image-list.images.width.title\": \"Bildbreite\",\n \"admin/editor.image-list.title\": \"Bildliste\",\n \"admin/editor.image-slider.description\": \"Bilder Slider\",\n \"admin/editor.image-slider.slider.infinite\": \"Unendlich\",\n \"admin/editor.image-slider.slider.showNavigation\": \"Navigationspfeile anzeigen\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"Punktenavigation anzeigen\",\n \"admin/editor.image-slider.slider.title\": \"Slider-Optionen\",\n \"admin/editor.image-slider.slider.usePagination\": \"Seitennavigation verwenden\",\n \"admin/editor.image-slider.title\": \"Bilder Slider\",\n \"admin/editor.image.analytics.none\": \"Nein\",\n \"admin/editor.image.analytics.promotionId\": \"Promotion-ID\",\n \"admin/editor.image.analytics.promotionName\": \"Promotionsname\",\n \"admin/editor.image.analytics.promotionPosition\": \"Kreative Position\",\n \"admin/editor.image.analytics.promotionProductId\": \"Produkt-ID\",\n \"admin/editor.image.analytics.promotionProductName\": \"Produktname\",\n \"admin/editor.image.analytics.provide\": \"Ja\",\n \"admin/editor.image.analytics.title\": \"Analytik-Ereignis\",\n \"admin/editor.store-image.alt.title\": \"Alternativer Text\",\n \"admin/editor.store-image.fetchpriority.auto\": \"Lassen Sie den Browser über die Priorität entscheiden\",\n \"admin/editor.store-image.fetchpriority.high\": \"Hohe Priorität\",\n \"admin/editor.store-image.fetchpriority.low\": \"Niedrige Priorität\",\n \"admin/editor.store-image.fetchpriority.title\": \"Hinweis auf die Abrufpriorität\",\n \"admin/editor.store-image.loading.eager\": \"Wenn die Seite geladen wird\",\n \"admin/editor.store-image.loading.lazy\": \"Bei Annäherung an das Ansichtsfenster\",\n \"admin/editor.store-image.loading.title\": \"Ladestrategie\",\n \"admin/editor.store-image.src.title\": \"Bild\",\n \"admin/editor.store-image.title.description\": \"Titel, der bei Mausverschiebung angezeigt wird\",\n \"admin/editor.store-image.title.title\": \"Bildtitel\",\n \"admin/editor.store-image.title\": \"Bild\"\n}\n```"
}
] |
code_store-image_cfa061aa
|
[
{
"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 store-image/messages/fr-FR.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"Afficher une liste d’images\",\n \"admin/editor.image-list.height.title\": \"Hauteur maximale pour chaque image (px)\",\n \"admin/editor.image-list.images.description.title\": \"Texte de remplacement de l’image\",\n \"admin/editor.image-list.images.image.title\": \"Photo\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"Devrait être un lien nofollow\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"Devrait s’ouvrir dans un nouvel onglet\",\n \"admin/editor.image-list.images.link.title.title\": \"Titre pour le lien\",\n \"admin/editor.image-list.images.link.url.title\": \"URL du lien de l’image\",\n \"admin/editor.image-list.images.mobileImage.title\": \"Image pour mobile\",\n \"admin/editor.image-list.images.title.title\": \"Titre de l’mage\",\n \"admin/editor.image-list.images.title\": \"Images\",\n \"admin/editor.image-list.images.width.description\": \"Largeur de l’image pour une seule image (% ou px)\",\n \"admin/editor.image-list.images.height.title\": \"Hauteur de l'image\",\n \"admin/editor.image-list.images.height.description\": \"Hauteur de l’image pour une seule image (px)\",\n \"admin/editor.image-list.images.width.title\": \"Largeur de l’image\",\n \"admin/editor.image-list.title\": \"Liste d’images\",\n \"admin/editor.image-slider.description\": \"Curseur image\",\n \"admin/editor.image-slider.slider.infinite\": \"Infini\",\n \"admin/editor.image-slider.slider.showNavigation\": \"Afficher les flèches de navigation\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"Afficher les points de pagination\",\n \"admin/editor.image-slider.slider.title\": \"Options du curseur\",\n \"admin/editor.image-slider.slider.usePagination\": \"Utiliser la pagination\",\n \"admin/editor.image-slider.title\": \"Curseur image\",\n \"admin/editor.image.analytics.none\": \"Non\",\n \"admin/editor.image.analytics.promotionId\": \"ID de promotion\",\n \"admin/editor.image.analytics.promotionName\": \"Nom de promotion\",\n \"admin/editor.image.analytics.promotionPosition\": \"Position créative\",\n \"admin/editor.image.analytics.promotionProductId\": \"ID produit\",\n \"admin/editor.image.analytics.promotionProductName\": \"Nom du produit\",\n \"admin/editor.image.analytics.provide\": \"Oui\",\n \"admin/editor.image.analytics.title\": \"Évènement d’analyse\",\n \"admin/editor.store-image.alt.title\": \"Texte alternatif\",\n \"admin/editor.store-image.fetchpriority.auto\": \"Laisser le navigateur décider de la priorité\",\n \"admin/editor.store-image.fetchpriority.high\": \"Priorité élevée\",\n \"admin/editor.store-image.fetchpriority.low\": \"Priorité basse\",\n \"admin/editor.store-image.fetchpriority.title\": \"Récupérer l'indice de priorité\",\n \"admin/editor.store-image.loading.eager\": \"Lors du chargement de la page\",\n \"admin/editor.store-image.loading.lazy\": \"En se rapprochant de la fenêtre d'affichage\",\n \"admin/editor.store-image.loading.title\": \"Stratégie de chargement\",\n \"admin/editor.store-image.src.title\": \"Photo\",\n \"admin/editor.store-image.title.description\": \"Titre à afficher par pointage\",\n \"admin/editor.store-image.title.title\": \"Titre de l’image\",\n \"admin/editor.store-image.title\": \"Photo\"\n}\n```"
}
] |
code_store-image_f75f41da
|
[
{
"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 store-image/messages/nl-NL.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"Toon een lijst van afbeeldingen\",\n \"admin/editor.image-list.height.title\": \"Maximale hoogte voor elke afbeelding (px)\",\n \"admin/editor.image-list.images.description.title\": \"Afbeelding alt-tekst\",\n \"admin/editor.image-list.images.image.title\": \"Afbeelding\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"Moet een nofollow link zijn\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"Moet openen op een nieuwe tab\",\n \"admin/editor.image-list.images.link.title.title\": \"Titel voor de link\",\n \"admin/editor.image-list.images.link.url.title\": \"URL van afbeeldingslink\",\n \"admin/editor.image-list.images.mobileImage.title\": \"Afbeelding voor mobiel\",\n \"admin/editor.image-list.images.title.title\": \"Titel van de afbeelding\",\n \"admin/editor.image-list.images.title\": \"Afbeeldingen\",\n \"admin/editor.image-list.images.width.description\": \"Afbeeldingsbreedte voor één afbeelding (% of px)\",\n \"admin/editor.image-list.images.height.title\": \"Beeldhoogte\",\n \"admin/editor.image-list.images.height.description\": \"Beeldhoogte voor één afbeelding (px)\",\n \"admin/editor.image-list.images.width.title\": \"Afbeeldingsbreedte\",\n \"admin/editor.image-list.title\": \"Afbeeldinglijst\",\n \"admin/editor.image-slider.description\": \"Afbeelding schuifregelaar\",\n \"admin/editor.image-slider.slider.infinite\": \"Oneindig\",\n \"admin/editor.image-slider.slider.showNavigation\": \"Toon navigatiepijlen\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"Toon pagineringstippen\",\n \"admin/editor.image-slider.slider.title\": \"Schuifregelaar opties\",\n \"admin/editor.image-slider.slider.usePagination\": \"Gebruik paginering\",\n \"admin/editor.image-slider.title\": \"Afbeelding schuifregelaar\",\n \"admin/editor.image.analytics.none\": \"Nee\",\n \"admin/editor.image.analytics.promotionId\": \"Promotie-id\",\n \"admin/editor.image.analytics.promotionName\": \"Promotienaam\",\n \"admin/editor.image.analytics.promotionPosition\": \"Creatieve positie\",\n \"admin/editor.image.analytics.promotionProductId\": \"Product-ID\",\n \"admin/editor.image.analytics.promotionProductName\": \"Productnaam\",\n \"admin/editor.image.analytics.provide\": \"Ja\",\n \"admin/editor.image.analytics.title\": \"Analytics-gebeurtenis\",\n \"admin/editor.store-image.alt.title\": \"Alternatieve tekst\",\n \"admin/editor.store-image.fetchpriority.auto\": \"Laat de browser de prioriteit bepalen\",\n \"admin/editor.store-image.fetchpriority.high\": \"Hoge prioriteit\",\n \"admin/editor.store-image.fetchpriority.low\": \"Lage prioriteit\",\n \"admin/editor.store-image.fetchpriority.title\": \"Hint voor prioriteit ophalen\",\n \"admin/editor.store-image.loading.eager\": \"Wanneer de pagina wordt geladen\",\n \"admin/editor.store-image.loading.lazy\": \"Wanneer dichter bij de viewport\",\n \"admin/editor.store-image.loading.title\": \"Laden van strategie\",\n \"admin/editor.store-image.src.title\": \"Afbeelding\",\n \"admin/editor.store-image.title.description\": \"Titel die moet worden weergegeven bij zweven\",\n \"admin/editor.store-image.title.title\": \"Titel van de afbeelding\",\n \"admin/editor.store-image.title\": \"Afbeelding\"\n}\n```"
}
] |
code_store-image_c8f199b9
|
[
{
"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 store-image/messages/es.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.image-list.description\": \"Mostrar una lista de imágenes\",\n \"admin/editor.image-list.height.title\": \"Altura máxima de cada imagen (px)\",\n \"admin/editor.image-list.images.description.title\": \"Texto alternativo de la imagen\",\n \"admin/editor.image-list.images.image.title\": \"Imagen\",\n \"admin/editor.image-list.images.link.noFollow.title\": \"Debe ser un enlace nofollow\",\n \"admin/editor.image-list.images.link.openNewTab.title\": \"Abrir en una nueva pestaña\",\n \"admin/editor.image-list.images.link.title.title\": \"Título del enlace\",\n \"admin/editor.image-list.images.link.url.title\": \"URL del enlace de la imagen\",\n \"admin/editor.image-list.images.mobileImage.title\": \"Imagen para móvil\",\n \"admin/editor.image-list.images.title.title\": \"Título de la imagen\",\n \"admin/editor.image-list.images.title\": \"Imágenes\",\n \"admin/editor.image-list.images.width.description\": \"Anchura de la imagen para una sola imagen (% o px)\",\n \"admin/editor.image-list.images.height.title\": \"Altura de la imagen\",\n \"admin/editor.image-list.images.height.description\": \"Altura de la imagen para una única imagen (px)\",\n \"admin/editor.image-list.images.width.title\": \"Anchura de la imagen\",\n \"admin/editor.image-list.title\": \"Lista de imágenes\",\n \"admin/editor.image-slider.description\": \"Control deslizante de imágenes\",\n \"admin/editor.image-slider.slider.infinite\": \"Infinito\",\n \"admin/editor.image-slider.slider.showNavigation\": \"Mostrar flechas de navegación\",\n \"admin/editor.image-slider.slider.showPaginationDots\": \"Mostrar puntos de paginación\",\n \"admin/editor.image-slider.slider.title\": \"Opciones del control deslizante\",\n \"admin/editor.image-slider.slider.usePagination\": \"Usar paginación\",\n \"admin/editor.image-slider.title\": \"Control deslizante de imágenes\",\n \"admin/editor.image.analytics.none\": \"No\",\n \"admin/editor.image.analytics.promotionId\": \"ID de la promoción\",\n \"admin/editor.image.analytics.promotionName\": \"Nombre de la promoción\",\n \"admin/editor.image.analytics.promotionPosition\": \"Posición creativa\",\n \"admin/editor.image.analytics.promotionProductId\": \"ID del producto\",\n \"admin/editor.image.analytics.promotionProductName\": \"Nombre del producto\",\n \"admin/editor.image.analytics.provide\": \"Sí\",\n \"admin/editor.image.analytics.title\": \"Evento de Analytics\",\n \"admin/editor.store-image.alt.title\": \"Texto alternativo\",\n \"admin/editor.store-image.fetchpriority.auto\": \"Dejar que el navegador decida la prioridad\",\n \"admin/editor.store-image.fetchpriority.high\": \"Prioridad alta\",\n \"admin/editor.store-image.fetchpriority.low\": \"Prioridad baja\",\n \"admin/editor.store-image.fetchpriority.title\": \"Sugerencia de prioridad de carga\",\n \"admin/editor.store-image.loading.eager\": \"Al cargar la página\",\n \"admin/editor.store-image.loading.lazy\": \"Al estar cerca de la zona de visualización\",\n \"admin/editor.store-image.loading.title\": \"Estrategia de carga\",\n \"admin/editor.store-image.src.title\": \"Imagen\",\n \"admin/editor.store-image.title.description\": \"Título que se mostrará al pasar el mouse sobre la imagen\",\n \"admin/editor.store-image.title.title\": \"Título de la imagen\",\n \"admin/editor.store-image.title\": \"Imagen\"\n}\n```"
}
] |
code_store-image_0c394cb6
|
[
{
"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 store-image/docs/README.md from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/store-image) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Store Image\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\nThe Store Image app exports the `list-context.image-list` block, which is responsible for the image content in the store theme.\n\n\n\n## Configuring the store image\n\n1. Add the `store-image` app to your theme dependencies in the `manifest.json`. For example:\n\n```diff\n \"dependencies \": {\n+ \"vtex.store-image\": \"0.x\"\n }\n```\n\nYou can now use the `list-context.image-list` block exported by the Store Image app. This block allows you to display images in your store with more composability since you can use it along with other `list-context` blocks to create a more flexible and customizable image slider.\n\n2. In any desired theme template, add the `list-context.image-list` block, declaring the `slider-layout` as a child block. For example:\n\n```json\n \"list-context.image-list#demo\": {\n \"children\": [\"slider-layout#demo-images\"],\n \"props\": {\n \"preload\": true,\n \"height\": 650,\n \"images\": [\n {\n \"loading\": \"eager\",\n \"image\": \"https://storecomponents.vteximg.com.br/arquivos/banner-infocard2.png\",\n \"description\": \"something something\"\n },\n {\n \"loading\": \"lazy\",\n \"image\": \"https://storecomponents.vteximg.com.br/assets/vtex.file-manager-graphql/images/Group%207%20(1)%20(1)%20(1)%20(1)%20(1)___c6b3ed853fb16a08b265753b50e0c57a.png\",\n \"description\": \"something something\"\n }\n ]\n }\n },\n\n \"slider-layout#demo-images\": {\n \"props\": {\n \"itemsPerPage\": {\n \"desktop\": 1,\n \"tablet\": 1,\n \"phone\": 1\n },\n \"infinite\": true\n }\n },\n```\n\nNote that the `slider-layout` block exported from the Slider Layout app is a child block of `list-context.image-list`. It defines which images will be displayed and their behavior when rendered.\n\n### `list-context.image-list` props\n\n| Prop name | Type | Description | Default value |\n| ----------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------- | ------------- |\n| `images` | `array` | Array of objects that declares all the images to be rendered. | `undefined` |\n| `height` | `number` | Image height for all images declared in the `image` object (in `px`). | `undefined` |\n| `preload` | `boolean` | Preloads the first image in a list, prioritizing the image display over other assets. | `false` |\n| `experimentalSetExplicitDimensions` | `boolean` | Sets explicit `width` and/or `height` attributes for an image, if `width` and/or `height` props are provided in `px`. |\n\n### `image-list` props\n\n| Prop name | Type | Description | Default value |\n| -------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------- | ------------- |\n| `images` | `array` | Array of objects that declares all the images to be rendered. | `undefined` |\n| `height` | `number` | Image height for all images declared in the `image` object (in `px`). | `undefined` |\n| `experimentalPreventLayoutShift` | `boolean` | Wraps the image in a `<span>` tag with a preset `width` and/or `height` to minimize layout shift during page loading. |\n\n- **`images` array:**\n\n| Prop name | Type | Description | Default value |\n| ---------------------- | ------------------- | --------------------------------------------------------------------------------------------------- | ------------- |\n| `image` | `string` | Image URL. | `undefined` |\n| `mobileImage` | `string` | Mobile image URL. | `undefined` |\n| `description` | `string` | Image description. | `undefined` |\n| `link` | `object` | Links a URL to the image being rendered. | `undefined` |\n| `width` | `string` / `number` | Image width (in `%` or `px`). | `100%` |\n| `loading` | `string` | Loading strategy, either when the page loads (`'eager'`) or when closer to the viewport (`'lazy'`). | `'eager'` |\n| `fetchpriority` | `string` | The fetch priority hint (`'high'`, `'low'`, or `'auto'`). | `'auto'` |\n| `analyticsProperties` | `string` | Whether analytics props should be set (`'provided'`) or not (`'none'`). | `'none'` |\n| `promotionId` | `string` | The ID of the promotion associated with the event. | `undefined` |\n| `promotionName` | `string` | The name of the promotion associated with the event. | `undefined` |\n| `promotionPosition` | `string` | The name of the promotional creative slot associated with the event. | `undefined` |\n| `promotionProductId` | `string` | The ID of the product associated with the event. | `undefined` |\n| `promotionProductName` | `string` | The name of the product associated with the event. | `undefined` |\n\n- **`link` object:**\n\n| Prop name | Type | Description | Default value |\n| ------------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |\n| `url` | `string` | URL users will be redirected to when they click the image. | `undefined` |\n| `noFollow` | `boolean` | Whether the page owner endorses the linked URL the user was navigating on, i.e., if there is a business relationship between both pages (`true`) or (`false`). | `false` |\n| `openNewTab` | `string` | Whether a new tab will be opened on the browser (`true`) or (`false`). | `undefined` |\n| `title` | `string` | Text label used to identify the image in the Admin Site Editor. | `undefined` |\n\n> ℹ️ Use the **Admin Site Editor** to manage all images declared in the `list-context.image-list` block.\n\n## Customization\n\nThe block does not have CSS handles for specific customization.\n\nAll CSS handles available for the Image block are available for the `slider-layout` block. Take a look at the Customization section in the [**Slider Layout documentation**](https://developers.vtex.com/docs/apps/vtex.slider-layout). Note that the `image-slider` uses our `vtex.slider-layout` app, so all the CSS namespaces defined by it are also available for `image-slider`. Learn more in [Slider Layout](https://developers.vtex.com/docs/apps/vtex.slider-layout).\n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\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```"
}
] |
code_store-image_8c674e97
|
[
{
"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 store-image/react/ImageList.tsx from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport type { PropsWithChildren } from 'react'\nimport { useDevice } from 'vtex.device-detector'\nimport { ListContextProvider, useListContext } from 'vtex.list-context'\n\nimport { IMAGE_LIST_SCHEMA } from './modules/schema'\nimport { getImagesAsJSXList } from './modules/imageAsList'\nimport type { ImagesSchema } from './ImageTypes'\n\nexport interface ImageListProps {\n images: ImagesSchema\n height?: number | string\n preload?: boolean\n experimentalPreventLayoutShift?: boolean\n experimentalSetExplicitDimensions?: boolean\n}\n\nfunction ImageList({\n images,\n height = 420,\n children,\n preload,\n experimentalPreventLayoutShift,\n experimentalSetExplicitDimensions,\n}: PropsWithChildren<ImageListProps>) {\n const list = useListContext()?.list ?? []\n const { isMobile } = useDevice()\n\n const imageListContent = getImagesAsJSXList(\n images,\n isMobile,\n height,\n preload,\n experimentalPreventLayoutShift,\n experimentalSetExplicitDimensions\n )\n\n const newListContextValue = list.concat(imageListContent)\n\n return (\n <ListContextProvider list={newListContextValue}>\n {children}\n </ListContextProvider>\n )\n}\n\nImageList.schema = IMAGE_LIST_SCHEMA\n\nexport default ImageList\n\n```"
}
] |
code_store-image_2be2ab6c
|
[
{
"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 store-image/react/ImageTypes.ts from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ImageProps } from './Image'\nimport type { ImageListProps } from './ImageList'\nimport type { ImageSliderProps } from './ImageSlider'\n\nexport { ImageProps, ImageListProps, ImageSliderProps }\n\nexport interface ImageSchema {\n src?: string\n link?: Link\n alt?: string\n title?: string\n analyticsProperties?: 'none' | 'provide'\n promotionId?: string\n promotionName?: string\n promotionPosition?: string\n promotionProductId?: string\n promotionProductName?: string\n}\n\nexport type ImagesSchema = Array<{\n image: string\n mobileImage: string\n link?: Link\n title?: string\n description: string\n experimentalPreventLayoutShift?: boolean\n experimentalSetExplicitDimensions?: boolean\n loading?: 'eager' | 'lazy'\n width?: number | string\n height?: number | string\n analyticsProperties?: 'none' | 'provide'\n promotionId?: string\n promotionName?: string\n promotionPosition?: string\n promotionProductId?: string\n promotionProductName?: string\n}>\n\ninterface Link {\n url: string\n attributeNofollow: boolean\n attributeTitle?: string\n /**\n * These two properties need to both exist because\n * there was a mismatch in the API defined by this component,\n * which exposes a openNewTab prop, and the native link type\n * from vtex.native-types, which expects a newTab property\n * instead of openNewTab.\n */\n openNewTab?: boolean\n newTab?: boolean\n}\n\nexport interface SliderConfig {\n itemsPerPage: {\n desktop: number\n tablet: number\n phone: number\n }\n showNavigationArrows: 'mobileOnly' | 'desktopOnly' | 'always' | 'never'\n showPaginationDots: 'mobileOnly' | 'desktopOnly' | 'always' | 'never'\n usePagination: boolean\n infinite: boolean\n}\n\n```"
}
] |
code_store-image_a906d399
|
[
{
"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 store-image/react/package.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"lint\": \"tsc --noEmit && eslint --quiet --fix --ext ts,tsx .\",\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"react\": \"^16.13.1\",\n \"react-intl\": \"^4.5.0\"\n },\n \"devDependencies\": {\n \"@types/jest\": \"^25.2.1\",\n \"@types/react\": \"^16.9.34\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@1.0.1/public/@types/vtex.css-handles\",\n \"vtex.device-detector\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.device-detector@0.2.6/public/@types/vtex.device-detector\",\n \"vtex.list-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.list-context@0.2.0/public/@types/vtex.list-context\",\n \"vtex.native-types\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.native-types@0.10.1/public/@types/vtex.native-types\",\n \"vtex.on-view\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.on-view@1.0.0/public/@types/vtex.on-view\",\n \"vtex.pixel-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-manager@1.9.0/public/@types/vtex.pixel-manager\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.135.1/public/@types/vtex.render-runtime\",\n \"vtex.slider-layout\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.slider-layout@0.24.6/public/@types/vtex.slider-layout\",\n \"vtex.store-image\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-image@0.22.3/public/@types/vtex.store-image\"\n },\n \"version\": \"0.24.0\"\n}\n\n```"
}
] |
code_store-image_6ba890cb
|
[
{
"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 store-image/react/ImageListWithoutContext.tsx from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useDevice } from 'vtex.device-detector'\n\nimport { IMAGE_LIST_SCHEMA } from './modules/schema'\nimport { getImagesAsJSXList } from './modules/imageAsList'\nimport type { ImageListProps } from './ImageList'\n\nconst ImageListWithoutContext = (props: ImageListProps) => {\n const { images, height = '420' } = props\n const { isMobile } = useDevice()\n\n const imageListContent = getImagesAsJSXList(images, isMobile, height)\n\n return <React.Fragment>{imageListContent}</React.Fragment>\n}\n\nImageListWithoutContext.schema = IMAGE_LIST_SCHEMA\n\nexport default ImageListWithoutContext\n\n```"
}
] |
code_store-image_5ad1f362
|
[
{
"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 store-image/react/Image.tsx from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment, useState, useRef, useEffect } from 'react'\nimport type { ImgHTMLAttributes, RefObject } from 'react'\nimport { useOnView } from 'vtex.on-view'\nimport { useCssHandles } from 'vtex.css-handles'\nimport type { CssHandlesTypes } from 'vtex.css-handles'\nimport { useIntl, defineMessages } from 'react-intl'\nimport { formatIOMessage } from 'vtex.native-types'\nimport { Link } from 'vtex.render-runtime'\nimport { usePixel } from 'vtex.pixel-manager'\n\nimport type { ImageSchema } from './ImageTypes'\n\nconst CSS_HANDLES = ['imageElement', 'imageElementLink'] as const\n\nexport interface ImageProps\n extends ImageSchema,\n ImgHTMLAttributes<HTMLImageElement> {\n maxWidth?: string | number\n maxHeight?: string | number\n minWidth?: string | number\n minHeight?: string | number\n blockClass?: string\n experimentalPreventLayoutShift?: boolean\n experimentalSetExplicitDimensions?: boolean\n classes?: CssHandlesTypes.CustomClasses<typeof CSS_HANDLES>\n preload?: boolean\n loading?: 'eager' | 'lazy'\n fetchpriority?: 'high' | 'low' | 'auto'\n width?: string | number\n height?: string | number\n specificHeight?: string | number\n /**\n * Warning: This property is for internal usage, please avoid using it.\n * This property is used when the Image is children of the SliderTrack component and it prevents triggering the promoView event twice for cloned images.\n * https://github.com/vtex-apps/slider-layout/blob/master/react/components/SliderTrack.tsx\n */\n __isDuplicated?: boolean\n}\n\nconst useImageLoad = (\n imageRef: RefObject<HTMLImageElement | null>,\n { bailOut = false } = {}\n) => {\n const [isLoaded, setLoaded] = useState(false)\n\n useEffect(() => {\n if (bailOut) {\n return\n }\n\n const imageElement = imageRef.current\n\n if (!imageElement) {\n return\n }\n\n if (imageElement.complete) {\n setLoaded(true)\n\n return\n }\n\n const handleLoad = () => {\n setLoaded(true)\n }\n\n imageElement.addEventListener('load', handleLoad)\n\n return () => {\n imageElement.removeEventListener('load', handleLoad)\n }\n }, [imageRef, bailOut])\n\n return isLoaded\n}\n\nfunction Image(props: ImageProps) {\n const {\n src,\n alt = '',\n maxWidth,\n maxHeight,\n minWidth,\n minHeight,\n width,\n height: genericHeight,\n specificHeight,\n srcSet = '',\n sizes = '',\n link,\n title,\n experimentalPreventLayoutShift,\n experimentalSetExplicitDimensions,\n analyticsProperties = 'none',\n promotionId,\n promotionName,\n promotionPosition,\n promotionProductId,\n promotionProductName,\n classes,\n preload,\n loading = 'eager',\n fetchpriority = 'auto',\n // eslint-disable-next-line\n __isDuplicated,\n } = props\n\n const imageRef = useRef<HTMLImageElement | null>(null)\n const isLoaded = useImageLoad(imageRef, {\n bailOut: !experimentalPreventLayoutShift,\n })\n\n const intl = useIntl()\n const { handles } = useCssHandles(CSS_HANDLES, {\n migrationFrom: 'vtex.store-components@3.x',\n classes,\n })\n\n const imageDimensionsWithoutExplicitDimensions = {\n minWidth,\n minHeight,\n maxWidth,\n maxHeight,\n }\n\n const imageDimensionsWithExplicitDimensions = {\n ...imageDimensionsWithoutExplicitDimensions,\n height: genericHeight,\n width,\n }\n\n const placeholderSize =\n specificHeight ?? genericHeight ?? maxHeight ?? minHeight ?? 'auto'\n\n const allowedExplicitDimensionsRegex = /(auto|inherit|initial|unset)|[^\\d]/g\n\n const explicitDimensions = (dimension: string | number | undefined) =>\n dimension !== '' && dimension\n ? dimension.toString().replace(allowedExplicitDimensionsRegex, '$1')\n : null\n\n const widthWithoutUnits = explicitDimensions(width)\n\n const heightWithoutUnits =\n explicitDimensions(specificHeight) ??\n explicitDimensions(genericHeight) ??\n explicitDimensions(maxHeight)\n\n const hasPercentage = (dimension: string | number | undefined) =>\n dimension?.toString().includes('%')\n\n const explicitDimensionsAreAvailable =\n !!width &&\n (!!specificHeight || !!maxHeight || !!genericHeight) &&\n !hasPercentage(width) &&\n (!hasPercentage(specificHeight) ||\n !hasPercentage(maxHeight) ||\n !hasPercentage(genericHeight))\n\n const formattedSrc = formatIOMessage({ id: src, intl })\n const formattedAlt = formatIOMessage({ id: alt, intl })\n\n const imgElement = (\n <img\n title={title}\n sizes={sizes}\n srcSet={srcSet}\n src={typeof formattedSrc === 'string' ? formattedSrc : ''}\n alt={typeof formattedAlt === 'string' ? formattedAlt : ''}\n ref={imageRef}\n className={handles.imageElement}\n loading={loading}\n fetchpriority={fetchpriority}\n {...(experimentalSetExplicitDimensions && explicitDimensionsAreAvailable\n ? {\n width: widthWithoutUnits ?? width ?? 'auto',\n height: heightWithoutUnits ?? 'auto',\n style: imageDimensionsWithoutExplicitDimensions,\n }\n : { style: imageDimensionsWithExplicitDimensions })}\n {...(preload\n ? {\n 'data-vtex-preload': 'true',\n }\n : {})}\n />\n )\n\n /**\n * To understand why we need to check for both newTab and openNewTab\n * properties, check the Image type definition at './typings/image.d.ts'.\n */\n const shouldOpenLinkInNewTab = link?.newTab ?? link?.openNewTab\n\n const { push } = usePixel()\n\n const promotionEventData =\n analyticsProperties === 'provide'\n ? {\n id: promotionId,\n name: promotionName,\n creative: formattedSrc,\n position: promotionPosition,\n products: [\n {\n productId: promotionProductId,\n productName: promotionProductName,\n },\n ],\n }\n : undefined\n\n const formattedLink = formatIOMessage({ id: link?.url, intl })\n const formattedTitle = formatIOMessage({ id: link?.attributeTitle, intl })\n\n const maybeLink = link?.url ? (\n // The onClick function and the <Link> component are necessary,\n // knowing this, it seems good to disable the anchor-is-valid rule.\n // eslint-disable-next-line jsx-a11y/anchor-is-valid\n <Link\n to={typeof formattedLink === 'string' ? formattedLink : ''}\n title={typeof formattedTitle === 'string' ? formattedTitle : ''}\n rel={link.attributeNofollow ? 'nofollow' : ''}\n target={shouldOpenLinkInNewTab ? '_blank' : undefined}\n className={handles.imageElementLink}\n onClick={() => {\n if (analyticsProperties === 'none') return\n\n push({ event: 'promotionClick', promotions: [promotionEventData] })\n }}\n >\n {imgElement}\n </Link>\n ) : (\n <Fragment>{imgElement}</Fragment>\n )\n\n useOnView({\n ref: imageRef,\n onView: () => {\n if (analyticsProperties === 'none' || __isDuplicated) return\n\n push({\n event: 'promoView',\n promotions: [promotionEventData],\n })\n },\n once: true,\n })\n\n return experimentalPreventLayoutShift ? (\n <span\n className=\"dib\"\n style={{\n height: isLoaded ? 'auto' : placeholderSize,\n }}\n >\n {maybeLink}\n </span>\n ) : (\n maybeLink\n )\n}\n\nconst messages = defineMessages({\n title: {\n id: 'admin/editor.store-image.title',\n },\n})\n\nImage.schema = {\n title: messages.title.id,\n}\n\nImage.cssHandles = CSS_HANDLES\n\nexport default Image\n\n```"
}
] |
code_store-image_d3b43dd6
|
[
{
"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 store-image/react/ImageSlider.tsx from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { defineMessages, useIntl } from 'react-intl'\nimport { SliderLayout } from 'vtex.slider-layout'\nimport { useDevice } from 'vtex.device-detector'\nimport { formatIOMessage } from 'vtex.native-types'\n\nimport Image from './Image'\nimport type { SliderConfig, ImagesSchema } from './ImageTypes'\n\nexport interface ImageSliderProps {\n images: ImagesSchema\n height: number\n sliderLayoutConfig: SliderConfig\n preload?: boolean\n}\n\nfunction getImageUrl(isMobile: boolean, image: string, mobileImage: string) {\n return !!mobileImage && isMobile ? mobileImage : image\n}\n\nfunction ImageSlider(props: ImageSliderProps) {\n const {\n images,\n height,\n sliderLayoutConfig = {\n itemsPerPage: {\n desktop: 1,\n tablet: 1,\n phone: 1,\n },\n infinite: true,\n showNavigationArrows: 'always',\n showPaginationDots: 'always',\n usePagination: true,\n },\n preload,\n } = props\n\n const { isMobile } = useDevice()\n const intl = useIntl()\n\n return (\n <SliderLayout {...sliderLayoutConfig} totalItems={images.length}>\n {images.map(\n ({ image, mobileImage, link, description, ...otherProps }, idx) => {\n const formattedImage = formatIOMessage({ id: image, intl })\n const formattedMobileImage = formatIOMessage({\n id: mobileImage,\n intl,\n })\n\n const imageUrl = getImageUrl(\n isMobile,\n typeof formattedImage === 'string' ? formattedImage : '',\n typeof formattedMobileImage === 'string' ? formattedMobileImage : ''\n )\n\n const formattedAltDescription = formatIOMessage({\n id: description,\n intl,\n })\n\n const formattedUrl = link\n ? formatIOMessage({ id: link.url, intl })\n : ''\n\n const formattedTitle = link\n ? formatIOMessage({\n id: link.attributeTitle,\n intl,\n })\n : ''\n\n const imageLink = link && {\n ...link,\n url: typeof formattedUrl === 'string' ? formattedUrl : '',\n title: typeof formattedTitle === 'string' ? formattedTitle : '',\n }\n\n return (\n <Image\n key={idx}\n src={imageUrl}\n alt={\n typeof formattedAltDescription === 'string'\n ? formattedAltDescription\n : ''\n }\n link={imageLink}\n maxHeight={height}\n width=\"100%\"\n preload={preload && idx === 0}\n {...otherProps}\n />\n )\n }\n )}\n </SliderLayout>\n )\n}\n\nconst messages = defineMessages({\n title: { id: 'admin/editor.image-slider.title', defaultMessage: '' },\n description: {\n id: 'admin/editor.image-slider.description',\n defaultMessage: '',\n },\n imagesImageTitle: {\n id: 'admin/editor.image-list.images.image.title',\n defaultMessage: '',\n },\n imagesMobileImageTitle: {\n id: 'admin/editor.image-list.images.mobileImage.title',\n defaultMessage: '',\n },\n imagesImageDescription: {\n id: 'admin/editor.image-list.images.description.title',\n defaultMessage: '',\n },\n imagesImageAttributeTitle: {\n id: 'admin/editor.image-list.images.title.title',\n defaultMessage: '',\n },\n imagesImageLinkUrl: {\n id: 'admin/editor.image-list.images.link.url.title',\n defaultMessage: '',\n },\n imagesImageLinkOpenNewTab: {\n id: 'admin/editor.image-list.images.link.openNewTab.title',\n defaultMessage: '',\n },\n imagesImageLinkNoFollow: {\n id: 'admin/editor.image-list.images.link.noFollow.title',\n defaultMessage: '',\n },\n imagesImageLinkTitle: {\n id: 'admin/editor.image-list.images.link.title.title',\n defaultMessage: '',\n },\n imagesTitle: {\n id: 'admin/editor.image-list.images.title',\n defaultMessage: '',\n },\n heightTitle: {\n id: 'admin/editor.image-list.height.title',\n defaultMessage: '',\n },\n sliderTitle: {\n id: 'admin/editor.image-slider.slider.title',\n defaultMessage: '',\n },\n sliderInfinite: {\n id: 'admin/editor.image-slider.slider.infinite',\n defaultMessage: '',\n },\n sliderShowNavigation: {\n id: 'admin/editor.image-slider.slider.showNavigation',\n defaultMessage: '',\n },\n sliderShowPaginationDots: {\n id: 'admin/editor.image-slider.slider.showPaginationDots',\n defaultMessage: '',\n },\n sliderUsePagination: {\n id: 'admin/editor.image-slider.slider.usePagination',\n defaultMessage: '',\n },\n})\n\nImageSlider.schema = {\n title: messages.title.id,\n description: messages.description.id,\n type: 'object',\n properties: {\n height: {\n default: 420,\n enum: [420, 440],\n isLayout: true,\n title: messages.heightTitle.id,\n type: 'number',\n },\n sliderLayoutConfig: {\n title: messages.sliderTitle.id,\n properties: {\n infinite: {\n default: true,\n title: messages.sliderInfinite.id,\n type: 'boolean',\n },\n showNavigationArrows: {\n default: 'always',\n enum: ['mobileOnly', 'desktopOnly', 'always', 'never'],\n title: messages.sliderShowNavigation.id,\n type: 'string',\n },\n showPaginationDots: {\n default: 'always',\n enum: ['mobileOnly', 'desktopOnly', 'always', 'never'],\n title: messages.sliderShowPaginationDots.id,\n type: 'string',\n },\n usePagination: {\n default: true,\n title: messages.sliderUsePagination.id,\n type: 'boolean',\n },\n },\n type: 'object',\n },\n },\n}\n\nexport default ImageSlider\n\n```"
}
] |
code_store-image_34dfdceb
|
[
{
"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 store-image/store/contentSchemas.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"definitions\": {\n \"Image\": {\n \"title\": \"admin/editor.store-image.title\",\n \"properties\": {\n \"src\": {\n \"title\": \"admin/editor.image.src.title\",\n \"$ref\": \"app:vtex.native-types#/definitions/url\",\n \"default\": \"\",\n \"widget\": {\n \"ui:widget\": \"image-uploader\"\n }\n },\n \"link\": {\n \"$ref\": \"app:vtex.native-types#/definitions/link\",\n \"default\": \"\"\n },\n \"alt\": {\n \"title\": \"admin/editor.image.alt.title\",\n \"$ref\": \"app:vtex.native-types#/definitions/text\",\n \"default\": \"\"\n },\n \"title\": {\n \"title\": \"admin/editor.image.title.title\",\n \"description\": \"admin/editor.image.title.description\",\n \"$ref\": \"app:vtex.native-types#/definitions/text\",\n \"default\": \"\"\n },\n \"loading\": {\n \"title\": \"admin/editor.store-image.loading.title\",\n \"enum\": [\"eager\", \"lazy\"],\n \"enumNames\": [\n \"admin/editor.store-image.loading.eager\",\n \"admin/editor.store-image.loading.lazy\"\n ],\n \"widget\": {\n \"ui:widget\": \"radio\"\n },\n \"default\": \"eager\"\n },\n \"fetchpriority\": {\n \"title\": \"admin/editor.store-image.fetchpriority.title\",\n \"enum\": [\"high\", \"low\", \"auto\"],\n \"enumNames\": [\n \"admin/editor.store-image.fetchpriority.high\",\n \"admin/editor.store-image.fetchpriority.low\",\n \"admin/editor.store-image.fetchpriority.auto\"\n ],\n \"widget\": {\n \"ui:widget\": \"radio\"\n },\n \"default\": \"auto\"\n },\n \"analyticsProperties\": {\n \"title\": \"admin/editor.image.analytics.title\",\n \"description\": \"admin/editor.image.analytics.description\",\n \"enum\": [\"none\", \"provide\"],\n \"enumNames\": [\n \"admin/editor.image.analytics.none\",\n \"admin/editor.image.analytics.provide\"\n ],\n \"widget\": {\n \"ui:widget\": \"radio\"\n },\n \"default\": \"none\"\n }\n },\n \"dependencies\": {\n \"analyticsProperties\": {\n \"oneOf\": [\n {\n \"properties\": {\n \"analyticsProperties\": {\n \"enum\": [\"provide\"]\n },\n \"promotionId\": {\n \"title\": \"admin/editor.image.analytics.promotionId\",\n \"type\": \"string\",\n \"default\": \"\"\n },\n \"promotionName\": {\n \"title\": \"admin/editor.image.analytics.promotionName\",\n \"type\": \"string\",\n \"default\": \"\"\n },\n \"promotionPosition\": {\n \"title\": \"admin/editor.image.analytics.promotionPosition\",\n \"type\": \"string\",\n \"default\": \"\"\n },\n \"promotionProductId\": {\n \"title\": \"admin/editor.image.analytics.promotionProductId\",\n \"type\": \"string\",\n \"default\": \"\"\n },\n \"promotionProductName\": {\n \"title\": \"admin/editor.image.analytics.promotionProductName\",\n \"type\": \"string\",\n \"default\": \"\"\n }\n }\n },\n {\n \"properties\": {\n \"analyticsProperties\": {\n \"enum\": [\"none\"]\n }\n }\n }\n ]\n }\n }\n },\n \"Images\": {\n \"type\": \"array\",\n \"title\": \"admin/editor.image-list.images.title\",\n \"items\": {\n \"properties\": {\n \"image\": {\n \"$ref\": \"app:vtex.native-types#/definitions/url\",\n \"default\": \"\",\n \"title\": \"admin/editor.image-list.images.image.title\",\n \"widget\": {\n \"ui:widget\": \"image-uploader\"\n }\n },\n \"mobileImage\": {\n \"$ref\": \"app:vtex.native-types#/definitions/url\",\n \"default\": \"\",\n \"title\": \"admin/editor.image-list.images.mobileImage.title\",\n \"widget\": {\n \"ui:widget\": \"image-uploader\"\n }\n },\n \"description\": {\n \"$ref\": \"app:vtex.native-types#/definitions/text\",\n \"default\": \"\",\n \"title\": \"admin/editor.image-list.images.description.title\"\n },\n \"title\": {\n \"title\": \"admin/editor.image-list.images.title.title\",\n \"$ref\": \"app:vtex.native-types#/definitions/text\",\n \"default\": \"\"\n },\n \"link\": {\n \"default\": \"\",\n \"title\": \"\",\n \"$ref\": \"app:vtex.native-types#/definitions/link\"\n },\n \"width\": {\n \"title\": \"admin/editor.image-list.images.width.title\",\n \"description\": \"admin/editor.image-list.images.width.description\",\n \"$ref\": \"app:vtex.native-types#/definitions/text\",\n \"default\": \"100%\"\n },\n \"height\": {\n \"title\": \"admin/editor.image-list.images.height.title\",\n \"description\": \"admin/editor.image-list.images.height.description\",\n \"$ref\": \"app:vtex.native-types#/definitions/text\",\n \"default\": \"\"\n },\n \"loading\": {\n \"title\": \"admin/editor.store-image.loading.title\",\n \"enum\": [\"eager\", \"lazy\"],\n \"enumNames\": [\n \"admin/editor.store-image.loading.eager\",\n \"admin/editor.store-image.loading.lazy\"\n ],\n \"widget\": {\n \"ui:widget\": \"radio\"\n },\n \"default\": \"eager\"\n },\n \"fetchpriority\": {\n \"title\": \"admin/editor.store-image.fetchpriority.title\",\n \"enum\": [\"high\", \"low\", \"auto\"],\n \"enumNames\": [\n \"admin/editor.store-image.fetchpriority.high\",\n \"admin/editor.store-image.fetchpriority.low\",\n \"admin/editor.store-image.fetchpriority.auto\"\n ],\n \"widget\": {\n \"ui:widget\": \"radio\"\n },\n \"default\": \"auto\"\n },\n \"analyticsProperties\": {\n \"title\": \"admin/editor.image.analytics.title\",\n \"description\": \"admin/editor.image.analytics.description\",\n \"enum\": [\"none\", \"provide\"],\n \"enumNames\": [\n \"admin/editor.image.analytics.none\",\n \"admin/editor.image.analytics.provide\"\n ],\n \"widget\": {\n \"ui:widget\": \"radio\"\n },\n \"default\": \"none\"\n }\n },\n \"dependencies\": {\n \"analyticsProperties\": {\n \"oneOf\": [\n {\n \"properties\": {\n \"analyticsProperties\": {\n \"enum\": [\"provide\"]\n },\n \"promotionId\": {\n \"title\": \"admin/editor.image.analytics.promotionId\",\n \"type\": \"string\",\n \"default\": \"\"\n },\n \"promotionName\": {\n \"title\": \"admin/editor.image.analytics.promotionName\",\n \"type\": \"string\",\n \"default\": \"\"\n },\n \"promotionPosition\": {\n \"title\": \"admin/editor.image.analytics.promotionPosition\",\n \"type\": \"string\",\n \"default\": \"\"\n },\n \"promotionProductId\": {\n \"title\": \"admin/editor.image.analytics.promotionProductId\",\n \"type\": \"string\",\n \"default\": \"\"\n },\n \"promotionProductName\": {\n \"title\": \"admin/editor.image.analytics.promotionProductName\",\n \"type\": \"string\",\n \"default\": \"\"\n }\n }\n },\n {\n \"properties\": {\n \"analyticsProperties\": {\n \"enum\": [\"none\"]\n }\n }\n }\n ]\n }\n }\n }\n }\n }\n}\n\n```"
}
] |
code_store-image_c4cea9a1
|
[
{
"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 store-image/store/interfaces.json from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"image-new\": {\n \"component\": \"Image\",\n \"content\": {\n \"$ref\": \"app:vtex.store-image#/definitions/Image\"\n }\n },\n \"image-slider\": {\n \"component\": \"ImageSlider\",\n \"content\": {\n \"properties\": {\n \"images\": {\n \"$ref\": \"app:vtex.store-image#/definitions/Images\"\n }\n }\n }\n },\n \"image-list\": {\n \"component\": \"ImageListWithoutContext\",\n \"content\": {\n \"properties\": {\n \"images\": {\n \"$ref\": \"app:vtex.store-image#/definitions/Images\"\n }\n }\n }\n },\n \"list-context.image-list\": {\n \"component\": \"ImageList\",\n \"composition\": \"children\",\n \"allowed\": \"*\",\n \"content\": {\n \"properties\": {\n \"images\": {\n \"$ref\": \"app:vtex.store-image#/definitions/Images\"\n }\n }\n }\n }\n}\n\n```"
}
] |
code_store-image_16cff409
|
[
{
"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 store-image/react/typings/css.d.ts from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: CSSHandles\n export default css\n}\n\ninterface CSSHandles {\n imageElement: string\n}\n\n```"
}
] |
code_store-image_7329a15c
|
[
{
"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 store-image/react/typings/image.d.ts from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport React from 'react'\n\ndeclare module 'react' {\n interface ImgHTMLAttributes<T> extends HTMLAttributes<T> {\n fetchpriority?: 'high' | 'low' | 'auto'\n }\n}\n\n```"
}
] |
code_store-image_680182a3
|
[
{
"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 store-image/react/__tests__/index.test.tsx from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\ndescribe('Orders List Scenarios', () => {\n it('should work', () => {\n expect(1).toBe(1)\n })\n})\n\n```"
}
] |
code_store-image_829ea71f
|
[
{
"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 store-image/react/modules/schema.ts from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { defineMessages } from 'react-intl'\n\nconst IMAGE_LIST_MESSAGES = defineMessages({\n title: { id: 'admin/editor.image-list.title' },\n description: {\n id: 'admin/editor.image-list.description',\n },\n imagesImageTitle: {\n id: 'admin/editor.image-list.images.image.title',\n },\n imagesMobileImageTitle: {\n id: 'admin/editor.image-list.images.mobileImage.title',\n },\n imagesImageDescription: {\n id: 'admin/editor.image-list.images.description.title',\n },\n imagesImageAttributeTitle: {\n id: 'admin/editor.image-list.images.title.title',\n },\n imagesImageLinkUrl: {\n id: 'admin/editor.image-list.images.link.url.title',\n },\n imagesImageLinkOpenNewTab: {\n id: 'admin/editor.image-list.images.link.openNewTab.title',\n },\n imagesImageLinkNoFollow: {\n id: 'admin/editor.image-list.images.link.noFollow.title',\n },\n imagesImageLinkTitle: {\n id: 'admin/editor.image-list.images.link.title.title',\n },\n imagesTitle: {\n id: 'admin/editor.image-list.images.title',\n },\n heightTitle: {\n id: 'admin/editor.image-list.height.title',\n },\n widthTitle: {\n id: 'admin/editor.image-list.images.width.title',\n },\n widthDescription: {\n id: 'admin/editor.image-list.images.width.description',\n },\n analyticsTitle: {\n id: 'admin/editor.image.analytics.title',\n },\n analyticsNone: {\n id: 'admin/editor.image.analytics.none',\n },\n analyticsProvide: {\n id: 'admin/editor.image.analytics.provide',\n },\n analyticsPromotionId: {\n id: 'admin/editor.image.analytics.promotionId',\n },\n analyticsPromotionName: {\n id: 'admin/editor.image.analytics.promotionName',\n },\n analyticsPromotionPosition: {\n id: 'admin/editor.image.analytics.promotionPosition',\n },\n analyticspromotionProductId: {\n id: 'admin/editor.image.analytics.promotionProductId',\n },\n analyticspromotionProductName: {\n id: 'admin/editor.image.analytics.promotionProductName',\n },\n})\n\nexport const IMAGE_LIST_SCHEMA = {\n title: IMAGE_LIST_MESSAGES.title.id,\n description: IMAGE_LIST_MESSAGES.description.id,\n type: 'object',\n properties: {\n height: {\n default: '420',\n isLayout: false,\n title: IMAGE_LIST_MESSAGES.heightTitle.id,\n type: 'string',\n },\n },\n}\n\n```"
}
] |
code_store-image_0956a031
|
[
{
"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 store-image/react/modules/imageAsList.tsx from the store-image VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport Image from '../Image'\nimport type { ImagesSchema } from '../ImageTypes'\n\nexport const getImagesAsJSXList = (\n images: ImagesSchema,\n isMobile: boolean,\n height: number | string,\n preload?: boolean,\n experimentalPreventLayoutShift?: boolean,\n experimentalSetExplicitDimensions?: boolean\n // eslint-disable-next-line max-params\n) => {\n return images.map(\n (\n {\n image,\n mobileImage,\n description,\n experimentalPreventLayoutShift: experimentalPreventLayoutShiftChild,\n experimentalSetExplicitDimensions: experimentalSetExplicitDimensionsChild,\n width = '100%',\n height: specificHeight,\n ...props\n },\n idx\n ) => (\n <Image\n key={idx}\n src={isMobile && mobileImage ? mobileImage : image}\n alt={description}\n maxHeight={height}\n width={width}\n specificHeight={specificHeight}\n experimentalPreventLayoutShift={\n experimentalPreventLayoutShift ?? experimentalPreventLayoutShiftChild\n }\n experimentalSetExplicitDimensions={\n experimentalSetExplicitDimensions ??\n experimentalSetExplicitDimensionsChild\n }\n preload={preload && idx === 0}\n {...props}\n />\n )\n )\n}\n\n```"
}
] |
code_logrocket_bf9da665
|
[
{
"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 logrocket/docs/README.md from the logrocket VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# LogRocket\n\nVTEX LogRocket first-party app\n\n## How to install\n\nOpen a terminal and type:\n\n```sh\nvtex install vtex.logrocket@1.x\n```\n\nOpen your admin in the Apps section:\n\nhttps://YOURSTORENAME.myvtex.com/admin/apps/vtex.logrocket@1.0.0/setup\n\n\nFill in your LogRocket's Account ID and click save.\n\n### Setup in Cart and Checkout page\n\n**This step will not be needed in a couple of months!**\n\nOpen your admin in the Checkout section in the `checkout6-custom.js`:\n\nhttps://ACCOUNT.myvtexdev.com/admin/portal/#/sites/default/code/files/checkout6-custom.js\n\nAdd the following snippet in the file:\n\n```js\n// LogRocket\n(function() {\n var accountId = 'YOURACCOUNTID';\n var b=document.createElement(\"script\");b.onload=function(){window.LogRocket && window.LogRocket.init(accountId);};b.type=\"text/javascript\";b.crossOrigin=\"anonymous\";b.src=\"https://cdn.lr-ingest.io/LogRocket.min.js\";a=document.getElementsByTagName(\"script\")[0];a.parentNode.insertBefore(b,a);\n})();\n```\n\nClick Save.\n\n```"
}
] |
code_minicart-freeshipping-bar_8caab9c2
|
[
{
"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 minicart-freeshipping-bar/messages/pt.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/minicartbar.text0\": \"Temos frete grátis de:\",\n \"store/minicartbar.text1\": \"Complete seu pedido para ter\",\n \"store/minicartbar.text2\": \"Frete GRÁTIS 24h\",\n \"store/minicartbar.text3\": \"Só faltam\",\n \"store/minicartbar.text4\": \"Você ganhou frete grátis!\"\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_d6b1c6d0
|
[
{
"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 minicart-freeshipping-bar/messages/en.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/minicartbar.text0\": \"We have free shipping from: \",\n \"store/minicartbar.text1\": \"Complete your order to have\",\n \"store/minicartbar.text2\": \"FREE shipping\",\n \"store/minicartbar.text3\": \"Only left\",\n \"store/minicartbar.text4\": \"You won free shipping\"\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_2c571059
|
[
{
"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 minicart-freeshipping-bar/messages/it.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/minicartbar.text0\": \"SPEDIZIONE GRATUITA per ordini sopra: \",\n \"store/minicartbar.text1\": \"Completa il tuo ordine per usufruire della\",\n \"store/minicartbar.text2\": \"SPEDIZIONE GRATUITA\",\n \"store/minicartbar.text3\": \"Per usufruire della SPEDIZIONE GRATUITA mancano solo: \",\n \"store/minicartbar.text4\": \"Hai diritto alla SPEDIZIONE GRATUITA!\"\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_9bde7b0d
|
[
{
"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 minicart-freeshipping-bar/messages/ro.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/minicartbar.text0\": \"Avem livrare gratuită la: \",\n \"store/minicartbar.text1\": \"Completați comanda dvs. pentru \",\n \"store/minicartbar.text2\": \"Livrare GRATUITĂ\",\n \"store/minicartbar.text3\": \"Au rămas doar\",\n \"store/minicartbar.text4\": \"Ai câștigat livrare gratuită\"\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_967673af
|
[
{
"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 minicart-freeshipping-bar/messages/context.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/minicartbar.text0\": \"minicartbar.text0\",\n \"store/minicartbar.text1\": \"minicartbar.text1\",\n \"store/minicartbar.text2\": \"minicartbar.text2\",\n \"store/minicartbar.text3\": \"minicartbar.text3\",\n \"store/minicartbar.text4\": \"minicartbar.text4\"\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_70919ff0
|
[
{
"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 minicart-freeshipping-bar/messages/es.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/minicartbar.text0\": \"Tenemos envío gratis desde: \",\n \"store/minicartbar.text1\": \"¡Completa tu pedido para tener\",\n \"store/minicartbar.text2\": \"Envio GRATIS 24!\",\n \"store/minicartbar.text3\": \"¡Solo te quedan\",\n \"store/minicartbar.text4\": \"¡Ganaste envío gratis!\"\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_73788afe
|
[
{
"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 minicart-freeshipping-bar/messages/ar.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/minicartbar.text0\": \"لدينا شحن مجاني من: \",\n \"store/minicartbar.text1\": \"أكمل طلبك للحصول على\",\n \"store/minicartbar.text2\": \"شحن مجاني\",\n \"store/minicartbar.text3\": \"بقي فقط\",\n \"store/minicartbar.text4\": \"لقد فزت بشحن مجاني\"\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_0a7f1147
|
[
{
"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 minicart-freeshipping-bar/react/package.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"minicart-freeshipping-bar\",\n \"version\": \"2.1.3\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"axios\": \"^0.24.0\",\n \"@types/react-intl\": \"^3.0.0\",\n \"graphql\": \"^14.0.2\",\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\",\n \"react-async-script-loader\": \"^0.3.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/graphql\": \"^14.0.5\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"prop-types\": \"^15.7.2\",\n \"typescript\": \"3.9.7\",\n \"vtex.apps-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.apps-graphql@2.9.0/public/@types/vtex.apps-graphql\",\n \"vtex.checkout-resources\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-resources@0.49.0/public/@types/vtex.checkout-resources\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.format-currency\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.format-currency@0.4.1/public/@types/vtex.format-currency\",\n \"vtex.order-details\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-details@1.8.0/public/@types/vtex.order-details\",\n \"vtex.order-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.12.0/public/@types/vtex.order-manager\",\n \"vtex.pixel-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-manager@1.8.0/public/@types/vtex.pixel-manager\",\n \"vtex.react-portal\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.react-portal@0.4.1/public/@types/vtex.react-portal\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.4/public/@types/vtex.render-runtime\",\n \"vtex.session-client\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.session-client@1.0.2/public/@types/vtex.session-client\",\n \"vtex.shipping-estimate-translator\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.shipping-estimate-translator@2.2.3/public/@types/vtex.shipping-estimate-translator\",\n \"vtex.store-components\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-components@3.162.0/public/@types/vtex.store-components\",\n \"vtex.store-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.155.32/public/@types/vtex.store-graphql\",\n \"vtex.store-resources\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-resources@0.88.0/public/@types/vtex.store-resources\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.1/public/@types/vtex.styleguide\",\n \"vtexeurope.minicart-freeshipping-bar\": \"http://vtexeurope.vtexassets.com/_v/public/typings/v1/vtexeurope.minicart-freeshipping-bar@2.0.2/public/@types/vtexeurope.minicart-freeshipping-bar\"\n }\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_61365ec3
|
[
{
"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 minicart-freeshipping-bar/react/MinicartFreeshipping.ts from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport MinicartFreeshipping from './components/MinicartFreeshipping'\n\nexport default MinicartFreeshipping\n\n```"
}
] |
code_minicart-freeshipping-bar_490a7093
|
[
{
"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 minicart-freeshipping-bar/react/SessionTypes.ts from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface SessionSuccess {\n id: string\n namespaces: {\n [key: string]: Record<string, unknown>\n public: Record<string, { value: string }>\n }\n}\n\nexport interface SessionUnauthorized {\n type: 'Unauthorized'\n message: string\n}\n\nexport interface SessionForbidden {\n type: 'Forbidden'\n message: string\n}\n\nexport type Session = SessionSuccess | SessionUnauthorized | SessionForbidden\n\n```"
}
] |
code_minicart-freeshipping-bar_9a97f8fa
|
[
{
"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 minicart-freeshipping-bar/store/interfaces.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"minicart-bar\": {\n \"component\": \"MinicartFreeshipping\"\n }\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_5c20626a
|
[
{
"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 minicart-freeshipping-bar/public/metadata/messages/es-AR.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Mini Cart Free Shipping Bar\",\n \"headline\": \"La barra de envío gratuito de Mini Cart es un componente de MiniCart.v2 que añade una barra de progreso al minicart para mostrar el progreso que tiene el cliente para ganar el envío gratuito.\",\n \"overview\": \"Este bloque es sólo una guía visual, lo que significa que no hará ningún cálculo ni deducirá el importe del envío de su tienda. Deberías emparejar esta app con una promoción de envío gratuito del mismo importe El valor del importe, puede editarse dentro de la configuración de la app.\",\n \"features\": [\n \"Muestra el progreso que tiene un cliente para ganar el envío gratuito\",\n \"Compatible con 5 idiomas diferentes, entre ellos: Inglés, español, italiano, portugués y rumano.\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_407c2c38
|
[
{
"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 minicart-freeshipping-bar/public/metadata/messages/pt-BR.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Mini Cart Free Shipping Bar\",\n \"headline\": \"A barra de embarque do Mini Cart Free é um componente do MiniCart.v2 que adiciona uma barra de progresso ao minicarro a fim de exibir o progresso que um cliente tem para ganhar embarque gratuito.\",\n \"overview\": \"Este bloco é apenas um guia visual, o que significa que não fará nenhum cálculo ou deduzirá o valor do frete de sua loja. Você deve emparelhar este aplicativo com uma promoção de remessa gratuita da mesma quantia O valor da quantia, pode ser editado dentro das configurações do aplicativo.\",\n \"features\": [\n \"Mostrar quanto progresso um cliente tem para ganhar remessa gratuita\",\n \"Compatível com 5 idiomas diferentes, incluindo: inglês, espanhol, italiano, português e romeno.\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_5caca980
|
[
{
"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 minicart-freeshipping-bar/public/metadata/messages/en-US.json from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"Mini Cart Free Shipping Bar\",\n \"headline\": \"The Mini Cart Free Shipping Bar is a MiniCart.v2 component that adds a progress bar to the minicart in order to display how much progress a customer has to win free shipping.\",\n \"overview\": \"This block is only a visual guide, meaning it will not make any calculation or deduct the shipping amount from your store. You should pair this app with a Free Shipping Promotion of the same amount The amount value, can be edited inside the App Settings.\",\n \"features\": [\n \"Display how much progress a customer has to win free shipping\",\n \"Compatible with 5 different languages including: English, Spanish, Italian, Portuguese and Romanian.\"\n ],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_minicart-freeshipping-bar_f49b0f76
|
[
{
"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 minicart-freeshipping-bar/react/typings/vtex.session-client.d.ts from the minicart-freeshipping-bar VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.session-client'\ndeclare module 'vtex.session-client/*'\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.